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.7.11.  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 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
     64 */
     65 #ifndef SQLITE_DISABLE_LFS
     66 # define _LARGE_FILE       1
     67 # ifndef _FILE_OFFSET_BITS
     68 #   define _FILE_OFFSET_BITS 64
     69 # endif
     70 # define _LARGEFILE_SOURCE 1
     71 #endif
     72 
     73 /*
     74 ** Include the configuration header output by 'configure' if we're using the
     75 ** autoconf-based build
     76 */
     77 #ifdef _HAVE_SQLITE_CONFIG_H
     78 #include "config.h"
     79 #endif
     80 
     81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
     82 /************** Begin file sqliteLimit.h *************************************/
     83 /*
     84 ** 2007 May 7
     85 **
     86 ** The author disclaims copyright to this source code.  In place of
     87 ** a legal notice, here is a blessing:
     88 **
     89 **    May you do good and not evil.
     90 **    May you find forgiveness for yourself and forgive others.
     91 **    May you share freely, never taking more than you give.
     92 **
     93 *************************************************************************
     94 **
     95 ** This file defines various limits of what SQLite can process.
     96 */
     97 
     98 /*
     99 ** The maximum length of a TEXT or BLOB in bytes.   This also
    100 ** limits the size of a row in a table or index.
    101 **
    102 ** The hard limit is the ability of a 32-bit signed integer
    103 ** to count the size: 2^31-1 or 2147483647.
    104 */
    105 #ifndef SQLITE_MAX_LENGTH
    106 # define SQLITE_MAX_LENGTH 1000000000
    107 #endif
    108 
    109 /*
    110 ** This is the maximum number of
    111 **
    112 **    * Columns in a table
    113 **    * Columns in an index
    114 **    * Columns in a view
    115 **    * Terms in the SET clause of an UPDATE statement
    116 **    * Terms in the result set of a SELECT statement
    117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
    118 **    * Terms in the VALUES clause of an INSERT statement
    119 **
    120 ** The hard upper limit here is 32676.  Most database people will
    121 ** tell you that in a well-normalized database, you usually should
    122 ** not have more than a dozen or so columns in any table.  And if
    123 ** that is the case, there is no point in having more than a few
    124 ** dozen values in any of the other situations described above.
    125 */
    126 #ifndef SQLITE_MAX_COLUMN
    127 # define SQLITE_MAX_COLUMN 2000
    128 #endif
    129 
    130 /*
    131 ** The maximum length of a single SQL statement in bytes.
    132 **
    133 ** It used to be the case that setting this value to zero would
    134 ** turn the limit off.  That is no longer true.  It is not possible
    135 ** to turn this limit off.
    136 */
    137 #ifndef SQLITE_MAX_SQL_LENGTH
    138 # define SQLITE_MAX_SQL_LENGTH 1000000000
    139 #endif
    140 
    141 /*
    142 ** The maximum depth of an expression tree. This is limited to
    143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
    144 ** want to place more severe limits on the complexity of an
    145 ** expression.
    146 **
    147 ** A value of 0 used to mean that the limit was not enforced.
    148 ** But that is no longer true.  The limit is now strictly enforced
    149 ** at all times.
    150 */
    151 #ifndef SQLITE_MAX_EXPR_DEPTH
    152 # define SQLITE_MAX_EXPR_DEPTH 1000
    153 #endif
    154 
    155 /*
    156 ** The maximum number of terms in a compound SELECT statement.
    157 ** The code generator for compound SELECT statements does one
    158 ** level of recursion for each term.  A stack overflow can result
    159 ** if the number of terms is too large.  In practice, most SQL
    160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
    161 ** any limit on the number of terms in a compount SELECT.
    162 */
    163 #ifndef SQLITE_MAX_COMPOUND_SELECT
    164 # define SQLITE_MAX_COMPOUND_SELECT 500
    165 #endif
    166 
    167 /*
    168 ** The maximum number of opcodes in a VDBE program.
    169 ** Not currently enforced.
    170 */
    171 #ifndef SQLITE_MAX_VDBE_OP
    172 # define SQLITE_MAX_VDBE_OP 25000
    173 #endif
    174 
    175 /*
    176 ** The maximum number of arguments to an SQL function.
    177 */
    178 #ifndef SQLITE_MAX_FUNCTION_ARG
    179 # define SQLITE_MAX_FUNCTION_ARG 127
    180 #endif
    181 
    182 /*
    183 ** The maximum number of in-memory pages to use for the main database
    184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
    185 */
    186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
    187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
    188 #endif
    189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
    190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
    191 #endif
    192 
    193 /*
    194 ** The default number of frames to accumulate in the log file before
    195 ** checkpointing the database in WAL mode.
    196 */
    197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
    198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
    199 #endif
    200 
    201 /*
    202 ** The maximum number of attached databases.  This must be between 0
    203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
    204 ** is used internally to track attached databases.
    205 */
    206 #ifndef SQLITE_MAX_ATTACHED
    207 # define SQLITE_MAX_ATTACHED 10
    208 #endif
    209 
    210 
    211 /*
    212 ** The maximum value of a ?nnn wildcard that the parser will accept.
    213 */
    214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
    215 # define SQLITE_MAX_VARIABLE_NUMBER 999
    216 #endif
    217 
    218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
    219 ** imposed by the use of 16-bit offsets within each page.
    220 **
    221 ** Earlier versions of SQLite allowed the user to change this value at
    222 ** compile time. This is no longer permitted, on the grounds that it creates
    223 ** a library that is technically incompatible with an SQLite library
    224 ** compiled with a different limit. If a process operating on a database
    225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
    226 ** compiled with the default page-size limit will not be able to rollback
    227 ** the aborted transaction. This could lead to database corruption.
    228 */
    229 #ifdef SQLITE_MAX_PAGE_SIZE
    230 # undef SQLITE_MAX_PAGE_SIZE
    231 #endif
    232 #define SQLITE_MAX_PAGE_SIZE 65536
    233 
    234 
    235 /*
    236 ** The default size of a database page.
    237 */
    238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
    239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
    240 #endif
    241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    242 # undef SQLITE_DEFAULT_PAGE_SIZE
    243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    244 #endif
    245 
    246 /*
    247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
    248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
    249 ** device characteristics (sector-size and atomic write() support),
    250 ** SQLite may choose a larger value. This constant is the maximum value
    251 ** SQLite will choose on its own.
    252 */
    253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
    254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
    255 #endif
    256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
    258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    259 #endif
    260 
    261 
    262 /*
    263 ** Maximum number of pages in one database file.
    264 **
    265 ** This is really just the default value for the max_page_count pragma.
    266 ** This value can be lowered (or raised) at run-time using that the
    267 ** max_page_count macro.
    268 */
    269 #ifndef SQLITE_MAX_PAGE_COUNT
    270 # define SQLITE_MAX_PAGE_COUNT 1073741823
    271 #endif
    272 
    273 /*
    274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
    275 ** operator.
    276 */
    277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
    278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
    279 #endif
    280 
    281 /*
    282 ** Maximum depth of recursion for triggers.
    283 **
    284 ** A value of 1 means that a trigger program will not be able to itself
    285 ** fire any triggers. A value of 0 means that no trigger programs at all
    286 ** may be executed.
    287 */
    288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
    289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
    290 #endif
    291 
    292 /************** End of sqliteLimit.h *****************************************/
    293 /************** Continuing where we left off in sqliteInt.h ******************/
    294 
    295 /* Disable nuisance warnings on Borland compilers */
    296 #if defined(__BORLANDC__)
    297 #pragma warn -rch /* unreachable code */
    298 #pragma warn -ccc /* Condition is always true or false */
    299 #pragma warn -aus /* Assigned value is never used */
    300 #pragma warn -csu /* Comparing signed and unsigned */
    301 #pragma warn -spa /* Suspicious pointer arithmetic */
    302 #endif
    303 
    304 /* Needed for various definitions... */
    305 #ifndef _GNU_SOURCE
    306 # define _GNU_SOURCE
    307 #endif
    308 
    309 /*
    310 ** Include standard header files as necessary
    311 */
    312 #ifdef HAVE_STDINT_H
    313 #include <stdint.h>
    314 #endif
    315 #ifdef HAVE_INTTYPES_H
    316 #include <inttypes.h>
    317 #endif
    318 
    319 /*
    320 ** The following macros are used to cast pointers to integers and
    321 ** integers to pointers.  The way you do this varies from one compiler
    322 ** to the next, so we have developed the following set of #if statements
    323 ** to generate appropriate macros for a wide range of compilers.
    324 **
    325 ** The correct "ANSI" way to do this is to use the intptr_t type.
    326 ** Unfortunately, that typedef is not available on all compilers, or
    327 ** if it is available, it requires an #include of specific headers
    328 ** that vary from one machine to the next.
    329 **
    330 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
    331 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
    332 ** So we have to define the macros in different ways depending on the
    333 ** compiler.
    334 */
    335 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
    336 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
    337 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
    338 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
    339 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
    340 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
    341 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
    342 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
    343 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
    344 #else                          /* Generates a warning - but it always works */
    345 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
    346 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
    347 #endif
    348 
    349 /*
    350 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
    351 ** 0 means mutexes are permanently disable and the library is never
    352 ** threadsafe.  1 means the library is serialized which is the highest
    353 ** level of threadsafety.  2 means the libary is multithreaded - multiple
    354 ** threads can use SQLite as long as no two threads try to use the same
    355 ** database connection at the same time.
    356 **
    357 ** Older versions of SQLite used an optional THREADSAFE macro.
    358 ** We support that for legacy.
    359 */
    360 #if !defined(SQLITE_THREADSAFE)
    361 #if defined(THREADSAFE)
    362 # define SQLITE_THREADSAFE THREADSAFE
    363 #else
    364 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
    365 #endif
    366 #endif
    367 
    368 /*
    369 ** Powersafe overwrite is on by default.  But can be turned off using
    370 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
    371 */
    372 #ifndef SQLITE_POWERSAFE_OVERWRITE
    373 # define SQLITE_POWERSAFE_OVERWRITE 1
    374 #endif
    375 
    376 /*
    377 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
    378 ** It determines whether or not the features related to
    379 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
    380 ** be overridden at runtime using the sqlite3_config() API.
    381 */
    382 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
    383 # define SQLITE_DEFAULT_MEMSTATUS 1
    384 #endif
    385 
    386 /*
    387 ** Exactly one of the following macros must be defined in order to
    388 ** specify which memory allocation subsystem to use.
    389 **
    390 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
    391 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
    392 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
    393 **
    394 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
    395 ** assert() macro is enabled, each call into the Win32 native heap subsystem
    396 ** will cause HeapValidate to be called.  If heap validation should fail, an
    397 ** assertion will be triggered.
    398 **
    399 ** (Historical note:  There used to be several other options, but we've
    400 ** pared it down to just these three.)
    401 **
    402 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
    403 ** the default.
    404 */
    405 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
    406 # error "At most one of the following compile-time configuration options\
    407  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
    408 #endif
    409 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
    410 # define SQLITE_SYSTEM_MALLOC 1
    411 #endif
    412 
    413 /*
    414 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
    415 ** sizes of memory allocations below this value where possible.
    416 */
    417 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
    418 # define SQLITE_MALLOC_SOFT_LIMIT 1024
    419 #endif
    420 
    421 /*
    422 ** We need to define _XOPEN_SOURCE as follows in order to enable
    423 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
    424 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
    425 ** so it is omitted there.  See ticket #2673.
    426 **
    427 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
    428 ** implemented on some systems.  So we avoid defining it at all
    429 ** if it is already defined or if it is unneeded because we are
    430 ** not doing a threadsafe build.  Ticket #2681.
    431 **
    432 ** See also ticket #2741.
    433 */
    434 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
    435 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
    436 #endif
    437 
    438 /*
    439 ** The TCL headers are only needed when compiling the TCL bindings.
    440 */
    441 #if defined(SQLITE_TCL) || defined(TCLSH)
    442 # include <tcl.h>
    443 #endif
    444 
    445 /*
    446 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    447 ** Setting NDEBUG makes the code smaller and run faster.  So the following
    448 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
    449 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
    450 ** feature.
    451 */
    452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
    453 # define NDEBUG 1
    454 #endif
    455 
    456 /*
    457 ** The testcase() macro is used to aid in coverage testing.  When
    458 ** doing coverage testing, the condition inside the argument to
    459 ** testcase() must be evaluated both true and false in order to
    460 ** get full branch coverage.  The testcase() macro is inserted
    461 ** to help ensure adequate test coverage in places where simple
    462 ** condition/decision coverage is inadequate.  For example, testcase()
    463 ** can be used to make sure boundary values are tested.  For
    464 ** bitmask tests, testcase() can be used to make sure each bit
    465 ** is significant and used at least once.  On switch statements
    466 ** where multiple cases go to the same block of code, testcase()
    467 ** can insure that all cases are evaluated.
    468 **
    469 */
    470 #ifdef SQLITE_COVERAGE_TEST
    471 SQLITE_PRIVATE   void sqlite3Coverage(int);
    472 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
    473 #else
    474 # define testcase(X)
    475 #endif
    476 
    477 /*
    478 ** The TESTONLY macro is used to enclose variable declarations or
    479 ** other bits of code that are needed to support the arguments
    480 ** within testcase() and assert() macros.
    481 */
    482 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
    483 # define TESTONLY(X)  X
    484 #else
    485 # define TESTONLY(X)
    486 #endif
    487 
    488 /*
    489 ** Sometimes we need a small amount of code such as a variable initialization
    490 ** to setup for a later assert() statement.  We do not want this code to
    491 ** appear when assert() is disabled.  The following macro is therefore
    492 ** used to contain that setup code.  The "VVA" acronym stands for
    493 ** "Verification, Validation, and Accreditation".  In other words, the
    494 ** code within VVA_ONLY() will only run during verification processes.
    495 */
    496 #ifndef NDEBUG
    497 # define VVA_ONLY(X)  X
    498 #else
    499 # define VVA_ONLY(X)
    500 #endif
    501 
    502 /*
    503 ** The ALWAYS and NEVER macros surround boolean expressions which
    504 ** are intended to always be true or false, respectively.  Such
    505 ** expressions could be omitted from the code completely.  But they
    506 ** are included in a few cases in order to enhance the resilience
    507 ** of SQLite to unexpected behavior - to make the code "self-healing"
    508 ** or "ductile" rather than being "brittle" and crashing at the first
    509 ** hint of unplanned behavior.
    510 **
    511 ** In other words, ALWAYS and NEVER are added for defensive code.
    512 **
    513 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
    514 ** be true and false so that the unreachable code then specify will
    515 ** not be counted as untested code.
    516 */
    517 #if defined(SQLITE_COVERAGE_TEST)
    518 # define ALWAYS(X)      (1)
    519 # define NEVER(X)       (0)
    520 #elif !defined(NDEBUG)
    521 # define ALWAYS(X)      ((X)?1:(assert(0),0))
    522 # define NEVER(X)       ((X)?(assert(0),1):0)
    523 #else
    524 # define ALWAYS(X)      (X)
    525 # define NEVER(X)       (X)
    526 #endif
    527 
    528 /*
    529 ** Return true (non-zero) if the input is a integer that is too large
    530 ** to fit in 32-bits.  This macro is used inside of various testcase()
    531 ** macros to verify that we have tested SQLite for large-file support.
    532 */
    533 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
    534 
    535 /*
    536 ** The macro unlikely() is a hint that surrounds a boolean
    537 ** expression that is usually false.  Macro likely() surrounds
    538 ** a boolean expression that is usually true.  GCC is able to
    539 ** use these hints to generate better code, sometimes.
    540 */
    541 #if defined(__GNUC__) && 0
    542 # define likely(X)    __builtin_expect((X),1)
    543 # define unlikely(X)  __builtin_expect((X),0)
    544 #else
    545 # define likely(X)    !!(X)
    546 # define unlikely(X)  !!(X)
    547 #endif
    548 
    549 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
    550 /************** Begin file sqlite3.h *****************************************/
    551 /*
    552 ** 2001 September 15
    553 **
    554 ** The author disclaims copyright to this source code.  In place of
    555 ** a legal notice, here is a blessing:
    556 **
    557 **    May you do good and not evil.
    558 **    May you find forgiveness for yourself and forgive others.
    559 **    May you share freely, never taking more than you give.
    560 **
    561 *************************************************************************
    562 ** This header file defines the interface that the SQLite library
    563 ** presents to client programs.  If a C-function, structure, datatype,
    564 ** or constant definition does not appear in this file, then it is
    565 ** not a published API of SQLite, is subject to change without
    566 ** notice, and should not be referenced by programs that use SQLite.
    567 **
    568 ** Some of the definitions that are in this file are marked as
    569 ** "experimental".  Experimental interfaces are normally new
    570 ** features recently added to SQLite.  We do not anticipate changes
    571 ** to experimental interfaces but reserve the right to make minor changes
    572 ** if experience from use "in the wild" suggest such changes are prudent.
    573 **
    574 ** The official C-language API documentation for SQLite is derived
    575 ** from comments in this file.  This file is the authoritative source
    576 ** on how SQLite interfaces are suppose to operate.
    577 **
    578 ** The name of this file under configuration management is "sqlite.h.in".
    579 ** The makefile makes some minor changes to this file (such as inserting
    580 ** the version number) and changes its name to "sqlite3.h" as
    581 ** part of the build process.
    582 */
    583 #ifndef _SQLITE3_H_
    584 #define _SQLITE3_H_
    585 #include <stdarg.h>     /* Needed for the definition of va_list */
    586 
    587 /*
    588 ** Make sure we can call this stuff from C++.
    589 */
    590 #if 0
    591 extern "C" {
    592 #endif
    593 
    594 
    595 /*
    596 ** Add the ability to override 'extern'
    597 */
    598 #ifndef SQLITE_EXTERN
    599 # define SQLITE_EXTERN extern
    600 #endif
    601 
    602 #ifndef SQLITE_API
    603 # define SQLITE_API
    604 #endif
    605 
    606 
    607 /*
    608 ** These no-op macros are used in front of interfaces to mark those
    609 ** interfaces as either deprecated or experimental.  New applications
    610 ** should not use deprecated interfaces - they are support for backwards
    611 ** compatibility only.  Application writers should be aware that
    612 ** experimental interfaces are subject to change in point releases.
    613 **
    614 ** These macros used to resolve to various kinds of compiler magic that
    615 ** would generate warning messages when they were used.  But that
    616 ** compiler magic ended up generating such a flurry of bug reports
    617 ** that we have taken it all out and gone back to using simple
    618 ** noop macros.
    619 */
    620 #define SQLITE_DEPRECATED
    621 #define SQLITE_EXPERIMENTAL
    622 
    623 /*
    624 ** Ensure these symbols were not defined by some previous header file.
    625 */
    626 #ifdef SQLITE_VERSION
    627 # undef SQLITE_VERSION
    628 #endif
    629 #ifdef SQLITE_VERSION_NUMBER
    630 # undef SQLITE_VERSION_NUMBER
    631 #endif
    632 
    633 /*
    634 ** CAPI3REF: Compile-Time Library Version Numbers
    635 **
    636 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
    637 ** evaluates to a string literal that is the SQLite version in the
    638 ** format "X.Y.Z" where X is the major version number (always 3 for
    639 ** SQLite3) and Y is the minor version number and Z is the release number.)^
    640 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
    641 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
    642 ** numbers used in [SQLITE_VERSION].)^
    643 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
    644 ** be larger than the release from which it is derived.  Either Y will
    645 ** be held constant and Z will be incremented or else Y will be incremented
    646 ** and Z will be reset to zero.
    647 **
    648 ** Since version 3.6.18, SQLite source code has been stored in the
    649 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
    650 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
    651 ** a string which identifies a particular check-in of SQLite
    652 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
    653 ** string contains the date and time of the check-in (UTC) and an SHA1
    654 ** hash of the entire source tree.
    655 **
    656 ** See also: [sqlite3_libversion()],
    657 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
    658 ** [sqlite_version()] and [sqlite_source_id()].
    659 */
    660 #define SQLITE_VERSION        "3.7.11"
    661 #define SQLITE_VERSION_NUMBER 3007011
    662 #define SQLITE_SOURCE_ID      "2012-03-20 11:35:50 00bb9c9ce4f465e6ac321ced2a9d0062dc364669"
    663 
    664 /*
    665 ** CAPI3REF: Run-Time Library Version Numbers
    666 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
    667 **
    668 ** These interfaces provide the same information as the [SQLITE_VERSION],
    669 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
    670 ** but are associated with the library instead of the header file.  ^(Cautious
    671 ** programmers might include assert() statements in their application to
    672 ** verify that values returned by these interfaces match the macros in
    673 ** the header, and thus insure that the application is
    674 ** compiled with matching library and header files.
    675 **
    676 ** <blockquote><pre>
    677 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    678 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    679 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    680 ** </pre></blockquote>)^
    681 **
    682 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
    683 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
    684 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
    685 ** function is provided for use in DLLs since DLL users usually do not have
    686 ** direct access to string constants within the DLL.  ^The
    687 ** sqlite3_libversion_number() function returns an integer equal to
    688 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
    689 ** a pointer to a string constant whose value is the same as the
    690 ** [SQLITE_SOURCE_ID] C preprocessor macro.
    691 **
    692 ** See also: [sqlite_version()] and [sqlite_source_id()].
    693 */
    694 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
    695 SQLITE_API const char *sqlite3_libversion(void);
    696 SQLITE_API const char *sqlite3_sourceid(void);
    697 SQLITE_API int sqlite3_libversion_number(void);
    698 
    699 /*
    700 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
    701 **
    702 ** ^The sqlite3_compileoption_used() function returns 0 or 1
    703 ** indicating whether the specified option was defined at
    704 ** compile time.  ^The SQLITE_ prefix may be omitted from the
    705 ** option name passed to sqlite3_compileoption_used().
    706 **
    707 ** ^The sqlite3_compileoption_get() function allows iterating
    708 ** over the list of options that were defined at compile time by
    709 ** returning the N-th compile time option string.  ^If N is out of range,
    710 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
    711 ** prefix is omitted from any strings returned by
    712 ** sqlite3_compileoption_get().
    713 **
    714 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
    715 ** and sqlite3_compileoption_get() may be omitted by specifying the
    716 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
    717 **
    718 ** See also: SQL functions [sqlite_compileoption_used()] and
    719 ** [sqlite_compileoption_get()] and the [compile_options pragma].
    720 */
    721 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
    722 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
    723 SQLITE_API const char *sqlite3_compileoption_get(int N);
    724 #endif
    725 
    726 /*
    727 ** CAPI3REF: Test To See If The Library Is Threadsafe
    728 **
    729 ** ^The sqlite3_threadsafe() function returns zero if and only if
    730 ** SQLite was compiled with mutexing code omitted due to the
    731 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
    732 **
    733 ** SQLite can be compiled with or without mutexes.  When
    734 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
    735 ** are enabled and SQLite is threadsafe.  When the
    736 ** [SQLITE_THREADSAFE] macro is 0,
    737 ** the mutexes are omitted.  Without the mutexes, it is not safe
    738 ** to use SQLite concurrently from more than one thread.
    739 **
    740 ** Enabling mutexes incurs a measurable performance penalty.
    741 ** So if speed is of utmost importance, it makes sense to disable
    742 ** the mutexes.  But for maximum safety, mutexes should be enabled.
    743 ** ^The default behavior is for mutexes to be enabled.
    744 **
    745 ** This interface can be used by an application to make sure that the
    746 ** version of SQLite that it is linking against was compiled with
    747 ** the desired setting of the [SQLITE_THREADSAFE] macro.
    748 **
    749 ** This interface only reports on the compile-time mutex setting
    750 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
    751 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
    752 ** can be fully or partially disabled using a call to [sqlite3_config()]
    753 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
    754 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
    755 ** sqlite3_threadsafe() function shows only the compile-time setting of
    756 ** thread safety, not any run-time changes to that setting made by
    757 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
    758 ** is unchanged by calls to sqlite3_config().)^
    759 **
    760 ** See the [threading mode] documentation for additional information.
    761 */
    762 SQLITE_API int sqlite3_threadsafe(void);
    763 
    764 /*
    765 ** CAPI3REF: Database Connection Handle
    766 ** KEYWORDS: {database connection} {database connections}
    767 **
    768 ** Each open SQLite database is represented by a pointer to an instance of
    769 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
    770 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
    771 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
    772 ** is its destructor.  There are many other interfaces (such as
    773 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
    774 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
    775 ** sqlite3 object.
    776 */
    777 typedef struct sqlite3 sqlite3;
    778 
    779 /*
    780 ** CAPI3REF: 64-Bit Integer Types
    781 ** KEYWORDS: sqlite_int64 sqlite_uint64
    782 **
    783 ** Because there is no cross-platform way to specify 64-bit integer types
    784 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
    785 **
    786 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
    787 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
    788 ** compatibility only.
    789 **
    790 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
    791 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
    792 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
    793 ** between 0 and +18446744073709551615 inclusive.
    794 */
    795 #ifdef SQLITE_INT64_TYPE
    796   typedef SQLITE_INT64_TYPE sqlite_int64;
    797   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
    798 #elif defined(_MSC_VER) || defined(__BORLANDC__)
    799   typedef __int64 sqlite_int64;
    800   typedef unsigned __int64 sqlite_uint64;
    801 #else
    802   typedef long long int sqlite_int64;
    803   typedef unsigned long long int sqlite_uint64;
    804 #endif
    805 typedef sqlite_int64 sqlite3_int64;
    806 typedef sqlite_uint64 sqlite3_uint64;
    807 
    808 /*
    809 ** If compiling for a processor that lacks floating point support,
    810 ** substitute integer for floating-point.
    811 */
    812 #ifdef SQLITE_OMIT_FLOATING_POINT
    813 # define double sqlite3_int64
    814 #endif
    815 
    816 /*
    817 ** CAPI3REF: Closing A Database Connection
    818 **
    819 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
    820 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
    821 ** successfully destroyed and all associated resources are deallocated.
    822 **
    823 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
    824 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
    825 ** the [sqlite3] object prior to attempting to close the object.  ^If
    826 ** sqlite3_close() is called on a [database connection] that still has
    827 ** outstanding [prepared statements] or [BLOB handles], then it returns
    828 ** SQLITE_BUSY.
    829 **
    830 ** ^If [sqlite3_close()] is invoked while a transaction is open,
    831 ** the transaction is automatically rolled back.
    832 **
    833 ** The C parameter to [sqlite3_close(C)] must be either a NULL
    834 ** pointer or an [sqlite3] object pointer obtained
    835 ** from [sqlite3_open()], [sqlite3_open16()], or
    836 ** [sqlite3_open_v2()], and not previously closed.
    837 ** ^Calling sqlite3_close() with a NULL pointer argument is a
    838 ** harmless no-op.
    839 */
    840 SQLITE_API int sqlite3_close(sqlite3 *);
    841 
    842 /*
    843 ** The type for a callback function.
    844 ** This is legacy and deprecated.  It is included for historical
    845 ** compatibility and is not documented.
    846 */
    847 typedef int (*sqlite3_callback)(void*,int,char**, char**);
    848 
    849 /*
    850 ** CAPI3REF: One-Step Query Execution Interface
    851 **
    852 ** The sqlite3_exec() interface is a convenience wrapper around
    853 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
    854 ** that allows an application to run multiple statements of SQL
    855 ** without having to use a lot of C code.
    856 **
    857 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
    858 ** semicolon-separate SQL statements passed into its 2nd argument,
    859 ** in the context of the [database connection] passed in as its 1st
    860 ** argument.  ^If the callback function of the 3rd argument to
    861 ** sqlite3_exec() is not NULL, then it is invoked for each result row
    862 ** coming out of the evaluated SQL statements.  ^The 4th argument to
    863 ** sqlite3_exec() is relayed through to the 1st argument of each
    864 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
    865 ** is NULL, then no callback is ever invoked and result rows are
    866 ** ignored.
    867 **
    868 ** ^If an error occurs while evaluating the SQL statements passed into
    869 ** sqlite3_exec(), then execution of the current statement stops and
    870 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
    871 ** is not NULL then any error message is written into memory obtained
    872 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
    873 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
    874 ** on error message strings returned through the 5th parameter of
    875 ** of sqlite3_exec() after the error message string is no longer needed.
    876 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
    877 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
    878 ** NULL before returning.
    879 **
    880 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
    881 ** routine returns SQLITE_ABORT without invoking the callback again and
    882 ** without running any subsequent SQL statements.
    883 **
    884 ** ^The 2nd argument to the sqlite3_exec() callback function is the
    885 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
    886 ** callback is an array of pointers to strings obtained as if from
    887 ** [sqlite3_column_text()], one for each column.  ^If an element of a
    888 ** result row is NULL then the corresponding string pointer for the
    889 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
    890 ** sqlite3_exec() callback is an array of pointers to strings where each
    891 ** entry represents the name of corresponding result column as obtained
    892 ** from [sqlite3_column_name()].
    893 **
    894 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
    895 ** to an empty string, or a pointer that contains only whitespace and/or
    896 ** SQL comments, then no SQL statements are evaluated and the database
    897 ** is not changed.
    898 **
    899 ** Restrictions:
    900 **
    901 ** <ul>
    902 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
    903 **      is a valid and open [database connection].
    904 ** <li> The application must not close [database connection] specified by
    905 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
    906 ** <li> The application must not modify the SQL statement text passed into
    907 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
    908 ** </ul>
    909 */
    910 SQLITE_API int sqlite3_exec(
    911   sqlite3*,                                  /* An open database */
    912   const char *sql,                           /* SQL to be evaluated */
    913   int (*callback)(void*,int,char**,char**),  /* Callback function */
    914   void *,                                    /* 1st argument to callback */
    915   char **errmsg                              /* Error msg written here */
    916 );
    917 
    918 /*
    919 ** CAPI3REF: Result Codes
    920 ** KEYWORDS: SQLITE_OK {error code} {error codes}
    921 ** KEYWORDS: {result code} {result codes}
    922 **
    923 ** Many SQLite functions return an integer result code from the set shown
    924 ** here in order to indicate success or failure.
    925 **
    926 ** New error codes may be added in future versions of SQLite.
    927 **
    928 ** See also: [SQLITE_IOERR_READ | extended result codes],
    929 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
    930 */
    931 #define SQLITE_OK           0   /* Successful result */
    932 /* beginning-of-error-codes */
    933 #define SQLITE_ERROR        1   /* SQL error or missing database */
    934 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
    935 #define SQLITE_PERM         3   /* Access permission denied */
    936 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
    937 #define SQLITE_BUSY         5   /* The database file is locked */
    938 #define SQLITE_LOCKED       6   /* A table in the database is locked */
    939 #define SQLITE_NOMEM        7   /* A malloc() failed */
    940 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
    941 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
    942 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
    943 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
    944 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
    945 #define SQLITE_FULL        13   /* Insertion failed because database is full */
    946 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
    947 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
    948 #define SQLITE_EMPTY       16   /* Database is empty */
    949 #define SQLITE_SCHEMA      17   /* The database schema changed */
    950 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
    951 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
    952 #define SQLITE_MISMATCH    20   /* Data type mismatch */
    953 #define SQLITE_MISUSE      21   /* Library used incorrectly */
    954 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
    955 #define SQLITE_AUTH        23   /* Authorization denied */
    956 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
    957 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
    958 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
    959 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
    960 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
    961 /* end-of-error-codes */
    962 
    963 /*
    964 ** CAPI3REF: Extended Result Codes
    965 ** KEYWORDS: {extended error code} {extended error codes}
    966 ** KEYWORDS: {extended result code} {extended result codes}
    967 **
    968 ** In its default configuration, SQLite API routines return one of 26 integer
    969 ** [SQLITE_OK | result codes].  However, experience has shown that many of
    970 ** these result codes are too coarse-grained.  They do not provide as
    971 ** much information about problems as programmers might like.  In an effort to
    972 ** address this, newer versions of SQLite (version 3.3.8 and later) include
    973 ** support for additional result codes that provide more detailed information
    974 ** about errors. The extended result codes are enabled or disabled
    975 ** on a per database connection basis using the
    976 ** [sqlite3_extended_result_codes()] API.
    977 **
    978 ** Some of the available extended result codes are listed here.
    979 ** One may expect the number of extended result codes will be expand
    980 ** over time.  Software that uses extended result codes should expect
    981 ** to see new result codes in future releases of SQLite.
    982 **
    983 ** The SQLITE_OK result code will never be extended.  It will always
    984 ** be exactly zero.
    985 */
    986 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
    987 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
    988 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
    989 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
    990 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
    991 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
    992 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
    993 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
    994 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
    995 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
    996 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
    997 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
    998 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
    999 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
   1000 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
   1001 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
   1002 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
   1003 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   1004 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   1005 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   1006 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
   1007 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
   1008 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   1009 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   1010 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   1011 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
   1012 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
   1013 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
   1014 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
   1015 
   1016 /*
   1017 ** CAPI3REF: Flags For File Open Operations
   1018 **
   1019 ** These bit values are intended for use in the
   1020 ** 3rd parameter to the [sqlite3_open_v2()] interface and
   1021 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
   1022 */
   1023 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
   1024 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
   1025 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
   1026 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
   1027 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
   1028 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
   1029 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
   1030 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
   1031 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
   1032 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
   1033 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
   1034 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
   1035 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
   1036 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
   1037 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
   1038 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
   1039 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
   1040 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
   1041 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
   1042 
   1043 /* Reserved:                         0x00F00000 */
   1044 
   1045 /*
   1046 ** CAPI3REF: Device Characteristics
   1047 **
   1048 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
   1049 ** object returns an integer which is a vector of the these
   1050 ** bit values expressing I/O characteristics of the mass storage
   1051 ** device that holds the file that the [sqlite3_io_methods]
   1052 ** refers to.
   1053 **
   1054 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1055 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1056 ** mean that writes of blocks that are nnn bytes in size and
   1057 ** are aligned to an address which is an integer multiple of
   1058 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1059 ** that when data is appended to a file, the data is appended
   1060 ** first then the size of the file is extended, never the other
   1061 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1062 ** information is written to disk in the same order as calls
   1063 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
   1064 ** after reboot following a crash or power loss, the only bytes in a
   1065 ** file that were written at the application level might have changed
   1066 ** and that adjacent bytes, even bytes within the same sector are
   1067 ** guaranteed to be unchanged.
   1068 */
   1069 #define SQLITE_IOCAP_ATOMIC                 0x00000001
   1070 #define SQLITE_IOCAP_ATOMIC512              0x00000002
   1071 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
   1072 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
   1073 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
   1074 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
   1075 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
   1076 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
   1077 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
   1078 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   1079 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   1080 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
   1081 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
   1082 
   1083 /*
   1084 ** CAPI3REF: File Locking Levels
   1085 **
   1086 ** SQLite uses one of these integer values as the second
   1087 ** argument to calls it makes to the xLock() and xUnlock() methods
   1088 ** of an [sqlite3_io_methods] object.
   1089 */
   1090 #define SQLITE_LOCK_NONE          0
   1091 #define SQLITE_LOCK_SHARED        1
   1092 #define SQLITE_LOCK_RESERVED      2
   1093 #define SQLITE_LOCK_PENDING       3
   1094 #define SQLITE_LOCK_EXCLUSIVE     4
   1095 
   1096 /*
   1097 ** CAPI3REF: Synchronization Type Flags
   1098 **
   1099 ** When SQLite invokes the xSync() method of an
   1100 ** [sqlite3_io_methods] object it uses a combination of
   1101 ** these integer values as the second argument.
   1102 **
   1103 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1104 ** sync operation only needs to flush data to mass storage.  Inode
   1105 ** information need not be flushed. If the lower four bits of the flag
   1106 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1107 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1108 ** to use Mac OS X style fullsync instead of fsync().
   1109 **
   1110 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
   1111 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
   1112 ** settings.  The [synchronous pragma] determines when calls to the
   1113 ** xSync VFS method occur and applies uniformly across all platforms.
   1114 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
   1115 ** energetic or rigorous or forceful the sync operations are and
   1116 ** only make a difference on Mac OSX for the default SQLite code.
   1117 ** (Third-party VFS implementations might also make the distinction
   1118 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
   1119 ** operating systems natively supported by SQLite, only Mac OSX
   1120 ** cares about the difference.)
   1121 */
   1122 #define SQLITE_SYNC_NORMAL        0x00002
   1123 #define SQLITE_SYNC_FULL          0x00003
   1124 #define SQLITE_SYNC_DATAONLY      0x00010
   1125 
   1126 /*
   1127 ** CAPI3REF: OS Interface Open File Handle
   1128 **
   1129 ** An [sqlite3_file] object represents an open file in the
   1130 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1131 ** implementations will
   1132 ** want to subclass this object by appending additional fields
   1133 ** for their own use.  The pMethods entry is a pointer to an
   1134 ** [sqlite3_io_methods] object that defines methods for performing
   1135 ** I/O operations on the open file.
   1136 */
   1137 typedef struct sqlite3_file sqlite3_file;
   1138 struct sqlite3_file {
   1139   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1140 };
   1141 
   1142 /*
   1143 ** CAPI3REF: OS Interface File Virtual Methods Object
   1144 **
   1145 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
   1146 ** [sqlite3_file] object (or, more commonly, a subclass of the
   1147 ** [sqlite3_file] object) with a pointer to an instance of this object.
   1148 ** This object defines the methods used to perform various operations
   1149 ** against the open file represented by the [sqlite3_file] object.
   1150 **
   1151 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
   1152 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1153 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
   1154 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
   1155 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
   1156 ** to NULL.
   1157 **
   1158 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1159 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1160 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1161 ** flag may be ORed in to indicate that only the data of the file
   1162 ** and not its inode needs to be synced.
   1163 **
   1164 ** The integer values to xLock() and xUnlock() are one of
   1165 ** <ul>
   1166 ** <li> [SQLITE_LOCK_NONE],
   1167 ** <li> [SQLITE_LOCK_SHARED],
   1168 ** <li> [SQLITE_LOCK_RESERVED],
   1169 ** <li> [SQLITE_LOCK_PENDING], or
   1170 ** <li> [SQLITE_LOCK_EXCLUSIVE].
   1171 ** </ul>
   1172 ** xLock() increases the lock. xUnlock() decreases the lock.
   1173 ** The xCheckReservedLock() method checks whether any database connection,
   1174 ** either in this process or in some other process, is holding a RESERVED,
   1175 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1176 ** if such a lock exists and false otherwise.
   1177 **
   1178 ** The xFileControl() method is a generic interface that allows custom
   1179 ** VFS implementations to directly control an open file using the
   1180 ** [sqlite3_file_control()] interface.  The second "op" argument is an
   1181 ** integer opcode.  The third argument is a generic pointer intended to
   1182 ** point to a structure that may contain arguments or space in which to
   1183 ** write return values.  Potential uses for xFileControl() might be
   1184 ** functions to enable blocking locks with timeouts, to change the
   1185 ** locking strategy (for example to use dot-file locks), to inquire
   1186 ** about the status of a lock, or to break stale locks.  The SQLite
   1187 ** core reserves all opcodes less than 100 for its own use.
   1188 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   1189 ** Applications that define a custom xFileControl method should use opcodes
   1190 ** greater than 100 to avoid conflicts.  VFS implementations should
   1191 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
   1192 ** recognize.
   1193 **
   1194 ** The xSectorSize() method returns the sector size of the
   1195 ** device that underlies the file.  The sector size is the
   1196 ** minimum write that can be performed without disturbing
   1197 ** other bytes in the file.  The xDeviceCharacteristics()
   1198 ** method returns a bit vector describing behaviors of the
   1199 ** underlying device:
   1200 **
   1201 ** <ul>
   1202 ** <li> [SQLITE_IOCAP_ATOMIC]
   1203 ** <li> [SQLITE_IOCAP_ATOMIC512]
   1204 ** <li> [SQLITE_IOCAP_ATOMIC1K]
   1205 ** <li> [SQLITE_IOCAP_ATOMIC2K]
   1206 ** <li> [SQLITE_IOCAP_ATOMIC4K]
   1207 ** <li> [SQLITE_IOCAP_ATOMIC8K]
   1208 ** <li> [SQLITE_IOCAP_ATOMIC16K]
   1209 ** <li> [SQLITE_IOCAP_ATOMIC32K]
   1210 ** <li> [SQLITE_IOCAP_ATOMIC64K]
   1211 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1212 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1213 ** </ul>
   1214 **
   1215 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1216 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1217 ** mean that writes of blocks that are nnn bytes in size and
   1218 ** are aligned to an address which is an integer multiple of
   1219 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1220 ** that when data is appended to a file, the data is appended
   1221 ** first then the size of the file is extended, never the other
   1222 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1223 ** information is written to disk in the same order as calls
   1224 ** to xWrite().
   1225 **
   1226 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1227 ** in the unread portions of the buffer with zeros.  A VFS that
   1228 ** fails to zero-fill short reads might seem to work.  However,
   1229 ** failure to zero-fill short reads will eventually lead to
   1230 ** database corruption.
   1231 */
   1232 typedef struct sqlite3_io_methods sqlite3_io_methods;
   1233 struct sqlite3_io_methods {
   1234   int iVersion;
   1235   int (*xClose)(sqlite3_file*);
   1236   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1237   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1238   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1239   int (*xSync)(sqlite3_file*, int flags);
   1240   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1241   int (*xLock)(sqlite3_file*, int);
   1242   int (*xUnlock)(sqlite3_file*, int);
   1243   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1244   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1245   int (*xSectorSize)(sqlite3_file*);
   1246   int (*xDeviceCharacteristics)(sqlite3_file*);
   1247   /* Methods above are valid for version 1 */
   1248   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   1249   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
   1250   void (*xShmBarrier)(sqlite3_file*);
   1251   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
   1252   /* Methods above are valid for version 2 */
   1253   /* Additional methods may be added in future releases */
   1254 };
   1255 
   1256 /*
   1257 ** CAPI3REF: Standard File Control Opcodes
   1258 **
   1259 ** These integer constants are opcodes for the xFileControl method
   1260 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1261 ** interface.
   1262 **
   1263 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1264 ** opcode causes the xFileControl method to write the current state of
   1265 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1266 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1267 ** into an integer that the pArg argument points to. This capability
   1268 ** is used during testing and only needs to be supported when SQLITE_TEST
   1269 ** is defined.
   1270 ** <ul>
   1271 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
   1272 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
   1273 ** layer a hint of how large the database file will grow to be during the
   1274 ** current transaction.  This hint is not guaranteed to be accurate but it
   1275 ** is often close.  The underlying VFS might choose to preallocate database
   1276 ** file space based on this hint in order to help writes to the database
   1277 ** file run faster.
   1278 **
   1279 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
   1280 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
   1281 ** extends and truncates the database file in chunks of a size specified
   1282 ** by the user. The fourth argument to [sqlite3_file_control()] should
   1283 ** point to an integer (type int) containing the new chunk-size to use
   1284 ** for the nominated database. Allocating database file space in large
   1285 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
   1286 ** improve performance on some systems.
   1287 **
   1288 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
   1289 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
   1290 ** to the [sqlite3_file] object associated with a particular database
   1291 ** connection.  See the [sqlite3_file_control()] documentation for
   1292 ** additional information.
   1293 **
   1294 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
   1295 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
   1296 ** SQLite and sent to all VFSes in place of a call to the xSync method
   1297 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
   1298 ** Some specialized VFSes need this signal in order to operate correctly
   1299 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
   1300 ** VFSes do not need this signal and should silently ignore this opcode.
   1301 ** Applications should not call [sqlite3_file_control()] with this
   1302 ** opcode as doing so may disrupt the operation of the specialized VFSes
   1303 ** that do require it.
   1304 **
   1305 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
   1306 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
   1307 ** retry counts and intervals for certain disk I/O operations for the
   1308 ** windows [VFS] in order to provide robustness in the presence of
   1309 ** anti-virus programs.  By default, the windows VFS will retry file read,
   1310 ** file write, and file delete operations up to 10 times, with a delay
   1311 ** of 25 milliseconds before the first retry and with the delay increasing
   1312 ** by an additional 25 milliseconds with each subsequent retry.  This
   1313 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
   1314 ** to be adjusted.  The values are changed for all database connections
   1315 ** within the same process.  The argument is a pointer to an array of two
   1316 ** integers where the first integer i the new retry count and the second
   1317 ** integer is the delay.  If either integer is negative, then the setting
   1318 ** is not changed but instead the prior value of that setting is written
   1319 ** into the array entry, allowing the current retry settings to be
   1320 ** interrogated.  The zDbName parameter is ignored.
   1321 **
   1322 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
   1323 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
   1324 ** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
   1325 ** write ahead log and shared memory files used for transaction control
   1326 ** are automatically deleted when the latest connection to the database
   1327 ** closes.  Setting persistent WAL mode causes those files to persist after
   1328 ** close.  Persisting the files is useful when other processes that do not
   1329 ** have write permission on the directory containing the database file want
   1330 ** to read the database file, as the WAL and shared memory files must exist
   1331 ** in order for the database to be readable.  The fourth parameter to
   1332 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1333 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
   1334 ** WAL mode.  If the integer is -1, then it is overwritten with the current
   1335 ** WAL persistence setting.
   1336 **
   1337 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
   1338 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
   1339 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
   1340 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
   1341 ** xDeviceCharacteristics methods. The fourth parameter to
   1342 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   1343 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
   1344 ** mode.  If the integer is -1, then it is overwritten with the current
   1345 ** zero-damage mode setting.
   1346 **
   1347 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
   1348 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
   1349 ** a write transaction to indicate that, unless it is rolled back for some
   1350 ** reason, the entire database file will be overwritten by the current
   1351 ** transaction. This is used by VACUUM operations.
   1352 **
   1353 ** <li>[[SQLITE_FCNTL_VFSNAME]]
   1354 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
   1355 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
   1356 ** final bottom-level VFS are written into memory obtained from
   1357 ** [sqlite3_malloc()] and the result is stored in the char* variable
   1358 ** that the fourth parameter of [sqlite3_file_control()] points to.
   1359 ** The caller is responsible for freeing the memory when done.  As with
   1360 ** all file-control actions, there is no guarantee that this will actually
   1361 ** do anything.  Callers should initialize the char* variable to a NULL
   1362 ** pointer in case this file-control is not implemented.  This file-control
   1363 ** is intended for diagnostic use only.
   1364 **
   1365 ** <li>[[SQLITE_FCNTL_PRAGMA]]
   1366 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
   1367 ** file control is sent to the open [sqlite3_file] object corresponding
   1368 ** to the database file to which the pragma statement refers. ^The argument
   1369 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
   1370 ** pointers to strings (char**) in which the second element of the array
   1371 ** is the name of the pragma and the third element is the argument to the
   1372 ** pragma or NULL if the pragma has no argument.  ^The handler for an
   1373 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
   1374 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
   1375 ** or the equivalent and that string will become the result of the pragma or
   1376 ** the error message if the pragma fails. ^If the
   1377 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
   1378 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
   1379 ** file control returns [SQLITE_OK], then the parser assumes that the
   1380 ** VFS has handled the PRAGMA itself and the parser generates a no-op
   1381 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
   1382 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
   1383 ** that the VFS encountered an error while handling the [PRAGMA] and the
   1384 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
   1385 ** file control occurs at the beginning of pragma statement analysis and so
   1386 ** it is able to override built-in [PRAGMA] statements.
   1387 ** </ul>
   1388 */
   1389 #define SQLITE_FCNTL_LOCKSTATE               1
   1390 #define SQLITE_GET_LOCKPROXYFILE             2
   1391 #define SQLITE_SET_LOCKPROXYFILE             3
   1392 #define SQLITE_LAST_ERRNO                    4
   1393 #define SQLITE_FCNTL_SIZE_HINT               5
   1394 #define SQLITE_FCNTL_CHUNK_SIZE              6
   1395 #define SQLITE_FCNTL_FILE_POINTER            7
   1396 #define SQLITE_FCNTL_SYNC_OMITTED            8
   1397 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
   1398 #define SQLITE_FCNTL_PERSIST_WAL            10
   1399 #define SQLITE_FCNTL_OVERWRITE              11
   1400 #define SQLITE_FCNTL_VFSNAME                12
   1401 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
   1402 #define SQLITE_FCNTL_PRAGMA                 14
   1403 
   1404 /*
   1405 ** CAPI3REF: Mutex Handle
   1406 **
   1407 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   1408 ** abstract type for a mutex object.  The SQLite core never looks
   1409 ** at the internal representation of an [sqlite3_mutex].  It only
   1410 ** deals with pointers to the [sqlite3_mutex] object.
   1411 **
   1412 ** Mutexes are created using [sqlite3_mutex_alloc()].
   1413 */
   1414 typedef struct sqlite3_mutex sqlite3_mutex;
   1415 
   1416 /*
   1417 ** CAPI3REF: OS Interface Object
   1418 **
   1419 ** An instance of the sqlite3_vfs object defines the interface between
   1420 ** the SQLite core and the underlying operating system.  The "vfs"
   1421 ** in the name of the object stands for "virtual file system".  See
   1422 ** the [VFS | VFS documentation] for further information.
   1423 **
   1424 ** The value of the iVersion field is initially 1 but may be larger in
   1425 ** future versions of SQLite.  Additional fields may be appended to this
   1426 ** object when the iVersion value is increased.  Note that the structure
   1427 ** of the sqlite3_vfs object changes in the transaction between
   1428 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
   1429 ** modified.
   1430 **
   1431 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   1432 ** structure used by this VFS.  mxPathname is the maximum length of
   1433 ** a pathname in this VFS.
   1434 **
   1435 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   1436 ** the pNext pointer.  The [sqlite3_vfs_register()]
   1437 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   1438 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   1439 ** searches the list.  Neither the application code nor the VFS
   1440 ** implementation should use the pNext pointer.
   1441 **
   1442 ** The pNext field is the only field in the sqlite3_vfs
   1443 ** structure that SQLite will ever modify.  SQLite will only access
   1444 ** or modify this field while holding a particular static mutex.
   1445 ** The application should never modify anything within the sqlite3_vfs
   1446 ** object once the object has been registered.
   1447 **
   1448 ** The zName field holds the name of the VFS module.  The name must
   1449 ** be unique across all VFS modules.
   1450 **
   1451 ** [[sqlite3_vfs.xOpen]]
   1452 ** ^SQLite guarantees that the zFilename parameter to xOpen
   1453 ** is either a NULL pointer or string obtained
   1454 ** from xFullPathname() with an optional suffix added.
   1455 ** ^If a suffix is added to the zFilename parameter, it will
   1456 ** consist of a single "-" character followed by no more than
   1457 ** 11 alphanumeric and/or "-" characters.
   1458 ** ^SQLite further guarantees that
   1459 ** the string will be valid and unchanged until xClose() is
   1460 ** called. Because of the previous sentence,
   1461 ** the [sqlite3_file] can safely store a pointer to the
   1462 ** filename if it needs to remember the filename for some reason.
   1463 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
   1464 ** must invent its own temporary name for the file.  ^Whenever the
   1465 ** xFilename parameter is NULL it will also be the case that the
   1466 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   1467 **
   1468 ** The flags argument to xOpen() includes all bits set in
   1469 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   1470 ** or [sqlite3_open16()] is used, then flags includes at least
   1471 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   1472 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   1473 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   1474 **
   1475 ** ^(SQLite will also add one of the following flags to the xOpen()
   1476 ** call, depending on the object being opened:
   1477 **
   1478 ** <ul>
   1479 ** <li>  [SQLITE_OPEN_MAIN_DB]
   1480 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   1481 ** <li>  [SQLITE_OPEN_TEMP_DB]
   1482 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   1483 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   1484 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   1485 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   1486 ** <li>  [SQLITE_OPEN_WAL]
   1487 ** </ul>)^
   1488 **
   1489 ** The file I/O implementation can use the object type flags to
   1490 ** change the way it deals with files.  For example, an application
   1491 ** that does not care about crash recovery or rollback might make
   1492 ** the open of a journal file a no-op.  Writes to this journal would
   1493 ** also be no-ops, and any attempt to read the journal would return
   1494 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   1495 ** file will be doing page-aligned sector reads and writes in a random
   1496 ** order and set up its I/O subsystem accordingly.
   1497 **
   1498 ** SQLite might also add one of the following flags to the xOpen method:
   1499 **
   1500 ** <ul>
   1501 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   1502 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   1503 ** </ul>
   1504 **
   1505 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   1506 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
   1507 ** will be set for TEMP databases and their journals, transient
   1508 ** databases, and subjournals.
   1509 **
   1510 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   1511 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   1512 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   1513 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   1514 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   1515 ** be created, and that it is an error if it already exists.
   1516 ** It is <i>not</i> used to indicate the file should be opened
   1517 ** for exclusive access.
   1518 **
   1519 ** ^At least szOsFile bytes of memory are allocated by SQLite
   1520 ** to hold the  [sqlite3_file] structure passed as the third
   1521 ** argument to xOpen.  The xOpen method does not have to
   1522 ** allocate the structure; it should just fill it in.  Note that
   1523 ** the xOpen method must set the sqlite3_file.pMethods to either
   1524 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   1525 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   1526 ** element will be valid after xOpen returns regardless of the success
   1527 ** or failure of the xOpen call.
   1528 **
   1529 ** [[sqlite3_vfs.xAccess]]
   1530 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   1531 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   1532 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   1533 ** to test whether a file is at least readable.   The file can be a
   1534 ** directory.
   1535 **
   1536 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
   1537 ** output buffer xFullPathname.  The exact size of the output buffer
   1538 ** is also passed as a parameter to both  methods. If the output buffer
   1539 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   1540 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   1541 ** to prevent this by setting mxPathname to a sufficiently large value.
   1542 **
   1543 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
   1544 ** interfaces are not strictly a part of the filesystem, but they are
   1545 ** included in the VFS structure for completeness.
   1546 ** The xRandomness() function attempts to return nBytes bytes
   1547 ** of good-quality randomness into zOut.  The return value is
   1548 ** the actual number of bytes of randomness obtained.
   1549 ** The xSleep() method causes the calling thread to sleep for at
   1550 ** least the number of microseconds given.  ^The xCurrentTime()
   1551 ** method returns a Julian Day Number for the current date and time as
   1552 ** a floating point value.
   1553 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
   1554 ** Day Number multiplied by 86400000 (the number of milliseconds in
   1555 ** a 24-hour day).
   1556 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
   1557 ** date and time if that method is available (if iVersion is 2 or
   1558 ** greater and the function pointer is not NULL) and will fall back
   1559 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
   1560 **
   1561 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
   1562 ** are not used by the SQLite core.  These optional interfaces are provided
   1563 ** by some VFSes to facilitate testing of the VFS code. By overriding
   1564 ** system calls with functions under its control, a test program can
   1565 ** simulate faults and error conditions that would otherwise be difficult
   1566 ** or impossible to induce.  The set of system calls that can be overridden
   1567 ** varies from one VFS to another, and from one version of the same VFS to the
   1568 ** next.  Applications that use these interfaces must be prepared for any
   1569 ** or all of these interfaces to be NULL or for their behavior to change
   1570 ** from one release to the next.  Applications must not attempt to access
   1571 ** any of these methods if the iVersion of the VFS is less than 3.
   1572 */
   1573 typedef struct sqlite3_vfs sqlite3_vfs;
   1574 typedef void (*sqlite3_syscall_ptr)(void);
   1575 struct sqlite3_vfs {
   1576   int iVersion;            /* Structure version number (currently 3) */
   1577   int szOsFile;            /* Size of subclassed sqlite3_file */
   1578   int mxPathname;          /* Maximum file pathname length */
   1579   sqlite3_vfs *pNext;      /* Next registered VFS */
   1580   const char *zName;       /* Name of this virtual file system */
   1581   void *pAppData;          /* Pointer to application-specific data */
   1582   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   1583                int flags, int *pOutFlags);
   1584   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   1585   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   1586   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   1587   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   1588   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   1589   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   1590   void (*xDlClose)(sqlite3_vfs*, void*);
   1591   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   1592   int (*xSleep)(sqlite3_vfs*, int microseconds);
   1593   int (*xCurrentTime)(sqlite3_vfs*, double*);
   1594   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   1595   /*
   1596   ** The methods above are in version 1 of the sqlite_vfs object
   1597   ** definition.  Those that follow are added in version 2 or later
   1598   */
   1599   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
   1600   /*
   1601   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
   1602   ** Those below are for version 3 and greater.
   1603   */
   1604   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
   1605   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
   1606   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
   1607   /*
   1608   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
   1609   ** New fields may be appended in figure versions.  The iVersion
   1610   ** value will increment whenever this happens.
   1611   */
   1612 };
   1613 
   1614 /*
   1615 ** CAPI3REF: Flags for the xAccess VFS method
   1616 **
   1617 ** These integer constants can be used as the third parameter to
   1618 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   1619 ** what kind of permissions the xAccess method is looking for.
   1620 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   1621 ** simply checks whether the file exists.
   1622 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   1623 ** checks whether the named directory is both readable and writable
   1624 ** (in other words, if files can be added, removed, and renamed within
   1625 ** the directory).
   1626 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
   1627 ** [temp_store_directory pragma], though this could change in a future
   1628 ** release of SQLite.
   1629 ** With SQLITE_ACCESS_READ, the xAccess method
   1630 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
   1631 ** currently unused, though it might be used in a future release of
   1632 ** SQLite.
   1633 */
   1634 #define SQLITE_ACCESS_EXISTS    0
   1635 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
   1636 #define SQLITE_ACCESS_READ      2   /* Unused */
   1637 
   1638 /*
   1639 ** CAPI3REF: Flags for the xShmLock VFS method
   1640 **
   1641 ** These integer constants define the various locking operations
   1642 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
   1643 ** following are the only legal combinations of flags to the
   1644 ** xShmLock method:
   1645 **
   1646 ** <ul>
   1647 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
   1648 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
   1649 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
   1650 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
   1651 ** </ul>
   1652 **
   1653 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
   1654 ** was given no the corresponding lock.
   1655 **
   1656 ** The xShmLock method can transition between unlocked and SHARED or
   1657 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
   1658 ** and EXCLUSIVE.
   1659 */
   1660 #define SQLITE_SHM_UNLOCK       1
   1661 #define SQLITE_SHM_LOCK         2
   1662 #define SQLITE_SHM_SHARED       4
   1663 #define SQLITE_SHM_EXCLUSIVE    8
   1664 
   1665 /*
   1666 ** CAPI3REF: Maximum xShmLock index
   1667 **
   1668 ** The xShmLock method on [sqlite3_io_methods] may use values
   1669 ** between 0 and this upper bound as its "offset" argument.
   1670 ** The SQLite core will never attempt to acquire or release a
   1671 ** lock outside of this range
   1672 */
   1673 #define SQLITE_SHM_NLOCK        8
   1674 
   1675 
   1676 /*
   1677 ** CAPI3REF: Initialize The SQLite Library
   1678 **
   1679 ** ^The sqlite3_initialize() routine initializes the
   1680 ** SQLite library.  ^The sqlite3_shutdown() routine
   1681 ** deallocates any resources that were allocated by sqlite3_initialize().
   1682 ** These routines are designed to aid in process initialization and
   1683 ** shutdown on embedded systems.  Workstation applications using
   1684 ** SQLite normally do not need to invoke either of these routines.
   1685 **
   1686 ** A call to sqlite3_initialize() is an "effective" call if it is
   1687 ** the first time sqlite3_initialize() is invoked during the lifetime of
   1688 ** the process, or if it is the first time sqlite3_initialize() is invoked
   1689 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   1690 ** of sqlite3_initialize() does any initialization.  All other calls
   1691 ** are harmless no-ops.)^
   1692 **
   1693 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   1694 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   1695 ** an effective call to sqlite3_shutdown() does any deinitialization.
   1696 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   1697 **
   1698 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   1699 ** is not.  The sqlite3_shutdown() interface must only be called from a
   1700 ** single thread.  All open [database connections] must be closed and all
   1701 ** other SQLite resources must be deallocated prior to invoking
   1702 ** sqlite3_shutdown().
   1703 **
   1704 ** Among other things, ^sqlite3_initialize() will invoke
   1705 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   1706 ** will invoke sqlite3_os_end().
   1707 **
   1708 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   1709 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   1710 ** the library (perhaps it is unable to allocate a needed resource such
   1711 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   1712 **
   1713 ** ^The sqlite3_initialize() routine is called internally by many other
   1714 ** SQLite interfaces so that an application usually does not need to
   1715 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   1716 ** calls sqlite3_initialize() so the SQLite library will be automatically
   1717 ** initialized when [sqlite3_open()] is called if it has not be initialized
   1718 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   1719 ** compile-time option, then the automatic calls to sqlite3_initialize()
   1720 ** are omitted and the application must call sqlite3_initialize() directly
   1721 ** prior to using any other SQLite interface.  For maximum portability,
   1722 ** it is recommended that applications always invoke sqlite3_initialize()
   1723 ** directly prior to using any other SQLite interface.  Future releases
   1724 ** of SQLite may require this.  In other words, the behavior exhibited
   1725 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   1726 ** default behavior in some future release of SQLite.
   1727 **
   1728 ** The sqlite3_os_init() routine does operating-system specific
   1729 ** initialization of the SQLite library.  The sqlite3_os_end()
   1730 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   1731 ** performed by these routines include allocation or deallocation
   1732 ** of static resources, initialization of global variables,
   1733 ** setting up a default [sqlite3_vfs] module, or setting up
   1734 ** a default configuration using [sqlite3_config()].
   1735 **
   1736 ** The application should never invoke either sqlite3_os_init()
   1737 ** or sqlite3_os_end() directly.  The application should only invoke
   1738 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   1739 ** interface is called automatically by sqlite3_initialize() and
   1740 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   1741 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   1742 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   1743 ** When [custom builds | built for other platforms]
   1744 ** (using the [SQLITE_OS_OTHER=1] compile-time
   1745 ** option) the application must supply a suitable implementation for
   1746 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   1747 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   1748 ** must return [SQLITE_OK] on success and some other [error code] upon
   1749 ** failure.
   1750 */
   1751 SQLITE_API int sqlite3_initialize(void);
   1752 SQLITE_API int sqlite3_shutdown(void);
   1753 SQLITE_API int sqlite3_os_init(void);
   1754 SQLITE_API int sqlite3_os_end(void);
   1755 
   1756 /*
   1757 ** CAPI3REF: Configuring The SQLite Library
   1758 **
   1759 ** The sqlite3_config() interface is used to make global configuration
   1760 ** changes to SQLite in order to tune SQLite to the specific needs of
   1761 ** the application.  The default configuration is recommended for most
   1762 ** applications and so this routine is usually not necessary.  It is
   1763 ** provided to support rare applications with unusual needs.
   1764 **
   1765 ** The sqlite3_config() interface is not threadsafe.  The application
   1766 ** must insure that no other SQLite interfaces are invoked by other
   1767 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
   1768 ** may only be invoked prior to library initialization using
   1769 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   1770 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   1771 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   1772 ** Note, however, that ^sqlite3_config() can be called as part of the
   1773 ** implementation of an application-defined [sqlite3_os_init()].
   1774 **
   1775 ** The first argument to sqlite3_config() is an integer
   1776 ** [configuration option] that determines
   1777 ** what property of SQLite is to be configured.  Subsequent arguments
   1778 ** vary depending on the [configuration option]
   1779 ** in the first argument.
   1780 **
   1781 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   1782 ** ^If the option is unknown or SQLite is unable to set the option
   1783 ** then this routine returns a non-zero [error code].
   1784 */
   1785 SQLITE_API int sqlite3_config(int, ...);
   1786 
   1787 /*
   1788 ** CAPI3REF: Configure database connections
   1789 **
   1790 ** The sqlite3_db_config() interface is used to make configuration
   1791 ** changes to a [database connection].  The interface is similar to
   1792 ** [sqlite3_config()] except that the changes apply to a single
   1793 ** [database connection] (specified in the first argument).
   1794 **
   1795 ** The second argument to sqlite3_db_config(D,V,...)  is the
   1796 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
   1797 ** that indicates what aspect of the [database connection] is being configured.
   1798 ** Subsequent arguments vary depending on the configuration verb.
   1799 **
   1800 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   1801 ** the call is considered successful.
   1802 */
   1803 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
   1804 
   1805 /*
   1806 ** CAPI3REF: Memory Allocation Routines
   1807 **
   1808 ** An instance of this object defines the interface between SQLite
   1809 ** and low-level memory allocation routines.
   1810 **
   1811 ** This object is used in only one place in the SQLite interface.
   1812 ** A pointer to an instance of this object is the argument to
   1813 ** [sqlite3_config()] when the configuration option is
   1814 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   1815 ** By creating an instance of this object
   1816 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   1817 ** during configuration, an application can specify an alternative
   1818 ** memory allocation subsystem for SQLite to use for all of its
   1819 ** dynamic memory needs.
   1820 **
   1821 ** Note that SQLite comes with several [built-in memory allocators]
   1822 ** that are perfectly adequate for the overwhelming majority of applications
   1823 ** and that this object is only useful to a tiny minority of applications
   1824 ** with specialized memory allocation requirements.  This object is
   1825 ** also used during testing of SQLite in order to specify an alternative
   1826 ** memory allocator that simulates memory out-of-memory conditions in
   1827 ** order to verify that SQLite recovers gracefully from such
   1828 ** conditions.
   1829 **
   1830 ** The xMalloc, xRealloc, and xFree methods must work like the
   1831 ** malloc(), realloc() and free() functions from the standard C library.
   1832 ** ^SQLite guarantees that the second argument to
   1833 ** xRealloc is always a value returned by a prior call to xRoundup.
   1834 **
   1835 ** xSize should return the allocated size of a memory allocation
   1836 ** previously obtained from xMalloc or xRealloc.  The allocated size
   1837 ** is always at least as big as the requested size but may be larger.
   1838 **
   1839 ** The xRoundup method returns what would be the allocated size of
   1840 ** a memory allocation given a particular requested size.  Most memory
   1841 ** allocators round up memory allocations at least to the next multiple
   1842 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   1843 ** Every memory allocation request coming in through [sqlite3_malloc()]
   1844 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   1845 ** that causes the corresponding memory allocation to fail.
   1846 **
   1847 ** The xInit method initializes the memory allocator.  (For example,
   1848 ** it might allocate any require mutexes or initialize internal data
   1849 ** structures.  The xShutdown method is invoked (indirectly) by
   1850 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   1851 ** by xInit.  The pAppData pointer is used as the only parameter to
   1852 ** xInit and xShutdown.
   1853 **
   1854 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   1855 ** the xInit method, so the xInit method need not be threadsafe.  The
   1856 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   1857 ** not need to be threadsafe either.  For all other methods, SQLite
   1858 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   1859 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   1860 ** it is by default) and so the methods are automatically serialized.
   1861 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   1862 ** methods must be threadsafe or else make their own arrangements for
   1863 ** serialization.
   1864 **
   1865 ** SQLite will never invoke xInit() more than once without an intervening
   1866 ** call to xShutdown().
   1867 */
   1868 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   1869 struct sqlite3_mem_methods {
   1870   void *(*xMalloc)(int);         /* Memory allocation function */
   1871   void (*xFree)(void*);          /* Free a prior allocation */
   1872   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   1873   int (*xSize)(void*);           /* Return the size of an allocation */
   1874   int (*xRoundup)(int);          /* Round up request size to allocation size */
   1875   int (*xInit)(void*);           /* Initialize the memory allocator */
   1876   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   1877   void *pAppData;                /* Argument to xInit() and xShutdown() */
   1878 };
   1879 
   1880 /*
   1881 ** CAPI3REF: Configuration Options
   1882 ** KEYWORDS: {configuration option}
   1883 **
   1884 ** These constants are the available integer configuration options that
   1885 ** can be passed as the first argument to the [sqlite3_config()] interface.
   1886 **
   1887 ** New configuration options may be added in future releases of SQLite.
   1888 ** Existing configuration options might be discontinued.  Applications
   1889 ** should check the return code from [sqlite3_config()] to make sure that
   1890 ** the call worked.  The [sqlite3_config()] interface will return a
   1891 ** non-zero [error code] if a discontinued or unsupported configuration option
   1892 ** is invoked.
   1893 **
   1894 ** <dl>
   1895 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   1896 ** <dd>There are no arguments to this option.  ^This option sets the
   1897 ** [threading mode] to Single-thread.  In other words, it disables
   1898 ** all mutexing and puts SQLite into a mode where it can only be used
   1899 ** by a single thread.   ^If SQLite is compiled with
   1900 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1901 ** it is not possible to change the [threading mode] from its default
   1902 ** value of Single-thread and so [sqlite3_config()] will return
   1903 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   1904 ** configuration option.</dd>
   1905 **
   1906 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   1907 ** <dd>There are no arguments to this option.  ^This option sets the
   1908 ** [threading mode] to Multi-thread.  In other words, it disables
   1909 ** mutexing on [database connection] and [prepared statement] objects.
   1910 ** The application is responsible for serializing access to
   1911 ** [database connections] and [prepared statements].  But other mutexes
   1912 ** are enabled so that SQLite will be safe to use in a multi-threaded
   1913 ** environment as long as no two threads attempt to use the same
   1914 ** [database connection] at the same time.  ^If SQLite is compiled with
   1915 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1916 ** it is not possible to set the Multi-thread [threading mode] and
   1917 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1918 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   1919 **
   1920 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
   1921 ** <dd>There are no arguments to this option.  ^This option sets the
   1922 ** [threading mode] to Serialized. In other words, this option enables
   1923 ** all mutexes including the recursive
   1924 ** mutexes on [database connection] and [prepared statement] objects.
   1925 ** In this mode (which is the default when SQLite is compiled with
   1926 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   1927 ** to [database connections] and [prepared statements] so that the
   1928 ** application is free to use the same [database connection] or the
   1929 ** same [prepared statement] in different threads at the same time.
   1930 ** ^If SQLite is compiled with
   1931 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1932 ** it is not possible to set the Serialized [threading mode] and
   1933 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1934 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   1935 **
   1936 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
   1937 ** <dd> ^(This option takes a single argument which is a pointer to an
   1938 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
   1939 ** alternative low-level memory allocation routines to be used in place of
   1940 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   1941 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   1942 ** before the [sqlite3_config()] call returns.</dd>
   1943 **
   1944 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
   1945 ** <dd> ^(This option takes a single argument which is a pointer to an
   1946 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
   1947 ** structure is filled with the currently defined memory allocation routines.)^
   1948 ** This option can be used to overload the default memory allocation
   1949 ** routines with a wrapper that simulations memory allocation failure or
   1950 ** tracks memory usage, for example. </dd>
   1951 **
   1952 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   1953 ** <dd> ^This option takes single argument of type int, interpreted as a
   1954 ** boolean, which enables or disables the collection of memory allocation
   1955 ** statistics. ^(When memory allocation statistics are disabled, the
   1956 ** following SQLite interfaces become non-operational:
   1957 **   <ul>
   1958 **   <li> [sqlite3_memory_used()]
   1959 **   <li> [sqlite3_memory_highwater()]
   1960 **   <li> [sqlite3_soft_heap_limit64()]
   1961 **   <li> [sqlite3_status()]
   1962 **   </ul>)^
   1963 ** ^Memory allocation statistics are enabled by default unless SQLite is
   1964 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   1965 ** allocation statistics are disabled by default.
   1966 ** </dd>
   1967 **
   1968 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
   1969 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1970 ** scratch memory.  There are three arguments:  A pointer an 8-byte
   1971 ** aligned memory buffer from which the scratch allocations will be
   1972 ** drawn, the size of each scratch allocation (sz),
   1973 ** and the maximum number of scratch allocations (N).  The sz
   1974 ** argument must be a multiple of 16.
   1975 ** The first argument must be a pointer to an 8-byte aligned buffer
   1976 ** of at least sz*N bytes of memory.
   1977 ** ^SQLite will use no more than two scratch buffers per thread.  So
   1978 ** N should be set to twice the expected maximum number of threads.
   1979 ** ^SQLite will never require a scratch buffer that is more than 6
   1980 ** times the database page size. ^If SQLite needs needs additional
   1981 ** scratch memory beyond what is provided by this configuration option, then
   1982 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
   1983 **
   1984 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
   1985 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1986 ** the database page cache with the default page cache implementation.
   1987 ** This configuration should not be used if an application-define page
   1988 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
   1989 ** There are three arguments to this option: A pointer to 8-byte aligned
   1990 ** memory, the size of each page buffer (sz), and the number of pages (N).
   1991 ** The sz argument should be the size of the largest database page
   1992 ** (a power of two between 512 and 32768) plus a little extra for each
   1993 ** page header.  ^The page header size is 20 to 40 bytes depending on
   1994 ** the host architecture.  ^It is harmless, apart from the wasted memory,
   1995 ** to make sz a little too large.  The first
   1996 ** argument should point to an allocation of at least sz*N bytes of memory.
   1997 ** ^SQLite will use the memory provided by the first argument to satisfy its
   1998 ** memory needs for the first N pages that it adds to cache.  ^If additional
   1999 ** page cache memory is needed beyond what is provided by this option, then
   2000 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
   2001 ** The pointer in the first argument must
   2002 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
   2003 ** will be undefined.</dd>
   2004 **
   2005 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
   2006 ** <dd> ^This option specifies a static memory buffer that SQLite will use
   2007 ** for all of its dynamic memory allocation needs beyond those provided
   2008 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
   2009 ** There are three arguments: An 8-byte aligned pointer to the memory,
   2010 ** the number of bytes in the memory buffer, and the minimum allocation size.
   2011 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   2012 ** to using its default memory allocator (the system malloc() implementation),
   2013 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   2014 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
   2015 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
   2016 ** allocator is engaged to handle all of SQLites memory allocation needs.
   2017 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   2018 ** boundary or subsequent behavior of SQLite will be undefined.
   2019 ** The minimum allocation size is capped at 2**12. Reasonable values
   2020 ** for the minimum allocation size are 2**5 through 2**8.</dd>
   2021 **
   2022 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
   2023 ** <dd> ^(This option takes a single argument which is a pointer to an
   2024 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
   2025 ** alternative low-level mutex routines to be used in place
   2026 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
   2027 ** content of the [sqlite3_mutex_methods] structure before the call to
   2028 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   2029 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2030 ** the entire mutexing subsystem is omitted from the build and hence calls to
   2031 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   2032 ** return [SQLITE_ERROR].</dd>
   2033 **
   2034 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
   2035 ** <dd> ^(This option takes a single argument which is a pointer to an
   2036 ** instance of the [sqlite3_mutex_methods] structure.  The
   2037 ** [sqlite3_mutex_methods]
   2038 ** structure is filled with the currently defined mutex routines.)^
   2039 ** This option can be used to overload the default mutex allocation
   2040 ** routines with a wrapper used to track mutex usage for performance
   2041 ** profiling or testing, for example.   ^If SQLite is compiled with
   2042 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   2043 ** the entire mutexing subsystem is omitted from the build and hence calls to
   2044 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   2045 ** return [SQLITE_ERROR].</dd>
   2046 **
   2047 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   2048 ** <dd> ^(This option takes two arguments that determine the default
   2049 ** memory allocation for the lookaside memory allocator on each
   2050 ** [database connection].  The first argument is the
   2051 ** size of each lookaside buffer slot and the second is the number of
   2052 ** slots allocated to each database connection.)^  ^(This option sets the
   2053 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   2054 ** verb to [sqlite3_db_config()] can be used to change the lookaside
   2055 ** configuration on individual connections.)^ </dd>
   2056 **
   2057 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
   2058 ** <dd> ^(This option takes a single argument which is a pointer to
   2059 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
   2060 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
   2061 ** object and uses it for page cache memory allocations.</dd>
   2062 **
   2063 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
   2064 ** <dd> ^(This option takes a single argument which is a pointer to an
   2065 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
   2066 ** page cache implementation into that object.)^ </dd>
   2067 **
   2068 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
   2069 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
   2070 ** function with a call signature of void(*)(void*,int,const char*),
   2071 ** and a pointer to void. ^If the function pointer is not NULL, it is
   2072 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
   2073 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
   2074 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
   2075 ** passed through as the first parameter to the application-defined logger
   2076 ** function whenever that function is invoked.  ^The second parameter to
   2077 ** the logger function is a copy of the first parameter to the corresponding
   2078 ** [sqlite3_log()] call and is intended to be a [result code] or an
   2079 ** [extended result code].  ^The third parameter passed to the logger is
   2080 ** log message after formatting via [sqlite3_snprintf()].
   2081 ** The SQLite logging interface is not reentrant; the logger function
   2082 ** supplied by the application must not invoke any SQLite interface.
   2083 ** In a multi-threaded application, the application-defined logger
   2084 ** function must be threadsafe. </dd>
   2085 **
   2086 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
   2087 ** <dd> This option takes a single argument of type int. If non-zero, then
   2088 ** URI handling is globally enabled. If the parameter is zero, then URI handling
   2089 ** is globally disabled. If URI handling is globally enabled, all filenames
   2090 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
   2091 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
   2092 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
   2093 ** connection is opened. If it is globally disabled, filenames are
   2094 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
   2095 ** database connection is opened. By default, URI handling is globally
   2096 ** disabled. The default value may be changed by compiling with the
   2097 ** [SQLITE_USE_URI] symbol defined.
   2098 **
   2099 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
   2100 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFNIG_GETPCACHE
   2101 ** <dd> These options are obsolete and should not be used by new code.
   2102 ** They are retained for backwards compatibility but are now no-ops.
   2103 ** </dl>
   2104 */
   2105 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   2106 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   2107 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   2108 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   2109 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   2110 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
   2111 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   2112 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   2113 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   2114 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   2115 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   2116 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   2117 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   2118 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
   2119 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
   2120 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   2121 #define SQLITE_CONFIG_URI          17  /* int */
   2122 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
   2123 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
   2124 
   2125 /*
   2126 ** CAPI3REF: Database Connection Configuration Options
   2127 **
   2128 ** These constants are the available integer configuration options that
   2129 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   2130 **
   2131 ** New configuration options may be added in future releases of SQLite.
   2132 ** Existing configuration options might be discontinued.  Applications
   2133 ** should check the return code from [sqlite3_db_config()] to make sure that
   2134 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   2135 ** non-zero [error code] if a discontinued or unsupported configuration option
   2136 ** is invoked.
   2137 **
   2138 ** <dl>
   2139 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   2140 ** <dd> ^This option takes three additional arguments that determine the
   2141 ** [lookaside memory allocator] configuration for the [database connection].
   2142 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   2143 ** pointer to a memory buffer to use for lookaside memory.
   2144 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   2145 ** may be NULL in which case SQLite will allocate the
   2146 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   2147 ** size of each lookaside buffer slot.  ^The third argument is the number of
   2148 ** slots.  The size of the buffer in the first argument must be greater than
   2149 ** or equal to the product of the second and third arguments.  The buffer
   2150 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   2151 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   2152 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
   2153 ** configuration for a database connection can only be changed when that
   2154 ** connection is not currently using lookaside memory, or in other words
   2155 ** when the "current value" returned by
   2156 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
   2157 ** Any attempt to change the lookaside memory configuration when lookaside
   2158 ** memory is in use leaves the configuration unchanged and returns
   2159 ** [SQLITE_BUSY].)^</dd>
   2160 **
   2161 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
   2162 ** <dd> ^This option is used to enable or disable the enforcement of
   2163 ** [foreign key constraints].  There should be two additional arguments.
   2164 ** The first argument is an integer which is 0 to disable FK enforcement,
   2165 ** positive to enable FK enforcement or negative to leave FK enforcement
   2166 ** unchanged.  The second parameter is a pointer to an integer into which
   2167 ** is written 0 or 1 to indicate whether FK enforcement is off or on
   2168 ** following this call.  The second parameter may be a NULL pointer, in
   2169 ** which case the FK enforcement setting is not reported back. </dd>
   2170 **
   2171 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
   2172 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
   2173 ** There should be two additional arguments.
   2174 ** The first argument is an integer which is 0 to disable triggers,
   2175 ** positive to enable triggers or negative to leave the setting unchanged.
   2176 ** The second parameter is a pointer to an integer into which
   2177 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
   2178 ** following this call.  The second parameter may be a NULL pointer, in
   2179 ** which case the trigger setting is not reported back. </dd>
   2180 **
   2181 ** </dl>
   2182 */
   2183 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
   2184 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
   2185 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
   2186 
   2187 
   2188 /*
   2189 ** CAPI3REF: Enable Or Disable Extended Result Codes
   2190 **
   2191 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   2192 ** [extended result codes] feature of SQLite. ^The extended result
   2193 ** codes are disabled by default for historical compatibility.
   2194 */
   2195 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   2196 
   2197 /*
   2198 ** CAPI3REF: Last Insert Rowid
   2199 **
   2200 ** ^Each entry in an SQLite table has a unique 64-bit signed
   2201 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   2202 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   2203 ** names are not also used by explicitly declared columns. ^If
   2204 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   2205 ** is another alias for the rowid.
   2206 **
   2207 ** ^This routine returns the [rowid] of the most recent
   2208 ** successful [INSERT] into the database from the [database connection]
   2209 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
   2210 ** records the last insert rowid of both ordinary tables and [virtual tables].
   2211 ** ^If no successful [INSERT]s
   2212 ** have ever occurred on that database connection, zero is returned.
   2213 **
   2214 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
   2215 ** method, then this routine will return the [rowid] of the inserted
   2216 ** row as long as the trigger or virtual table method is running.
   2217 ** But once the trigger or virtual table method ends, the value returned
   2218 ** by this routine reverts to what it was before the trigger or virtual
   2219 ** table method began.)^
   2220 **
   2221 ** ^An [INSERT] that fails due to a constraint violation is not a
   2222 ** successful [INSERT] and does not change the value returned by this
   2223 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   2224 ** and INSERT OR ABORT make no changes to the return value of this
   2225 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   2226 ** encounters a constraint violation, it does not fail.  The
   2227 ** INSERT continues to completion after deleting rows that caused
   2228 ** the constraint problem so INSERT OR REPLACE will always change
   2229 ** the return value of this interface.)^
   2230 **
   2231 ** ^For the purposes of this routine, an [INSERT] is considered to
   2232 ** be successful even if it is subsequently rolled back.
   2233 **
   2234 ** This function is accessible to SQL statements via the
   2235 ** [last_insert_rowid() SQL function].
   2236 **
   2237 ** If a separate thread performs a new [INSERT] on the same
   2238 ** database connection while the [sqlite3_last_insert_rowid()]
   2239 ** function is running and thus changes the last insert [rowid],
   2240 ** then the value returned by [sqlite3_last_insert_rowid()] is
   2241 ** unpredictable and might not equal either the old or the new
   2242 ** last insert [rowid].
   2243 */
   2244 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   2245 
   2246 /*
   2247 ** CAPI3REF: Count The Number Of Rows Modified
   2248 **
   2249 ** ^This function returns the number of database rows that were changed
   2250 ** or inserted or deleted by the most recently completed SQL statement
   2251 ** on the [database connection] specified by the first parameter.
   2252 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
   2253 ** or [DELETE] statement are counted.  Auxiliary changes caused by
   2254 ** triggers or [foreign key actions] are not counted.)^ Use the
   2255 ** [sqlite3_total_changes()] function to find the total number of changes
   2256 ** including changes caused by triggers and foreign key actions.
   2257 **
   2258 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
   2259 ** are not counted.  Only real table changes are counted.
   2260 **
   2261 ** ^(A "row change" is a change to a single row of a single table
   2262 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
   2263 ** are changed as side effects of [REPLACE] constraint resolution,
   2264 ** rollback, ABORT processing, [DROP TABLE], or by any other
   2265 ** mechanisms do not count as direct row changes.)^
   2266 **
   2267 ** A "trigger context" is a scope of execution that begins and
   2268 ** ends with the script of a [CREATE TRIGGER | trigger].
   2269 ** Most SQL statements are
   2270 ** evaluated outside of any trigger.  This is the "top level"
   2271 ** trigger context.  If a trigger fires from the top level, a
   2272 ** new trigger context is entered for the duration of that one
   2273 ** trigger.  Subtriggers create subcontexts for their duration.
   2274 **
   2275 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
   2276 ** not create a new trigger context.
   2277 **
   2278 ** ^This function returns the number of direct row changes in the
   2279 ** most recent INSERT, UPDATE, or DELETE statement within the same
   2280 ** trigger context.
   2281 **
   2282 ** ^Thus, when called from the top level, this function returns the
   2283 ** number of changes in the most recent INSERT, UPDATE, or DELETE
   2284 ** that also occurred at the top level.  ^(Within the body of a trigger,
   2285 ** the sqlite3_changes() interface can be called to find the number of
   2286 ** changes in the most recently completed INSERT, UPDATE, or DELETE
   2287 ** statement within the body of the same trigger.
   2288 ** However, the number returned does not include changes
   2289 ** caused by subtriggers since those have their own context.)^
   2290 **
   2291 ** See also the [sqlite3_total_changes()] interface, the
   2292 ** [count_changes pragma], and the [changes() SQL function].
   2293 **
   2294 ** If a separate thread makes changes on the same database connection
   2295 ** while [sqlite3_changes()] is running then the value returned
   2296 ** is unpredictable and not meaningful.
   2297 */
   2298 SQLITE_API int sqlite3_changes(sqlite3*);
   2299 
   2300 /*
   2301 ** CAPI3REF: Total Number Of Rows Modified
   2302 **
   2303 ** ^This function returns the number of row changes caused by [INSERT],
   2304 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
   2305 ** ^(The count returned by sqlite3_total_changes() includes all changes
   2306 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
   2307 ** [foreign key actions]. However,
   2308 ** the count does not include changes used to implement [REPLACE] constraints,
   2309 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
   2310 ** count does not include rows of views that fire an [INSTEAD OF trigger],
   2311 ** though if the INSTEAD OF trigger makes changes of its own, those changes
   2312 ** are counted.)^
   2313 ** ^The sqlite3_total_changes() function counts the changes as soon as
   2314 ** the statement that makes them is completed (when the statement handle
   2315 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
   2316 **
   2317 ** See also the [sqlite3_changes()] interface, the
   2318 ** [count_changes pragma], and the [total_changes() SQL function].
   2319 **
   2320 ** If a separate thread makes changes on the same database connection
   2321 ** while [sqlite3_total_changes()] is running then the value
   2322 ** returned is unpredictable and not meaningful.
   2323 */
   2324 SQLITE_API int sqlite3_total_changes(sqlite3*);
   2325 
   2326 /*
   2327 ** CAPI3REF: Interrupt A Long-Running Query
   2328 **
   2329 ** ^This function causes any pending database operation to abort and
   2330 ** return at its earliest opportunity. This routine is typically
   2331 ** called in response to a user action such as pressing "Cancel"
   2332 ** or Ctrl-C where the user wants a long query operation to halt
   2333 ** immediately.
   2334 **
   2335 ** ^It is safe to call this routine from a thread different from the
   2336 ** thread that is currently running the database operation.  But it
   2337 ** is not safe to call this routine with a [database connection] that
   2338 ** is closed or might close before sqlite3_interrupt() returns.
   2339 **
   2340 ** ^If an SQL operation is very nearly finished at the time when
   2341 ** sqlite3_interrupt() is called, then it might not have an opportunity
   2342 ** to be interrupted and might continue to completion.
   2343 **
   2344 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   2345 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   2346 ** that is inside an explicit transaction, then the entire transaction
   2347 ** will be rolled back automatically.
   2348 **
   2349 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   2350 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   2351 ** that are started after the sqlite3_interrupt() call and before the
   2352 ** running statements reaches zero are interrupted as if they had been
   2353 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   2354 ** that are started after the running statement count reaches zero are
   2355 ** not effected by the sqlite3_interrupt().
   2356 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   2357 ** SQL statements is a no-op and has no effect on SQL statements
   2358 ** that are started after the sqlite3_interrupt() call returns.
   2359 **
   2360 ** If the database connection closes while [sqlite3_interrupt()]
   2361 ** is running then bad things will likely happen.
   2362 */
   2363 SQLITE_API void sqlite3_interrupt(sqlite3*);
   2364 
   2365 /*
   2366 ** CAPI3REF: Determine If An SQL Statement Is Complete
   2367 **
   2368 ** These routines are useful during command-line input to determine if the
   2369 ** currently entered text seems to form a complete SQL statement or
   2370 ** if additional input is needed before sending the text into
   2371 ** SQLite for parsing.  ^These routines return 1 if the input string
   2372 ** appears to be a complete SQL statement.  ^A statement is judged to be
   2373 ** complete if it ends with a semicolon token and is not a prefix of a
   2374 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   2375 ** string literals or quoted identifier names or comments are not
   2376 ** independent tokens (they are part of the token in which they are
   2377 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   2378 ** and comments that follow the final semicolon are ignored.
   2379 **
   2380 ** ^These routines return 0 if the statement is incomplete.  ^If a
   2381 ** memory allocation fails, then SQLITE_NOMEM is returned.
   2382 **
   2383 ** ^These routines do not parse the SQL statements thus
   2384 ** will not detect syntactically incorrect SQL.
   2385 **
   2386 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   2387 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   2388 ** automatically by sqlite3_complete16().  If that initialization fails,
   2389 ** then the return value from sqlite3_complete16() will be non-zero
   2390 ** regardless of whether or not the input SQL is complete.)^
   2391 **
   2392 ** The input to [sqlite3_complete()] must be a zero-terminated
   2393 ** UTF-8 string.
   2394 **
   2395 ** The input to [sqlite3_complete16()] must be a zero-terminated
   2396 ** UTF-16 string in native byte order.
   2397 */
   2398 SQLITE_API int sqlite3_complete(const char *sql);
   2399 SQLITE_API int sqlite3_complete16(const void *sql);
   2400 
   2401 /*
   2402 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   2403 **
   2404 ** ^This routine sets a callback function that might be invoked whenever
   2405 ** an attempt is made to open a database table that another thread
   2406 ** or process has locked.
   2407 **
   2408 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
   2409 ** is returned immediately upon encountering the lock.  ^If the busy callback
   2410 ** is not NULL, then the callback might be invoked with two arguments.
   2411 **
   2412 ** ^The first argument to the busy handler is a copy of the void* pointer which
   2413 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   2414 ** the busy handler callback is the number of times that the busy handler has
   2415 ** been invoked for this locking event.  ^If the
   2416 ** busy callback returns 0, then no additional attempts are made to
   2417 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
   2418 ** ^If the callback returns non-zero, then another attempt
   2419 ** is made to open the database for reading and the cycle repeats.
   2420 **
   2421 ** The presence of a busy handler does not guarantee that it will be invoked
   2422 ** when there is lock contention. ^If SQLite determines that invoking the busy
   2423 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   2424 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
   2425 ** Consider a scenario where one process is holding a read lock that
   2426 ** it is trying to promote to a reserved lock and
   2427 ** a second process is holding a reserved lock that it is trying
   2428 ** to promote to an exclusive lock.  The first process cannot proceed
   2429 ** because it is blocked by the second and the second process cannot
   2430 ** proceed because it is blocked by the first.  If both processes
   2431 ** invoke the busy handlers, neither will make any progress.  Therefore,
   2432 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   2433 ** will induce the first process to release its read lock and allow
   2434 ** the second process to proceed.
   2435 **
   2436 ** ^The default busy callback is NULL.
   2437 **
   2438 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
   2439 ** when SQLite is in the middle of a large transaction where all the
   2440 ** changes will not fit into the in-memory cache.  SQLite will
   2441 ** already hold a RESERVED lock on the database file, but it needs
   2442 ** to promote this lock to EXCLUSIVE so that it can spill cache
   2443 ** pages into the database file without harm to concurrent
   2444 ** readers.  ^If it is unable to promote the lock, then the in-memory
   2445 ** cache will be left in an inconsistent state and so the error
   2446 ** code is promoted from the relatively benign [SQLITE_BUSY] to
   2447 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
   2448 ** forces an automatic rollback of the changes.  See the
   2449 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
   2450 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
   2451 ** this is important.
   2452 **
   2453 ** ^(There can only be a single busy handler defined for each
   2454 ** [database connection].  Setting a new busy handler clears any
   2455 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   2456 ** will also set or clear the busy handler.
   2457 **
   2458 ** The busy callback should not take any actions which modify the
   2459 ** database connection that invoked the busy handler.  Any such actions
   2460 ** result in undefined behavior.
   2461 **
   2462 ** A busy handler must not close the database connection
   2463 ** or [prepared statement] that invoked the busy handler.
   2464 */
   2465 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
   2466 
   2467 /*
   2468 ** CAPI3REF: Set A Busy Timeout
   2469 **
   2470 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   2471 ** for a specified amount of time when a table is locked.  ^The handler
   2472 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   2473 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   2474 ** the handler returns 0 which causes [sqlite3_step()] to return
   2475 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
   2476 **
   2477 ** ^Calling this routine with an argument less than or equal to zero
   2478 ** turns off all busy handlers.
   2479 **
   2480 ** ^(There can only be a single busy handler for a particular
   2481 ** [database connection] any any given moment.  If another busy handler
   2482 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   2483 ** this routine, that other busy handler is cleared.)^
   2484 */
   2485 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   2486 
   2487 /*
   2488 ** CAPI3REF: Convenience Routines For Running Queries
   2489 **
   2490 ** This is a legacy interface that is preserved for backwards compatibility.
   2491 ** Use of this interface is not recommended.
   2492 **
   2493 ** Definition: A <b>result table</b> is memory data structure created by the
   2494 ** [sqlite3_get_table()] interface.  A result table records the
   2495 ** complete query results from one or more queries.
   2496 **
   2497 ** The table conceptually has a number of rows and columns.  But
   2498 ** these numbers are not part of the result table itself.  These
   2499 ** numbers are obtained separately.  Let N be the number of rows
   2500 ** and M be the number of columns.
   2501 **
   2502 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   2503 ** There are (N+1)*M elements in the array.  The first M pointers point
   2504 ** to zero-terminated strings that  contain the names of the columns.
   2505 ** The remaining entries all point to query results.  NULL values result
   2506 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   2507 ** string representation as returned by [sqlite3_column_text()].
   2508 **
   2509 ** A result table might consist of one or more memory allocations.
   2510 ** It is not safe to pass a result table directly to [sqlite3_free()].
   2511 ** A result table should be deallocated using [sqlite3_free_table()].
   2512 **
   2513 ** ^(As an example of the result table format, suppose a query result
   2514 ** is as follows:
   2515 **
   2516 ** <blockquote><pre>
   2517 **        Name        | Age
   2518 **        -----------------------
   2519 **        Alice       | 43
   2520 **        Bob         | 28
   2521 **        Cindy       | 21
   2522 ** </pre></blockquote>
   2523 **
   2524 ** There are two column (M==2) and three rows (N==3).  Thus the
   2525 ** result table has 8 entries.  Suppose the result table is stored
   2526 ** in an array names azResult.  Then azResult holds this content:
   2527 **
   2528 ** <blockquote><pre>
   2529 **        azResult&#91;0] = "Name";
   2530 **        azResult&#91;1] = "Age";
   2531 **        azResult&#91;2] = "Alice";
   2532 **        azResult&#91;3] = "43";
   2533 **        azResult&#91;4] = "Bob";
   2534 **        azResult&#91;5] = "28";
   2535 **        azResult&#91;6] = "Cindy";
   2536 **        azResult&#91;7] = "21";
   2537 ** </pre></blockquote>)^
   2538 **
   2539 ** ^The sqlite3_get_table() function evaluates one or more
   2540 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   2541 ** string of its 2nd parameter and returns a result table to the
   2542 ** pointer given in its 3rd parameter.
   2543 **
   2544 ** After the application has finished with the result from sqlite3_get_table(),
   2545 ** it must pass the result table pointer to sqlite3_free_table() in order to
   2546 ** release the memory that was malloced.  Because of the way the
   2547 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   2548 ** function must not try to call [sqlite3_free()] directly.  Only
   2549 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   2550 **
   2551 ** The sqlite3_get_table() interface is implemented as a wrapper around
   2552 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   2553 ** to any internal data structures of SQLite.  It uses only the public
   2554 ** interface defined here.  As a consequence, errors that occur in the
   2555 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   2556 ** reflected in subsequent calls to [sqlite3_errcode()] or
   2557 ** [sqlite3_errmsg()].
   2558 */
   2559 SQLITE_API int sqlite3_get_table(
   2560   sqlite3 *db,          /* An open database */
   2561   const char *zSql,     /* SQL to be evaluated */
   2562   char ***pazResult,    /* Results of the query */
   2563   int *pnRow,           /* Number of result rows written here */
   2564   int *pnColumn,        /* Number of result columns written here */
   2565   char **pzErrmsg       /* Error msg written here */
   2566 );
   2567 SQLITE_API void sqlite3_free_table(char **result);
   2568 
   2569 /*
   2570 ** CAPI3REF: Formatted String Printing Functions
   2571 **
   2572 ** These routines are work-alikes of the "printf()" family of functions
   2573 ** from the standard C library.
   2574 **
   2575 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   2576 ** results into memory obtained from [sqlite3_malloc()].
   2577 ** The strings returned by these two routines should be
   2578 ** released by [sqlite3_free()].  ^Both routines return a
   2579 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   2580 ** memory to hold the resulting string.
   2581 **
   2582 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
   2583 ** the standard C library.  The result is written into the
   2584 ** buffer supplied as the second parameter whose size is given by
   2585 ** the first parameter. Note that the order of the
   2586 ** first two parameters is reversed from snprintf().)^  This is an
   2587 ** historical accident that cannot be fixed without breaking
   2588 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   2589 ** returns a pointer to its buffer instead of the number of
   2590 ** characters actually written into the buffer.)^  We admit that
   2591 ** the number of characters written would be a more useful return
   2592 ** value but we cannot change the implementation of sqlite3_snprintf()
   2593 ** now without breaking compatibility.
   2594 **
   2595 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   2596 ** guarantees that the buffer is always zero-terminated.  ^The first
   2597 ** parameter "n" is the total size of the buffer, including space for
   2598 ** the zero terminator.  So the longest string that can be completely
   2599 ** written will be n-1 characters.
   2600 **
   2601 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
   2602 **
   2603 ** These routines all implement some additional formatting
   2604 ** options that are useful for constructing SQL statements.
   2605 ** All of the usual printf() formatting options apply.  In addition, there
   2606 ** is are "%q", "%Q", and "%z" options.
   2607 **
   2608 ** ^(The %q option works like %s in that it substitutes a nul-terminated
   2609 ** string from the argument list.  But %q also doubles every '\'' character.
   2610 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   2611 ** character it escapes that character and allows it to be inserted into
   2612 ** the string.
   2613 **
   2614 ** For example, assume the string variable zText contains text as follows:
   2615 **
   2616 ** <blockquote><pre>
   2617 **  char *zText = "It's a happy day!";
   2618 ** </pre></blockquote>
   2619 **
   2620 ** One can use this text in an SQL statement as follows:
   2621 **
   2622 ** <blockquote><pre>
   2623 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   2624 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2625 **  sqlite3_free(zSQL);
   2626 ** </pre></blockquote>
   2627 **
   2628 ** Because the %q format string is used, the '\'' character in zText
   2629 ** is escaped and the SQL generated is as follows:
   2630 **
   2631 ** <blockquote><pre>
   2632 **  INSERT INTO table1 VALUES('It''s a happy day!')
   2633 ** </pre></blockquote>
   2634 **
   2635 ** This is correct.  Had we used %s instead of %q, the generated SQL
   2636 ** would have looked like this:
   2637 **
   2638 ** <blockquote><pre>
   2639 **  INSERT INTO table1 VALUES('It's a happy day!');
   2640 ** </pre></blockquote>
   2641 **
   2642 ** This second example is an SQL syntax error.  As a general rule you should
   2643 ** always use %q instead of %s when inserting text into a string literal.
   2644 **
   2645 ** ^(The %Q option works like %q except it also adds single quotes around
   2646 ** the outside of the total string.  Additionally, if the parameter in the
   2647 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   2648 ** single quotes).)^  So, for example, one could say:
   2649 **
   2650 ** <blockquote><pre>
   2651 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   2652 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2653 **  sqlite3_free(zSQL);
   2654 ** </pre></blockquote>
   2655 **
   2656 ** The code above will render a correct SQL statement in the zSQL
   2657 ** variable even if the zText variable is a NULL pointer.
   2658 **
   2659 ** ^(The "%z" formatting option works like "%s" but with the
   2660 ** addition that after the string has been read and copied into
   2661 ** the result, [sqlite3_free()] is called on the input string.)^
   2662 */
   2663 SQLITE_API char *sqlite3_mprintf(const char*,...);
   2664 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   2665 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   2666 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
   2667 
   2668 /*
   2669 ** CAPI3REF: Memory Allocation Subsystem
   2670 **
   2671 ** The SQLite core uses these three routines for all of its own
   2672 ** internal memory allocation needs. "Core" in the previous sentence
   2673 ** does not include operating-system specific VFS implementation.  The
   2674 ** Windows VFS uses native malloc() and free() for some operations.
   2675 **
   2676 ** ^The sqlite3_malloc() routine returns a pointer to a block
   2677 ** of memory at least N bytes in length, where N is the parameter.
   2678 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   2679 ** memory, it returns a NULL pointer.  ^If the parameter N to
   2680 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   2681 ** a NULL pointer.
   2682 **
   2683 ** ^Calling sqlite3_free() with a pointer previously returned
   2684 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   2685 ** that it might be reused.  ^The sqlite3_free() routine is
   2686 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   2687 ** to sqlite3_free() is harmless.  After being freed, memory
   2688 ** should neither be read nor written.  Even reading previously freed
   2689 ** memory might result in a segmentation fault or other severe error.
   2690 ** Memory corruption, a segmentation fault, or other severe error
   2691 ** might result if sqlite3_free() is called with a non-NULL pointer that
   2692 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   2693 **
   2694 ** ^(The sqlite3_realloc() interface attempts to resize a
   2695 ** prior memory allocation to be at least N bytes, where N is the
   2696 ** second parameter.  The memory allocation to be resized is the first
   2697 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
   2698 ** is a NULL pointer then its behavior is identical to calling
   2699 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
   2700 ** ^If the second parameter to sqlite3_realloc() is zero or
   2701 ** negative then the behavior is exactly the same as calling
   2702 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
   2703 ** ^sqlite3_realloc() returns a pointer to a memory allocation
   2704 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
   2705 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   2706 ** of the prior allocation are copied into the beginning of buffer returned
   2707 ** by sqlite3_realloc() and the prior allocation is freed.
   2708 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
   2709 ** is not freed.
   2710 **
   2711 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
   2712 ** is always aligned to at least an 8 byte boundary, or to a
   2713 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
   2714 ** option is used.
   2715 **
   2716 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   2717 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   2718 ** implementation of these routines to be omitted.  That capability
   2719 ** is no longer provided.  Only built-in memory allocators can be used.
   2720 **
   2721 ** The Windows OS interface layer calls
   2722 ** the system malloc() and free() directly when converting
   2723 ** filenames between the UTF-8 encoding used by SQLite
   2724 ** and whatever filename encoding is used by the particular Windows
   2725 ** installation.  Memory allocation errors are detected, but
   2726 ** they are reported back as [SQLITE_CANTOPEN] or
   2727 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   2728 **
   2729 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   2730 ** must be either NULL or else pointers obtained from a prior
   2731 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   2732 ** not yet been released.
   2733 **
   2734 ** The application must not read or write any part of
   2735 ** a block of memory after it has been released using
   2736 ** [sqlite3_free()] or [sqlite3_realloc()].
   2737 */
   2738 SQLITE_API void *sqlite3_malloc(int);
   2739 SQLITE_API void *sqlite3_realloc(void*, int);
   2740 SQLITE_API void sqlite3_free(void*);
   2741 
   2742 /*
   2743 ** CAPI3REF: Memory Allocator Statistics
   2744 **
   2745 ** SQLite provides these two interfaces for reporting on the status
   2746 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   2747 ** routines, which form the built-in memory allocation subsystem.
   2748 **
   2749 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   2750 ** of memory currently outstanding (malloced but not freed).
   2751 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   2752 ** value of [sqlite3_memory_used()] since the high-water mark
   2753 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   2754 ** [sqlite3_memory_highwater()] include any overhead
   2755 ** added by SQLite in its implementation of [sqlite3_malloc()],
   2756 ** but not overhead added by the any underlying system library
   2757 ** routines that [sqlite3_malloc()] may call.
   2758 **
   2759 ** ^The memory high-water mark is reset to the current value of
   2760 ** [sqlite3_memory_used()] if and only if the parameter to
   2761 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   2762 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   2763 ** prior to the reset.
   2764 */
   2765 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   2766 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   2767 
   2768 /*
   2769 ** CAPI3REF: Pseudo-Random Number Generator
   2770 **
   2771 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   2772 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   2773 ** already uses the largest possible [ROWID].  The PRNG is also used for
   2774 ** the build-in random() and randomblob() SQL functions.  This interface allows
   2775 ** applications to access the same PRNG for other purposes.
   2776 **
   2777 ** ^A call to this routine stores N bytes of randomness into buffer P.
   2778 **
   2779 ** ^The first time this routine is invoked (either internally or by
   2780 ** the application) the PRNG is seeded using randomness obtained
   2781 ** from the xRandomness method of the default [sqlite3_vfs] object.
   2782 ** ^On all subsequent invocations, the pseudo-randomness is generated
   2783 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   2784 ** method.
   2785 */
   2786 SQLITE_API void sqlite3_randomness(int N, void *P);
   2787 
   2788 /*
   2789 ** CAPI3REF: Compile-Time Authorization Callbacks
   2790 **
   2791 ** ^This routine registers an authorizer callback with a particular
   2792 ** [database connection], supplied in the first argument.
   2793 ** ^The authorizer callback is invoked as SQL statements are being compiled
   2794 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   2795 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
   2796 ** points during the compilation process, as logic is being created
   2797 ** to perform various actions, the authorizer callback is invoked to
   2798 ** see if those actions are allowed.  ^The authorizer callback should
   2799 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   2800 ** specific action but allow the SQL statement to continue to be
   2801 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   2802 ** rejected with an error.  ^If the authorizer callback returns
   2803 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   2804 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   2805 ** the authorizer will fail with an error message.
   2806 **
   2807 ** When the callback returns [SQLITE_OK], that means the operation
   2808 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   2809 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   2810 ** authorizer will fail with an error message explaining that
   2811 ** access is denied.
   2812 **
   2813 ** ^The first parameter to the authorizer callback is a copy of the third
   2814 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   2815 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   2816 ** the particular action to be authorized. ^The third through sixth parameters
   2817 ** to the callback are zero-terminated strings that contain additional
   2818 ** details about the action to be authorized.
   2819 **
   2820 ** ^If the action code is [SQLITE_READ]
   2821 ** and the callback returns [SQLITE_IGNORE] then the
   2822 ** [prepared statement] statement is constructed to substitute
   2823 ** a NULL value in place of the table column that would have
   2824 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   2825 ** return can be used to deny an untrusted user access to individual
   2826 ** columns of a table.
   2827 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   2828 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   2829 ** [truncate optimization] is disabled and all rows are deleted individually.
   2830 **
   2831 ** An authorizer is used when [sqlite3_prepare | preparing]
   2832 ** SQL statements from an untrusted source, to ensure that the SQL statements
   2833 ** do not try to access data they are not allowed to see, or that they do not
   2834 ** try to execute malicious statements that damage the database.  For
   2835 ** example, an application may allow a user to enter arbitrary
   2836 ** SQL queries for evaluation by a database.  But the application does
   2837 ** not want the user to be able to make arbitrary changes to the
   2838 ** database.  An authorizer could then be put in place while the
   2839 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   2840 ** disallows everything except [SELECT] statements.
   2841 **
   2842 ** Applications that need to process SQL from untrusted sources
   2843 ** might also consider lowering resource limits using [sqlite3_limit()]
   2844 ** and limiting database size using the [max_page_count] [PRAGMA]
   2845 ** in addition to using an authorizer.
   2846 **
   2847 ** ^(Only a single authorizer can be in place on a database connection
   2848 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   2849 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   2850 ** The authorizer is disabled by default.
   2851 **
   2852 ** The authorizer callback must not do anything that will modify
   2853 ** the database connection that invoked the authorizer callback.
   2854 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2855 ** database connections for the meaning of "modify" in this paragraph.
   2856 **
   2857 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   2858 ** statement might be re-prepared during [sqlite3_step()] due to a
   2859 ** schema change.  Hence, the application should ensure that the
   2860 ** correct authorizer callback remains in place during the [sqlite3_step()].
   2861 **
   2862 ** ^Note that the authorizer callback is invoked only during
   2863 ** [sqlite3_prepare()] or its variants.  Authorization is not
   2864 ** performed during statement evaluation in [sqlite3_step()], unless
   2865 ** as stated in the previous paragraph, sqlite3_step() invokes
   2866 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   2867 */
   2868 SQLITE_API int sqlite3_set_authorizer(
   2869   sqlite3*,
   2870   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   2871   void *pUserData
   2872 );
   2873 
   2874 /*
   2875 ** CAPI3REF: Authorizer Return Codes
   2876 **
   2877 ** The [sqlite3_set_authorizer | authorizer callback function] must
   2878 ** return either [SQLITE_OK] or one of these two constants in order
   2879 ** to signal SQLite whether or not the action is permitted.  See the
   2880 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   2881 ** information.
   2882 **
   2883 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
   2884 ** from the [sqlite3_vtab_on_conflict()] interface.
   2885 */
   2886 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   2887 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   2888 
   2889 /*
   2890 ** CAPI3REF: Authorizer Action Codes
   2891 **
   2892 ** The [sqlite3_set_authorizer()] interface registers a callback function
   2893 ** that is invoked to authorize certain SQL statement actions.  The
   2894 ** second parameter to the callback is an integer code that specifies
   2895 ** what action is being authorized.  These are the integer action codes that
   2896 ** the authorizer callback may be passed.
   2897 **
   2898 ** These action code values signify what kind of operation is to be
   2899 ** authorized.  The 3rd and 4th parameters to the authorization
   2900 ** callback function will be parameters or NULL depending on which of these
   2901 ** codes is used as the second parameter.  ^(The 5th parameter to the
   2902 ** authorizer callback is the name of the database ("main", "temp",
   2903 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   2904 ** is the name of the inner-most trigger or view that is responsible for
   2905 ** the access attempt or NULL if this access attempt is directly from
   2906 ** top-level SQL code.
   2907 */
   2908 /******************************************* 3rd ************ 4th ***********/
   2909 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   2910 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   2911 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   2912 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   2913 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   2914 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   2915 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   2916 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   2917 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   2918 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   2919 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   2920 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   2921 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   2922 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   2923 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   2924 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   2925 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   2926 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   2927 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   2928 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   2929 #define SQLITE_SELECT               21   /* NULL            NULL            */
   2930 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   2931 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   2932 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   2933 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   2934 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   2935 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   2936 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   2937 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   2938 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   2939 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   2940 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   2941 #define SQLITE_COPY                  0   /* No longer used */
   2942 
   2943 /*
   2944 ** CAPI3REF: Tracing And Profiling Functions
   2945 **
   2946 ** These routines register callback functions that can be used for
   2947 ** tracing and profiling the execution of SQL statements.
   2948 **
   2949 ** ^The callback function registered by sqlite3_trace() is invoked at
   2950 ** various times when an SQL statement is being run by [sqlite3_step()].
   2951 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   2952 ** SQL statement text as the statement first begins executing.
   2953 ** ^(Additional sqlite3_trace() callbacks might occur
   2954 ** as each triggered subprogram is entered.  The callbacks for triggers
   2955 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   2956 **
   2957 ** ^The callback function registered by sqlite3_profile() is invoked
   2958 ** as each SQL statement finishes.  ^The profile callback contains
   2959 ** the original statement text and an estimate of wall-clock time
   2960 ** of how long that statement took to run.  ^The profile callback
   2961 ** time is in units of nanoseconds, however the current implementation
   2962 ** is only capable of millisecond resolution so the six least significant
   2963 ** digits in the time are meaningless.  Future versions of SQLite
   2964 ** might provide greater resolution on the profiler callback.  The
   2965 ** sqlite3_profile() function is considered experimental and is
   2966 ** subject to change in future versions of SQLite.
   2967 */
   2968 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
   2969 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   2970    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   2971 
   2972 /*
   2973 ** CAPI3REF: Query Progress Callbacks
   2974 **
   2975 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
   2976 ** function X to be invoked periodically during long running calls to
   2977 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
   2978 ** database connection D.  An example use for this
   2979 ** interface is to keep a GUI updated during a large query.
   2980 **
   2981 ** ^The parameter P is passed through as the only parameter to the
   2982 ** callback function X.  ^The parameter N is the number of
   2983 ** [virtual machine instructions] that are evaluated between successive
   2984 ** invocations of the callback X.
   2985 **
   2986 ** ^Only a single progress handler may be defined at one time per
   2987 ** [database connection]; setting a new progress handler cancels the
   2988 ** old one.  ^Setting parameter X to NULL disables the progress handler.
   2989 ** ^The progress handler is also disabled by setting N to a value less
   2990 ** than 1.
   2991 **
   2992 ** ^If the progress callback returns non-zero, the operation is
   2993 ** interrupted.  This feature can be used to implement a
   2994 ** "Cancel" button on a GUI progress dialog box.
   2995 **
   2996 ** The progress handler callback must not do anything that will modify
   2997 ** the database connection that invoked the progress handler.
   2998 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2999 ** database connections for the meaning of "modify" in this paragraph.
   3000 **
   3001 */
   3002 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   3003 
   3004 /*
   3005 ** CAPI3REF: Opening A New Database Connection
   3006 **
   3007 ** ^These routines open an SQLite database file as specified by the
   3008 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   3009 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   3010 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   3011 ** returned in *ppDb, even if an error occurs.  The only exception is that
   3012 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   3013 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   3014 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   3015 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   3016 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   3017 ** an English language description of the error following a failure of any
   3018 ** of the sqlite3_open() routines.
   3019 **
   3020 ** ^The default encoding for the database will be UTF-8 if
   3021 ** sqlite3_open() or sqlite3_open_v2() is called and
   3022 ** UTF-16 in the native byte order if sqlite3_open16() is used.
   3023 **
   3024 ** Whether or not an error occurs when it is opened, resources
   3025 ** associated with the [database connection] handle should be released by
   3026 ** passing it to [sqlite3_close()] when it is no longer required.
   3027 **
   3028 ** The sqlite3_open_v2() interface works like sqlite3_open()
   3029 ** except that it accepts two additional parameters for additional control
   3030 ** over the new database connection.  ^(The flags parameter to
   3031 ** sqlite3_open_v2() can take one of
   3032 ** the following three values, optionally combined with the
   3033 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   3034 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
   3035 **
   3036 ** <dl>
   3037 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   3038 ** <dd>The database is opened in read-only mode.  If the database does not
   3039 ** already exist, an error is returned.</dd>)^
   3040 **
   3041 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   3042 ** <dd>The database is opened for reading and writing if possible, or reading
   3043 ** only if the file is write protected by the operating system.  In either
   3044 ** case the database must already exist, otherwise an error is returned.</dd>)^
   3045 **
   3046 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   3047 ** <dd>The database is opened for reading and writing, and is created if
   3048 ** it does not already exist. This is the behavior that is always used for
   3049 ** sqlite3_open() and sqlite3_open16().</dd>)^
   3050 ** </dl>
   3051 **
   3052 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   3053 ** combinations shown above optionally combined with other
   3054 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
   3055 ** then the behavior is undefined.
   3056 **
   3057 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   3058 ** opens in the multi-thread [threading mode] as long as the single-thread
   3059 ** mode has not been set at compile-time or start-time.  ^If the
   3060 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   3061 ** in the serialized [threading mode] unless single-thread was
   3062 ** previously selected at compile-time or start-time.
   3063 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   3064 ** eligible to use [shared cache mode], regardless of whether or not shared
   3065 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   3066 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   3067 ** participate in [shared cache mode] even if it is enabled.
   3068 **
   3069 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   3070 ** [sqlite3_vfs] object that defines the operating system interface that
   3071 ** the new database connection should use.  ^If the fourth parameter is
   3072 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   3073 **
   3074 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   3075 ** is created for the connection.  ^This in-memory database will vanish when
   3076 ** the database connection is closed.  Future versions of SQLite might
   3077 ** make use of additional special filenames that begin with the ":" character.
   3078 ** It is recommended that when a database filename actually does begin with
   3079 ** a ":" character you should prefix the filename with a pathname such as
   3080 ** "./" to avoid ambiguity.
   3081 **
   3082 ** ^If the filename is an empty string, then a private, temporary
   3083 ** on-disk database will be created.  ^This private database will be
   3084 ** automatically deleted as soon as the database connection is closed.
   3085 **
   3086 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
   3087 **
   3088 ** ^If [URI filename] interpretation is enabled, and the filename argument
   3089 ** begins with "file:", then the filename is interpreted as a URI. ^URI
   3090 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
   3091 ** set in the fourth argument to sqlite3_open_v2(), or if it has
   3092 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
   3093 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
   3094 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
   3095 ** by default, but future releases of SQLite might enable URI filename
   3096 ** interpretation by default.  See "[URI filenames]" for additional
   3097 ** information.
   3098 **
   3099 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
   3100 ** authority, then it must be either an empty string or the string
   3101 ** "localhost". ^If the authority is not an empty string or "localhost", an
   3102 ** error is returned to the caller. ^The fragment component of a URI, if
   3103 ** present, is ignored.
   3104 **
   3105 ** ^SQLite uses the path component of the URI as the name of the disk file
   3106 ** which contains the database. ^If the path begins with a '/' character,
   3107 ** then it is interpreted as an absolute path. ^If the path does not begin
   3108 ** with a '/' (meaning that the authority section is omitted from the URI)
   3109 ** then the path is interpreted as a relative path.
   3110 ** ^On windows, the first component of an absolute path
   3111 ** is a drive specification (e.g. "C:").
   3112 **
   3113 ** [[core URI query parameters]]
   3114 ** The query component of a URI may contain parameters that are interpreted
   3115 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
   3116 ** SQLite interprets the following three query parameters:
   3117 **
   3118 ** <ul>
   3119 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
   3120 **     a VFS object that provides the operating system interface that should
   3121 **     be used to access the database file on disk. ^If this option is set to
   3122 **     an empty string the default VFS object is used. ^Specifying an unknown
   3123 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
   3124 **     present, then the VFS specified by the option takes precedence over
   3125 **     the value passed as the fourth parameter to sqlite3_open_v2().
   3126 **
   3127 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
   3128 **     "rwc". Attempting to set it to any other value is an error)^.
   3129 **     ^If "ro" is specified, then the database is opened for read-only
   3130 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
   3131 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to
   3132 **     "rw", then the database is opened for read-write (but not create)
   3133 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
   3134 **     been set. ^Value "rwc" is equivalent to setting both
   3135 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
   3136 **     used, it is an error to specify a value for the mode parameter that is
   3137 **     less restrictive than that specified by the flags passed as the third
   3138 **     parameter.
   3139 **
   3140 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
   3141 **     "private". ^Setting it to "shared" is equivalent to setting the
   3142 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
   3143 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
   3144 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
   3145 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
   3146 **     a URI filename, its value overrides any behaviour requested by setting
   3147 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
   3148 ** </ul>
   3149 **
   3150 ** ^Specifying an unknown parameter in the query component of a URI is not an
   3151 ** error.  Future versions of SQLite might understand additional query
   3152 ** parameters.  See "[query parameters with special meaning to SQLite]" for
   3153 ** additional information.
   3154 **
   3155 ** [[URI filename examples]] <h3>URI filename examples</h3>
   3156 **
   3157 ** <table border="1" align=center cellpadding=5>
   3158 ** <tr><th> URI filenames <th> Results
   3159 ** <tr><td> file:data.db <td>
   3160 **          Open the file "data.db" in the current directory.
   3161 ** <tr><td> file:/home/fred/data.db<br>
   3162 **          file:///home/fred/data.db <br>
   3163 **          file://localhost/home/fred/data.db <br> <td>
   3164 **          Open the database file "/home/fred/data.db".
   3165 ** <tr><td> file://darkstar/home/fred/data.db <td>
   3166 **          An error. "darkstar" is not a recognized authority.
   3167 ** <tr><td style="white-space:nowrap">
   3168 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
   3169 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
   3170 **          C:. Note that the %20 escaping in this example is not strictly
   3171 **          necessary - space characters can be used literally
   3172 **          in URI filenames.
   3173 ** <tr><td> file:data.db?mode=ro&cache=private <td>
   3174 **          Open file "data.db" in the current directory for read-only access.
   3175 **          Regardless of whether or not shared-cache mode is enabled by
   3176 **          default, use a private cache.
   3177 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
   3178 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
   3179 ** <tr><td> file:data.db?mode=readonly <td>
   3180 **          An error. "readonly" is not a valid option for the "mode" parameter.
   3181 ** </table>
   3182 **
   3183 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
   3184 ** query components of a URI. A hexadecimal escape sequence consists of a
   3185 ** percent sign - "%" - followed by exactly two hexadecimal digits
   3186 ** specifying an octet value. ^Before the path or query components of a
   3187 ** URI filename are interpreted, they are encoded using UTF-8 and all
   3188 ** hexadecimal escape sequences replaced by a single byte containing the
   3189 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
   3190 ** the results are undefined.
   3191 **
   3192 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   3193 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   3194 ** codepage is currently defined.  Filenames containing international
   3195 ** characters must be converted to UTF-8 prior to passing them into
   3196 ** sqlite3_open() or sqlite3_open_v2().
   3197 */
   3198 SQLITE_API int sqlite3_open(
   3199   const char *filename,   /* Database filename (UTF-8) */
   3200   sqlite3 **ppDb          /* OUT: SQLite db handle */
   3201 );
   3202 SQLITE_API int sqlite3_open16(
   3203   const void *filename,   /* Database filename (UTF-16) */
   3204   sqlite3 **ppDb          /* OUT: SQLite db handle */
   3205 );
   3206 SQLITE_API int sqlite3_open_v2(
   3207   const char *filename,   /* Database filename (UTF-8) */
   3208   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   3209   int flags,              /* Flags */
   3210   const char *zVfs        /* Name of VFS module to use */
   3211 );
   3212 
   3213 /*
   3214 ** CAPI3REF: Obtain Values For URI Parameters
   3215 **
   3216 ** These are utility routines, useful to VFS implementations, that check
   3217 ** to see if a database file was a URI that contained a specific query
   3218 ** parameter, and if so obtains the value of that query parameter.
   3219 **
   3220 ** If F is the database filename pointer passed into the xOpen() method of
   3221 ** a VFS implementation when the flags parameter to xOpen() has one or
   3222 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
   3223 ** P is the name of the query parameter, then
   3224 ** sqlite3_uri_parameter(F,P) returns the value of the P
   3225 ** parameter if it exists or a NULL pointer if P does not appear as a
   3226 ** query parameter on F.  If P is a query parameter of F
   3227 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
   3228 ** a pointer to an empty string.
   3229 **
   3230 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
   3231 ** parameter and returns true (1) or false (0) according to the value
   3232 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
   3233 ** value of query parameter P is one of "yes", "true", or "on" in any
   3234 ** case or if the value begins with a non-zero number.  The
   3235 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
   3236 ** query parameter P is one of "no", "false", or "off" in any case or
   3237 ** if the value begins with a numeric zero.  If P is not a query
   3238 ** parameter on F or if the value of P is does not match any of the
   3239 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
   3240 **
   3241 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
   3242 ** 64-bit signed integer and returns that integer, or D if P does not
   3243 ** exist.  If the value of P is something other than an integer, then
   3244 ** zero is returned.
   3245 **
   3246 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
   3247 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
   3248 ** is not a database file pathname pointer that SQLite passed into the xOpen
   3249 ** VFS method, then the behavior of this routine is undefined and probably
   3250 ** undesirable.
   3251 */
   3252 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
   3253 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
   3254 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
   3255 
   3256 
   3257 /*
   3258 ** CAPI3REF: Error Codes And Messages
   3259 **
   3260 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
   3261 ** [extended result code] for the most recent failed sqlite3_* API call
   3262 ** associated with a [database connection]. If a prior API call failed
   3263 ** but the most recent API call succeeded, the return value from
   3264 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
   3265 ** interface is the same except that it always returns the
   3266 ** [extended result code] even when extended result codes are
   3267 ** disabled.
   3268 **
   3269 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   3270 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   3271 ** ^(Memory to hold the error message string is managed internally.
   3272 ** The application does not need to worry about freeing the result.
   3273 ** However, the error string might be overwritten or deallocated by
   3274 ** subsequent calls to other SQLite interface functions.)^
   3275 **
   3276 ** When the serialized [threading mode] is in use, it might be the
   3277 ** case that a second error occurs on a separate thread in between
   3278 ** the time of the first error and the call to these interfaces.
   3279 ** When that happens, the second error will be reported since these
   3280 ** interfaces always report the most recent result.  To avoid
   3281 ** this, each thread can obtain exclusive use of the [database connection] D
   3282 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   3283 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   3284 ** all calls to the interfaces listed here are completed.
   3285 **
   3286 ** If an interface fails with SQLITE_MISUSE, that means the interface
   3287 ** was invoked incorrectly by the application.  In that case, the
   3288 ** error code and message may or may not be set.
   3289 */
   3290 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   3291 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   3292 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   3293 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   3294 
   3295 /*
   3296 ** CAPI3REF: SQL Statement Object
   3297 ** KEYWORDS: {prepared statement} {prepared statements}
   3298 **
   3299 ** An instance of this object represents a single SQL statement.
   3300 ** This object is variously known as a "prepared statement" or a
   3301 ** "compiled SQL statement" or simply as a "statement".
   3302 **
   3303 ** The life of a statement object goes something like this:
   3304 **
   3305 ** <ol>
   3306 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
   3307 **      function.
   3308 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
   3309 **      interfaces.
   3310 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   3311 ** <li> Reset the statement using [sqlite3_reset()] then go back
   3312 **      to step 2.  Do this zero or more times.
   3313 ** <li> Destroy the object using [sqlite3_finalize()].
   3314 ** </ol>
   3315 **
   3316 ** Refer to documentation on individual methods above for additional
   3317 ** information.
   3318 */
   3319 typedef struct sqlite3_stmt sqlite3_stmt;
   3320 
   3321 /*
   3322 ** CAPI3REF: Run-time Limits
   3323 **
   3324 ** ^(This interface allows the size of various constructs to be limited
   3325 ** on a connection by connection basis.  The first parameter is the
   3326 ** [database connection] whose limit is to be set or queried.  The
   3327 ** second parameter is one of the [limit categories] that define a
   3328 ** class of constructs to be size limited.  The third parameter is the
   3329 ** new limit for that construct.)^
   3330 **
   3331 ** ^If the new limit is a negative number, the limit is unchanged.
   3332 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
   3333 ** [limits | hard upper bound]
   3334 ** set at compile-time by a C preprocessor macro called
   3335 ** [limits | SQLITE_MAX_<i>NAME</i>].
   3336 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   3337 ** ^Attempts to increase a limit above its hard upper bound are
   3338 ** silently truncated to the hard upper bound.
   3339 **
   3340 ** ^Regardless of whether or not the limit was changed, the
   3341 ** [sqlite3_limit()] interface returns the prior value of the limit.
   3342 ** ^Hence, to find the current value of a limit without changing it,
   3343 ** simply invoke this interface with the third parameter set to -1.
   3344 **
   3345 ** Run-time limits are intended for use in applications that manage
   3346 ** both their own internal database and also databases that are controlled
   3347 ** by untrusted external sources.  An example application might be a
   3348 ** web browser that has its own databases for storing history and
   3349 ** separate databases controlled by JavaScript applications downloaded
   3350 ** off the Internet.  The internal databases can be given the
   3351 ** large, default limits.  Databases managed by external sources can
   3352 ** be given much smaller limits designed to prevent a denial of service
   3353 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   3354 ** interface to further control untrusted SQL.  The size of the database
   3355 ** created by an untrusted script can be contained using the
   3356 ** [max_page_count] [PRAGMA].
   3357 **
   3358 ** New run-time limit categories may be added in future releases.
   3359 */
   3360 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   3361 
   3362 /*
   3363 ** CAPI3REF: Run-Time Limit Categories
   3364 ** KEYWORDS: {limit category} {*limit categories}
   3365 **
   3366 ** These constants define various performance limits
   3367 ** that can be lowered at run-time using [sqlite3_limit()].
   3368 ** The synopsis of the meanings of the various limits is shown below.
   3369 ** Additional information is available at [limits | Limits in SQLite].
   3370 **
   3371 ** <dl>
   3372 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   3373 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
   3374 **
   3375 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   3376 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   3377 **
   3378 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   3379 ** <dd>The maximum number of columns in a table definition or in the
   3380 ** result set of a [SELECT] or the maximum number of columns in an index
   3381 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   3382 **
   3383 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   3384 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   3385 **
   3386 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   3387 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   3388 **
   3389 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   3390 ** <dd>The maximum number of instructions in a virtual machine program
   3391 ** used to implement an SQL statement.  This limit is not currently
   3392 ** enforced, though that might be added in some future release of
   3393 ** SQLite.</dd>)^
   3394 **
   3395 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   3396 ** <dd>The maximum number of arguments on a function.</dd>)^
   3397 **
   3398 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   3399 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   3400 **
   3401 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
   3402 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   3403 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   3404 ** [GLOB] operators.</dd>)^
   3405 **
   3406 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
   3407 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   3408 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
   3409 **
   3410 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   3411 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   3412 ** </dl>
   3413 */
   3414 #define SQLITE_LIMIT_LENGTH                    0
   3415 #define SQLITE_LIMIT_SQL_LENGTH                1
   3416 #define SQLITE_LIMIT_COLUMN                    2
   3417 #define SQLITE_LIMIT_EXPR_DEPTH                3
   3418 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   3419 #define SQLITE_LIMIT_VDBE_OP                   5
   3420 #define SQLITE_LIMIT_FUNCTION_ARG              6
   3421 #define SQLITE_LIMIT_ATTACHED                  7
   3422 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   3423 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   3424 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   3425 
   3426 /*
   3427 ** CAPI3REF: Compiling An SQL Statement
   3428 ** KEYWORDS: {SQL statement compiler}
   3429 **
   3430 ** To execute an SQL query, it must first be compiled into a byte-code
   3431 ** program using one of these routines.
   3432 **
   3433 ** The first argument, "db", is a [database connection] obtained from a
   3434 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   3435 ** [sqlite3_open16()].  The database connection must not have been closed.
   3436 **
   3437 ** The second argument, "zSql", is the statement to be compiled, encoded
   3438 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
   3439 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
   3440 ** use UTF-16.
   3441 **
   3442 ** ^If the nByte argument is less than zero, then zSql is read up to the
   3443 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
   3444 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
   3445 ** zSql string ends at either the first '\000' or '\u0000' character or
   3446 ** the nByte-th byte, whichever comes first. If the caller knows
   3447 ** that the supplied string is nul-terminated, then there is a small
   3448 ** performance advantage to be gained by passing an nByte parameter that
   3449 ** is equal to the number of bytes in the input string <i>including</i>
   3450 ** the nul-terminator bytes as this saves SQLite from having to
   3451 ** make a copy of the input string.
   3452 **
   3453 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   3454 ** past the end of the first SQL statement in zSql.  These routines only
   3455 ** compile the first statement in zSql, so *pzTail is left pointing to
   3456 ** what remains uncompiled.
   3457 **
   3458 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   3459 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   3460 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   3461 ** string or a comment) then *ppStmt is set to NULL.
   3462 ** The calling procedure is responsible for deleting the compiled
   3463 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   3464 ** ppStmt may not be NULL.
   3465 **
   3466 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   3467 ** otherwise an [error code] is returned.
   3468 **
   3469 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
   3470 ** recommended for all new programs. The two older interfaces are retained
   3471 ** for backwards compatibility, but their use is discouraged.
   3472 ** ^In the "v2" interfaces, the prepared statement
   3473 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   3474 ** original SQL text. This causes the [sqlite3_step()] interface to
   3475 ** behave differently in three ways:
   3476 **
   3477 ** <ol>
   3478 ** <li>
   3479 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   3480 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   3481 ** statement and try to run it again.
   3482 ** </li>
   3483 **
   3484 ** <li>
   3485 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   3486 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   3487 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   3488 ** and the application would have to make a second call to [sqlite3_reset()]
   3489 ** in order to find the underlying cause of the problem. With the "v2" prepare
   3490 ** interfaces, the underlying reason for the error is returned immediately.
   3491 ** </li>
   3492 **
   3493 ** <li>
   3494 ** ^If the specific value bound to [parameter | host parameter] in the
   3495 ** WHERE clause might influence the choice of query plan for a statement,
   3496 ** then the statement will be automatically recompiled, as if there had been
   3497 ** a schema change, on the first  [sqlite3_step()] call following any change
   3498 ** to the [sqlite3_bind_text | bindings] of that [parameter].
   3499 ** ^The specific value of WHERE-clause [parameter] might influence the
   3500 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
   3501 ** or [GLOB] operator or if the parameter is compared to an indexed column
   3502 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
   3503 ** the
   3504 ** </li>
   3505 ** </ol>
   3506 */
   3507 SQLITE_API int sqlite3_prepare(
   3508   sqlite3 *db,            /* Database handle */
   3509   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3510   int nByte,              /* Maximum length of zSql in bytes. */
   3511   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3512   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3513 );
   3514 SQLITE_API int sqlite3_prepare_v2(
   3515   sqlite3 *db,            /* Database handle */
   3516   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3517   int nByte,              /* Maximum length of zSql in bytes. */
   3518   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3519   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3520 );
   3521 SQLITE_API int sqlite3_prepare16(
   3522   sqlite3 *db,            /* Database handle */
   3523   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3524   int nByte,              /* Maximum length of zSql in bytes. */
   3525   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3526   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3527 );
   3528 SQLITE_API int sqlite3_prepare16_v2(
   3529   sqlite3 *db,            /* Database handle */
   3530   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3531   int nByte,              /* Maximum length of zSql in bytes. */
   3532   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3533   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3534 );
   3535 
   3536 /*
   3537 ** CAPI3REF: Retrieving Statement SQL
   3538 **
   3539 ** ^This interface can be used to retrieve a saved copy of the original
   3540 ** SQL text used to create a [prepared statement] if that statement was
   3541 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
   3542 */
   3543 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   3544 
   3545 /*
   3546 ** CAPI3REF: Determine If An SQL Statement Writes The Database
   3547 **
   3548 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
   3549 ** and only if the [prepared statement] X makes no direct changes to
   3550 ** the content of the database file.
   3551 **
   3552 ** Note that [application-defined SQL functions] or
   3553 ** [virtual tables] might change the database indirectly as a side effect.
   3554 ** ^(For example, if an application defines a function "eval()" that
   3555 ** calls [sqlite3_exec()], then the following SQL statement would
   3556 ** change the database file through side-effects:
   3557 **
   3558 ** <blockquote><pre>
   3559 **    SELECT eval('DELETE FROM t1') FROM t2;
   3560 ** </pre></blockquote>
   3561 **
   3562 ** But because the [SELECT] statement does not change the database file
   3563 ** directly, sqlite3_stmt_readonly() would still return true.)^
   3564 **
   3565 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
   3566 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
   3567 ** since the statements themselves do not actually modify the database but
   3568 ** rather they control the timing of when other statements modify the
   3569 ** database.  ^The [ATTACH] and [DETACH] statements also cause
   3570 ** sqlite3_stmt_readonly() to return true since, while those statements
   3571 ** change the configuration of a database connection, they do not make
   3572 ** changes to the content of the database files on disk.
   3573 */
   3574 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
   3575 
   3576 /*
   3577 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
   3578 **
   3579 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
   3580 ** [prepared statement] S has been stepped at least once using
   3581 ** [sqlite3_step(S)] but has not run to completion and/or has not
   3582 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
   3583 ** interface returns false if S is a NULL pointer.  If S is not a
   3584 ** NULL pointer and is not a pointer to a valid [prepared statement]
   3585 ** object, then the behavior is undefined and probably undesirable.
   3586 **
   3587 ** This interface can be used in combination [sqlite3_next_stmt()]
   3588 ** to locate all prepared statements associated with a database
   3589 ** connection that are in need of being reset.  This can be used,
   3590 ** for example, in diagnostic routines to search for prepared
   3591 ** statements that are holding a transaction open.
   3592 */
   3593 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
   3594 
   3595 /*
   3596 ** CAPI3REF: Dynamically Typed Value Object
   3597 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   3598 **
   3599 ** SQLite uses the sqlite3_value object to represent all values
   3600 ** that can be stored in a database table. SQLite uses dynamic typing
   3601 ** for the values it stores.  ^Values stored in sqlite3_value objects
   3602 ** can be integers, floating point values, strings, BLOBs, or NULL.
   3603 **
   3604 ** An sqlite3_value object may be either "protected" or "unprotected".
   3605 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   3606 ** will accept either a protected or an unprotected sqlite3_value.
   3607 ** Every interface that accepts sqlite3_value arguments specifies
   3608 ** whether or not it requires a protected sqlite3_value.
   3609 **
   3610 ** The terms "protected" and "unprotected" refer to whether or not
   3611 ** a mutex is held.  An internal mutex is held for a protected
   3612 ** sqlite3_value object but no mutex is held for an unprotected
   3613 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   3614 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   3615 ** or if SQLite is run in one of reduced mutex modes
   3616 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   3617 ** then there is no distinction between protected and unprotected
   3618 ** sqlite3_value objects and they can be used interchangeably.  However,
   3619 ** for maximum code portability it is recommended that applications
   3620 ** still make the distinction between protected and unprotected
   3621 ** sqlite3_value objects even when not strictly required.
   3622 **
   3623 ** ^The sqlite3_value objects that are passed as parameters into the
   3624 ** implementation of [application-defined SQL functions] are protected.
   3625 ** ^The sqlite3_value object returned by
   3626 ** [sqlite3_column_value()] is unprotected.
   3627 ** Unprotected sqlite3_value objects may only be used with
   3628 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
   3629 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   3630 ** interfaces require protected sqlite3_value objects.
   3631 */
   3632 typedef struct Mem sqlite3_value;
   3633 
   3634 /*
   3635 ** CAPI3REF: SQL Function Context Object
   3636 **
   3637 ** The context in which an SQL function executes is stored in an
   3638 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   3639 ** is always first parameter to [application-defined SQL functions].
   3640 ** The application-defined SQL function implementation will pass this
   3641 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   3642 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   3643 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   3644 ** and/or [sqlite3_set_auxdata()].
   3645 */
   3646 typedef struct sqlite3_context sqlite3_context;
   3647 
   3648 /*
   3649 ** CAPI3REF: Binding Values To Prepared Statements
   3650 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   3651 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   3652 **
   3653 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   3654 ** literals may be replaced by a [parameter] that matches one of following
   3655 ** templates:
   3656 **
   3657 ** <ul>
   3658 ** <li>  ?
   3659 ** <li>  ?NNN
   3660 ** <li>  :VVV
   3661 ** <li>  @VVV
   3662 ** <li>  $VVV
   3663 ** </ul>
   3664 **
   3665 ** In the templates above, NNN represents an integer literal,
   3666 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
   3667 ** parameters (also called "host parameter names" or "SQL parameters")
   3668 ** can be set using the sqlite3_bind_*() routines defined here.
   3669 **
   3670 ** ^The first argument to the sqlite3_bind_*() routines is always
   3671 ** a pointer to the [sqlite3_stmt] object returned from
   3672 ** [sqlite3_prepare_v2()] or its variants.
   3673 **
   3674 ** ^The second argument is the index of the SQL parameter to be set.
   3675 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   3676 ** SQL parameter is used more than once, second and subsequent
   3677 ** occurrences have the same index as the first occurrence.
   3678 ** ^The index for named parameters can be looked up using the
   3679 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   3680 ** for "?NNN" parameters is the value of NNN.
   3681 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   3682 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   3683 **
   3684 ** ^The third argument is the value to bind to the parameter.
   3685 **
   3686 ** ^(In those routines that have a fourth argument, its value is the
   3687 ** number of bytes in the parameter.  To be clear: the value is the
   3688 ** number of <u>bytes</u> in the value, not the number of characters.)^
   3689 ** ^If the fourth parameter is negative, the length of the string is
   3690 ** the number of bytes up to the first zero terminator.
   3691 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
   3692 ** or sqlite3_bind_text16() then that parameter must be the byte offset
   3693 ** where the NUL terminator would occur assuming the string were NUL
   3694 ** terminated.  If any NUL characters occur at byte offsets less than
   3695 ** the value of the fourth parameter then the resulting string value will
   3696 ** contain embedded NULs.  The result of expressions involving strings
   3697 ** with embedded NULs is undefined.
   3698 **
   3699 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
   3700 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
   3701 ** string after SQLite has finished with it.  ^The destructor is called
   3702 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
   3703 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
   3704 ** ^If the fifth argument is
   3705 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   3706 ** information is in static, unmanaged space and does not need to be freed.
   3707 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   3708 ** SQLite makes its own private copy of the data immediately, before
   3709 ** the sqlite3_bind_*() routine returns.
   3710 **
   3711 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   3712 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   3713 ** (just an integer to hold its size) while it is being processed.
   3714 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   3715 ** content is later written using
   3716 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   3717 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   3718 **
   3719 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   3720 ** for the [prepared statement] or with a prepared statement for which
   3721 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   3722 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   3723 ** routine is passed a [prepared statement] that has been finalized, the
   3724 ** result is undefined and probably harmful.
   3725 **
   3726 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   3727 ** ^Unbound parameters are interpreted as NULL.
   3728 **
   3729 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   3730 ** [error code] if anything goes wrong.
   3731 ** ^[SQLITE_RANGE] is returned if the parameter
   3732 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   3733 **
   3734 ** See also: [sqlite3_bind_parameter_count()],
   3735 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   3736 */
   3737 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   3738 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   3739 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   3740 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   3741 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   3742 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
   3743 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   3744 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   3745 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   3746 
   3747 /*
   3748 ** CAPI3REF: Number Of SQL Parameters
   3749 **
   3750 ** ^This routine can be used to find the number of [SQL parameters]
   3751 ** in a [prepared statement].  SQL parameters are tokens of the
   3752 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   3753 ** placeholders for values that are [sqlite3_bind_blob | bound]
   3754 ** to the parameters at a later time.
   3755 **
   3756 ** ^(This routine actually returns the index of the largest (rightmost)
   3757 ** parameter. For all forms except ?NNN, this will correspond to the
   3758 ** number of unique parameters.  If parameters of the ?NNN form are used,
   3759 ** there may be gaps in the list.)^
   3760 **
   3761 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3762 ** [sqlite3_bind_parameter_name()], and
   3763 ** [sqlite3_bind_parameter_index()].
   3764 */
   3765 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   3766 
   3767 /*
   3768 ** CAPI3REF: Name Of A Host Parameter
   3769 **
   3770 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   3771 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   3772 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3773 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3774 ** respectively.
   3775 ** In other words, the initial ":" or "$" or "@" or "?"
   3776 ** is included as part of the name.)^
   3777 ** ^Parameters of the form "?" without a following integer have no name
   3778 ** and are referred to as "nameless" or "anonymous parameters".
   3779 **
   3780 ** ^The first host parameter has an index of 1, not 0.
   3781 **
   3782 ** ^If the value N is out of range or if the N-th parameter is
   3783 ** nameless, then NULL is returned.  ^The returned string is
   3784 ** always in UTF-8 encoding even if the named parameter was
   3785 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
   3786 ** [sqlite3_prepare16_v2()].
   3787 **
   3788 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3789 ** [sqlite3_bind_parameter_count()], and
   3790 ** [sqlite3_bind_parameter_index()].
   3791 */
   3792 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   3793 
   3794 /*
   3795 ** CAPI3REF: Index Of A Parameter With A Given Name
   3796 **
   3797 ** ^Return the index of an SQL parameter given its name.  ^The
   3798 ** index value returned is suitable for use as the second
   3799 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   3800 ** is returned if no matching parameter is found.  ^The parameter
   3801 ** name must be given in UTF-8 even if the original statement
   3802 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
   3803 **
   3804 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3805 ** [sqlite3_bind_parameter_count()], and
   3806 ** [sqlite3_bind_parameter_index()].
   3807 */
   3808 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   3809 
   3810 /*
   3811 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   3812 **
   3813 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   3814 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   3815 ** ^Use this routine to reset all host parameters to NULL.
   3816 */
   3817 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   3818 
   3819 /*
   3820 ** CAPI3REF: Number Of Columns In A Result Set
   3821 **
   3822 ** ^Return the number of columns in the result set returned by the
   3823 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
   3824 ** statement that does not return data (for example an [UPDATE]).
   3825 **
   3826 ** See also: [sqlite3_data_count()]
   3827 */
   3828 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   3829 
   3830 /*
   3831 ** CAPI3REF: Column Names In A Result Set
   3832 **
   3833 ** ^These routines return the name assigned to a particular column
   3834 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   3835 ** interface returns a pointer to a zero-terminated UTF-8 string
   3836 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   3837 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   3838 ** that implements the [SELECT] statement. ^The second parameter is the
   3839 ** column number.  ^The leftmost column is number 0.
   3840 **
   3841 ** ^The returned string pointer is valid until either the [prepared statement]
   3842 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
   3843 ** reprepared by the first call to [sqlite3_step()] for a particular run
   3844 ** or until the next call to
   3845 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   3846 **
   3847 ** ^If sqlite3_malloc() fails during the processing of either routine
   3848 ** (for example during a conversion from UTF-8 to UTF-16) then a
   3849 ** NULL pointer is returned.
   3850 **
   3851 ** ^The name of a result column is the value of the "AS" clause for
   3852 ** that column, if there is an AS clause.  If there is no AS clause
   3853 ** then the name of the column is unspecified and may change from
   3854 ** one release of SQLite to the next.
   3855 */
   3856 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   3857 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   3858 
   3859 /*
   3860 ** CAPI3REF: Source Of Data In A Query Result
   3861 **
   3862 ** ^These routines provide a means to determine the database, table, and
   3863 ** table column that is the origin of a particular result column in
   3864 ** [SELECT] statement.
   3865 ** ^The name of the database or table or column can be returned as
   3866 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   3867 ** the database name, the _table_ routines return the table name, and
   3868 ** the origin_ routines return the column name.
   3869 ** ^The returned string is valid until the [prepared statement] is destroyed
   3870 ** using [sqlite3_finalize()] or until the statement is automatically
   3871 ** reprepared by the first call to [sqlite3_step()] for a particular run
   3872 ** or until the same information is requested
   3873 ** again in a different encoding.
   3874 **
   3875 ** ^The names returned are the original un-aliased names of the
   3876 ** database, table, and column.
   3877 **
   3878 ** ^The first argument to these interfaces is a [prepared statement].
   3879 ** ^These functions return information about the Nth result column returned by
   3880 ** the statement, where N is the second function argument.
   3881 ** ^The left-most column is column 0 for these routines.
   3882 **
   3883 ** ^If the Nth column returned by the statement is an expression or
   3884 ** subquery and is not a column value, then all of these functions return
   3885 ** NULL.  ^These routine might also return NULL if a memory allocation error
   3886 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   3887 ** or column that query result column was extracted from.
   3888 **
   3889 ** ^As with all other SQLite APIs, those whose names end with "16" return
   3890 ** UTF-16 encoded strings and the other functions return UTF-8.
   3891 **
   3892 ** ^These APIs are only available if the library was compiled with the
   3893 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   3894 **
   3895 ** If two or more threads call one or more of these routines against the same
   3896 ** prepared statement and column at the same time then the results are
   3897 ** undefined.
   3898 **
   3899 ** If two or more threads call one or more
   3900 ** [sqlite3_column_database_name | column metadata interfaces]
   3901 ** for the same [prepared statement] and result column
   3902 ** at the same time then the results are undefined.
   3903 */
   3904 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   3905 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   3906 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   3907 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   3908 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   3909 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   3910 
   3911 /*
   3912 ** CAPI3REF: Declared Datatype Of A Query Result
   3913 **
   3914 ** ^(The first parameter is a [prepared statement].
   3915 ** If this statement is a [SELECT] statement and the Nth column of the
   3916 ** returned result set of that [SELECT] is a table column (not an
   3917 ** expression or subquery) then the declared type of the table
   3918 ** column is returned.)^  ^If the Nth column of the result set is an
   3919 ** expression or subquery, then a NULL pointer is returned.
   3920 ** ^The returned string is always UTF-8 encoded.
   3921 **
   3922 ** ^(For example, given the database schema:
   3923 **
   3924 ** CREATE TABLE t1(c1 VARIANT);
   3925 **
   3926 ** and the following statement to be compiled:
   3927 **
   3928 ** SELECT c1 + 1, c1 FROM t1;
   3929 **
   3930 ** this routine would return the string "VARIANT" for the second result
   3931 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   3932 **
   3933 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   3934 ** is declared to contain a particular type does not mean that the
   3935 ** data stored in that column is of the declared type.  SQLite is
   3936 ** strongly typed, but the typing is dynamic not static.  ^Type
   3937 ** is associated with individual values, not with the containers
   3938 ** used to hold those values.
   3939 */
   3940 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   3941 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   3942 
   3943 /*
   3944 ** CAPI3REF: Evaluate An SQL Statement
   3945 **
   3946 ** After a [prepared statement] has been prepared using either
   3947 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
   3948 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   3949 ** must be called one or more times to evaluate the statement.
   3950 **
   3951 ** The details of the behavior of the sqlite3_step() interface depend
   3952 ** on whether the statement was prepared using the newer "v2" interface
   3953 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
   3954 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   3955 ** new "v2" interface is recommended for new applications but the legacy
   3956 ** interface will continue to be supported.
   3957 **
   3958 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   3959 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   3960 ** ^With the "v2" interface, any of the other [result codes] or
   3961 ** [extended result codes] might be returned as well.
   3962 **
   3963 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   3964 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   3965 ** or occurs outside of an explicit transaction, then you can retry the
   3966 ** statement.  If the statement is not a [COMMIT] and occurs within an
   3967 ** explicit transaction then you should rollback the transaction before
   3968 ** continuing.
   3969 **
   3970 ** ^[SQLITE_DONE] means that the statement has finished executing
   3971 ** successfully.  sqlite3_step() should not be called again on this virtual
   3972 ** machine without first calling [sqlite3_reset()] to reset the virtual
   3973 ** machine back to its initial state.
   3974 **
   3975 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   3976 ** is returned each time a new row of data is ready for processing by the
   3977 ** caller. The values may be accessed using the [column access functions].
   3978 ** sqlite3_step() is called again to retrieve the next row of data.
   3979 **
   3980 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   3981 ** violation) has occurred.  sqlite3_step() should not be called again on
   3982 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   3983 ** ^With the legacy interface, a more specific error code (for example,
   3984 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   3985 ** can be obtained by calling [sqlite3_reset()] on the
   3986 ** [prepared statement].  ^In the "v2" interface,
   3987 ** the more specific error code is returned directly by sqlite3_step().
   3988 **
   3989 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   3990 ** Perhaps it was called on a [prepared statement] that has
   3991 ** already been [sqlite3_finalize | finalized] or on one that had
   3992 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   3993 ** be the case that the same database connection is being used by two or
   3994 ** more threads at the same moment in time.
   3995 **
   3996 ** For all versions of SQLite up to and including 3.6.23.1, a call to
   3997 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
   3998 ** other than [SQLITE_ROW] before any subsequent invocation of
   3999 ** sqlite3_step().  Failure to reset the prepared statement using
   4000 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
   4001 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
   4002 ** calling [sqlite3_reset()] automatically in this circumstance rather
   4003 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
   4004 ** break because any application that ever receives an SQLITE_MISUSE error
   4005 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
   4006 ** can be used to restore the legacy behavior.
   4007 **
   4008 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   4009 ** API always returns a generic error code, [SQLITE_ERROR], following any
   4010 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   4011 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   4012 ** specific [error codes] that better describes the error.
   4013 ** We admit that this is a goofy design.  The problem has been fixed
   4014 ** with the "v2" interface.  If you prepare all of your SQL statements
   4015 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
   4016 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   4017 ** then the more specific [error codes] are returned directly
   4018 ** by sqlite3_step().  The use of the "v2" interface is recommended.
   4019 */
   4020 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   4021 
   4022 /*
   4023 ** CAPI3REF: Number of columns in a result set
   4024 **
   4025 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
   4026 ** current row of the result set of [prepared statement] P.
   4027 ** ^If prepared statement P does not have results ready to return
   4028 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
   4029 ** interfaces) then sqlite3_data_count(P) returns 0.
   4030 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
   4031 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
   4032 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
   4033 ** will return non-zero if previous call to [sqlite3_step](P) returned
   4034 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
   4035 ** where it always returns zero since each step of that multi-step
   4036 ** pragma returns 0 columns of data.
   4037 **
   4038 ** See also: [sqlite3_column_count()]
   4039 */
   4040 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   4041 
   4042 /*
   4043 ** CAPI3REF: Fundamental Datatypes
   4044 ** KEYWORDS: SQLITE_TEXT
   4045 **
   4046 ** ^(Every value in SQLite has one of five fundamental datatypes:
   4047 **
   4048 ** <ul>
   4049 ** <li> 64-bit signed integer
   4050 ** <li> 64-bit IEEE floating point number
   4051 ** <li> string
   4052 ** <li> BLOB
   4053 ** <li> NULL
   4054 ** </ul>)^
   4055 **
   4056 ** These constants are codes for each of those types.
   4057 **
   4058 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   4059 ** for a completely different meaning.  Software that links against both
   4060 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   4061 ** SQLITE_TEXT.
   4062 */
   4063 #define SQLITE_INTEGER  1
   4064 #define SQLITE_FLOAT    2
   4065 #define SQLITE_BLOB     4
   4066 #define SQLITE_NULL     5
   4067 #ifdef SQLITE_TEXT
   4068 # undef SQLITE_TEXT
   4069 #else
   4070 # define SQLITE_TEXT     3
   4071 #endif
   4072 #define SQLITE3_TEXT     3
   4073 
   4074 /*
   4075 ** CAPI3REF: Result Values From A Query
   4076 ** KEYWORDS: {column access functions}
   4077 **
   4078 ** These routines form the "result set" interface.
   4079 **
   4080 ** ^These routines return information about a single column of the current
   4081 ** result row of a query.  ^In every case the first argument is a pointer
   4082 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   4083 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   4084 ** and the second argument is the index of the column for which information
   4085 ** should be returned. ^The leftmost column of the result set has the index 0.
   4086 ** ^The number of columns in the result can be determined using
   4087 ** [sqlite3_column_count()].
   4088 **
   4089 ** If the SQL statement does not currently point to a valid row, or if the
   4090 ** column index is out of range, the result is undefined.
   4091 ** These routines may only be called when the most recent call to
   4092 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   4093 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   4094 ** If any of these routines are called after [sqlite3_reset()] or
   4095 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   4096 ** something other than [SQLITE_ROW], the results are undefined.
   4097 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   4098 ** are called from a different thread while any of these routines
   4099 ** are pending, then the results are undefined.
   4100 **
   4101 ** ^The sqlite3_column_type() routine returns the
   4102 ** [SQLITE_INTEGER | datatype code] for the initial data type
   4103 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   4104 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
   4105 ** returned by sqlite3_column_type() is only meaningful if no type
   4106 ** conversions have occurred as described below.  After a type conversion,
   4107 ** the value returned by sqlite3_column_type() is undefined.  Future
   4108 ** versions of SQLite may change the behavior of sqlite3_column_type()
   4109 ** following a type conversion.
   4110 **
   4111 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   4112 ** routine returns the number of bytes in that BLOB or string.
   4113 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   4114 ** the string to UTF-8 and then returns the number of bytes.
   4115 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   4116 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   4117 ** the number of bytes in that string.
   4118 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
   4119 **
   4120 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
   4121 ** routine returns the number of bytes in that BLOB or string.
   4122 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
   4123 ** the string to UTF-16 and then returns the number of bytes.
   4124 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
   4125 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
   4126 ** the number of bytes in that string.
   4127 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
   4128 **
   4129 ** ^The values returned by [sqlite3_column_bytes()] and
   4130 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
   4131 ** of the string.  ^For clarity: the values returned by
   4132 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
   4133 ** bytes in the string, not the number of characters.
   4134 **
   4135 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   4136 ** even empty strings, are always zero-terminated.  ^The return
   4137 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
   4138 **
   4139 ** ^The object returned by [sqlite3_column_value()] is an
   4140 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
   4141 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
   4142 ** If the [unprotected sqlite3_value] object returned by
   4143 ** [sqlite3_column_value()] is used in any other way, including calls
   4144 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   4145 ** or [sqlite3_value_bytes()], then the behavior is undefined.
   4146 **
   4147 ** These routines attempt to convert the value where appropriate.  ^For
   4148 ** example, if the internal representation is FLOAT and a text result
   4149 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   4150 ** conversion automatically.  ^(The following table details the conversions
   4151 ** that are applied:
   4152 **
   4153 ** <blockquote>
   4154 ** <table border="1">
   4155 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   4156 **
   4157 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   4158 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   4159 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
   4160 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
   4161 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   4162 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   4163 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   4164 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
   4165 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   4166 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
   4167 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
   4168 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
   4169 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   4170 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
   4171 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
   4172 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   4173 ** </table>
   4174 ** </blockquote>)^
   4175 **
   4176 ** The table above makes reference to standard C library functions atoi()
   4177 ** and atof().  SQLite does not really use these functions.  It has its
   4178 ** own equivalent internal routines.  The atoi() and atof() names are
   4179 ** used in the table for brevity and because they are familiar to most
   4180 ** C programmers.
   4181 **
   4182 ** Note that when type conversions occur, pointers returned by prior
   4183 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   4184 ** sqlite3_column_text16() may be invalidated.
   4185 ** Type conversions and pointer invalidations might occur
   4186 ** in the following cases:
   4187 **
   4188 ** <ul>
   4189 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   4190 **      sqlite3_column_text16() is called.  A zero-terminator might
   4191 **      need to be added to the string.</li>
   4192 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   4193 **      sqlite3_column_text16() is called.  The content must be converted
   4194 **      to UTF-16.</li>
   4195 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   4196 **      sqlite3_column_text() is called.  The content must be converted
   4197 **      to UTF-8.</li>
   4198 ** </ul>
   4199 **
   4200 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   4201 ** not invalidate a prior pointer, though of course the content of the buffer
   4202 ** that the prior pointer references will have been modified.  Other kinds
   4203 ** of conversion are done in place when it is possible, but sometimes they
   4204 ** are not possible and in those cases prior pointers are invalidated.
   4205 **
   4206 ** The safest and easiest to remember policy is to invoke these routines
   4207 ** in one of the following ways:
   4208 **
   4209 ** <ul>
   4210 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   4211 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   4212 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   4213 ** </ul>
   4214 **
   4215 ** In other words, you should call sqlite3_column_text(),
   4216 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   4217 ** into the desired format, then invoke sqlite3_column_bytes() or
   4218 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   4219 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   4220 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   4221 ** with calls to sqlite3_column_bytes().
   4222 **
   4223 ** ^The pointers returned are valid until a type conversion occurs as
   4224 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   4225 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   4226 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
   4227 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   4228 ** [sqlite3_free()].
   4229 **
   4230 ** ^(If a memory allocation error occurs during the evaluation of any
   4231 ** of these routines, a default value is returned.  The default value
   4232 ** is either the integer 0, the floating point number 0.0, or a NULL
   4233 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   4234 ** [SQLITE_NOMEM].)^
   4235 */
   4236 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   4237 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   4238 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   4239 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   4240 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   4241 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   4242 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   4243 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   4244 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   4245 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   4246 
   4247 /*
   4248 ** CAPI3REF: Destroy A Prepared Statement Object
   4249 **
   4250 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   4251 ** ^If the most recent evaluation of the statement encountered no errors
   4252 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
   4253 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
   4254 ** sqlite3_finalize(S) returns the appropriate [error code] or
   4255 ** [extended error code].
   4256 **
   4257 ** ^The sqlite3_finalize(S) routine can be called at any point during
   4258 ** the life cycle of [prepared statement] S:
   4259 ** before statement S is ever evaluated, after
   4260 ** one or more calls to [sqlite3_reset()], or after any call
   4261 ** to [sqlite3_step()] regardless of whether or not the statement has
   4262 ** completed execution.
   4263 **
   4264 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
   4265 **
   4266 ** The application must finalize every [prepared statement] in order to avoid
   4267 ** resource leaks.  It is a grievous error for the application to try to use
   4268 ** a prepared statement after it has been finalized.  Any use of a prepared
   4269 ** statement after it has been finalized can result in undefined and
   4270 ** undesirable behavior such as segfaults and heap corruption.
   4271 */
   4272 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   4273 
   4274 /*
   4275 ** CAPI3REF: Reset A Prepared Statement Object
   4276 **
   4277 ** The sqlite3_reset() function is called to reset a [prepared statement]
   4278 ** object back to its initial state, ready to be re-executed.
   4279 ** ^Any SQL statement variables that had values bound to them using
   4280 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   4281 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   4282 **
   4283 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   4284 ** back to the beginning of its program.
   4285 **
   4286 ** ^If the most recent call to [sqlite3_step(S)] for the
   4287 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   4288 ** or if [sqlite3_step(S)] has never before been called on S,
   4289 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   4290 **
   4291 ** ^If the most recent call to [sqlite3_step(S)] for the
   4292 ** [prepared statement] S indicated an error, then
   4293 ** [sqlite3_reset(S)] returns an appropriate [error code].
   4294 **
   4295 ** ^The [sqlite3_reset(S)] interface does not change the values
   4296 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   4297 */
   4298 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   4299 
   4300 /*
   4301 ** CAPI3REF: Create Or Redefine SQL Functions
   4302 ** KEYWORDS: {function creation routines}
   4303 ** KEYWORDS: {application-defined SQL function}
   4304 ** KEYWORDS: {application-defined SQL functions}
   4305 **
   4306 ** ^These functions (collectively known as "function creation routines")
   4307 ** are used to add SQL functions or aggregates or to redefine the behavior
   4308 ** of existing SQL functions or aggregates.  The only differences between
   4309 ** these routines are the text encoding expected for
   4310 ** the second parameter (the name of the function being created)
   4311 ** and the presence or absence of a destructor callback for
   4312 ** the application data pointer.
   4313 **
   4314 ** ^The first parameter is the [database connection] to which the SQL
   4315 ** function is to be added.  ^If an application uses more than one database
   4316 ** connection then application-defined SQL functions must be added
   4317 ** to each database connection separately.
   4318 **
   4319 ** ^The second parameter is the name of the SQL function to be created or
   4320 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
   4321 ** representation, exclusive of the zero-terminator.  ^Note that the name
   4322 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
   4323 ** ^Any attempt to create a function with a longer name
   4324 ** will result in [SQLITE_MISUSE] being returned.
   4325 **
   4326 ** ^The third parameter (nArg)
   4327 ** is the number of arguments that the SQL function or
   4328 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   4329 ** aggregate may take any number of arguments between 0 and the limit
   4330 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   4331 ** parameter is less than -1 or greater than 127 then the behavior is
   4332 ** undefined.
   4333 **
   4334 ** ^The fourth parameter, eTextRep, specifies what
   4335 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   4336 ** its parameters.  Every SQL function implementation must be able to work
   4337 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
   4338 ** more efficient with one encoding than another.  ^An application may
   4339 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
   4340 ** times with the same function but with different values of eTextRep.
   4341 ** ^When multiple implementations of the same function are available, SQLite
   4342 ** will pick the one that involves the least amount of data conversion.
   4343 ** If there is only a single implementation which does not care what text
   4344 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
   4345 **
   4346 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   4347 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   4348 **
   4349 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
   4350 ** pointers to C-language functions that implement the SQL function or
   4351 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   4352 ** callback only; NULL pointers must be passed as the xStep and xFinal
   4353 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   4354 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
   4355 ** SQL function or aggregate, pass NULL pointers for all three function
   4356 ** callbacks.
   4357 **
   4358 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
   4359 ** then it is destructor for the application data pointer.
   4360 ** The destructor is invoked when the function is deleted, either by being
   4361 ** overloaded or when the database connection closes.)^
   4362 ** ^The destructor is also invoked if the call to
   4363 ** sqlite3_create_function_v2() fails.
   4364 ** ^When the destructor callback of the tenth parameter is invoked, it
   4365 ** is passed a single argument which is a copy of the application data
   4366 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
   4367 **
   4368 ** ^It is permitted to register multiple implementations of the same
   4369 ** functions with the same name but with either differing numbers of
   4370 ** arguments or differing preferred text encodings.  ^SQLite will use
   4371 ** the implementation that most closely matches the way in which the
   4372 ** SQL function is used.  ^A function implementation with a non-negative
   4373 ** nArg parameter is a better match than a function implementation with
   4374 ** a negative nArg.  ^A function where the preferred text encoding
   4375 ** matches the database encoding is a better
   4376 ** match than a function where the encoding is different.
   4377 ** ^A function where the encoding difference is between UTF16le and UTF16be
   4378 ** is a closer match than a function where the encoding difference is
   4379 ** between UTF8 and UTF16.
   4380 **
   4381 ** ^Built-in functions may be overloaded by new application-defined functions.
   4382 **
   4383 ** ^An application-defined function is permitted to call other
   4384 ** SQLite interfaces.  However, such calls must not
   4385 ** close the database connection nor finalize or reset the prepared
   4386 ** statement in which the function is running.
   4387 */
   4388 SQLITE_API int sqlite3_create_function(
   4389   sqlite3 *db,
   4390   const char *zFunctionName,
   4391   int nArg,
   4392   int eTextRep,
   4393   void *pApp,
   4394   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4395   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4396   void (*xFinal)(sqlite3_context*)
   4397 );
   4398 SQLITE_API int sqlite3_create_function16(
   4399   sqlite3 *db,
   4400   const void *zFunctionName,
   4401   int nArg,
   4402   int eTextRep,
   4403   void *pApp,
   4404   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4405   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4406   void (*xFinal)(sqlite3_context*)
   4407 );
   4408 SQLITE_API int sqlite3_create_function_v2(
   4409   sqlite3 *db,
   4410   const char *zFunctionName,
   4411   int nArg,
   4412   int eTextRep,
   4413   void *pApp,
   4414   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4415   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4416   void (*xFinal)(sqlite3_context*),
   4417   void(*xDestroy)(void*)
   4418 );
   4419 
   4420 /*
   4421 ** CAPI3REF: Text Encodings
   4422 **
   4423 ** These constant define integer codes that represent the various
   4424 ** text encodings supported by SQLite.
   4425 */
   4426 #define SQLITE_UTF8           1
   4427 #define SQLITE_UTF16LE        2
   4428 #define SQLITE_UTF16BE        3
   4429 #define SQLITE_UTF16          4    /* Use native byte order */
   4430 #define SQLITE_ANY            5    /* sqlite3_create_function only */
   4431 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   4432 
   4433 /*
   4434 ** CAPI3REF: Deprecated Functions
   4435 ** DEPRECATED
   4436 **
   4437 ** These functions are [deprecated].  In order to maintain
   4438 ** backwards compatibility with older code, these functions continue
   4439 ** to be supported.  However, new applications should avoid
   4440 ** the use of these functions.  To help encourage people to avoid
   4441 ** using these functions, we are not going to tell you what they do.
   4442 */
   4443 #ifndef SQLITE_OMIT_DEPRECATED
   4444 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   4445 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   4446 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   4447 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   4448 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   4449 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
   4450 #endif
   4451 
   4452 /*
   4453 ** CAPI3REF: Obtaining SQL Function Parameter Values
   4454 **
   4455 ** The C-language implementation of SQL functions and aggregates uses
   4456 ** this set of interface routines to access the parameter values on
   4457 ** the function or aggregate.
   4458 **
   4459 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
   4460 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
   4461 ** define callbacks that implement the SQL functions and aggregates.
   4462 ** The 3rd parameter to these callbacks is an array of pointers to
   4463 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
   4464 ** each parameter to the SQL function.  These routines are used to
   4465 ** extract values from the [sqlite3_value] objects.
   4466 **
   4467 ** These routines work only with [protected sqlite3_value] objects.
   4468 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   4469 ** object results in undefined behavior.
   4470 **
   4471 ** ^These routines work just like the corresponding [column access functions]
   4472 ** except that  these routines take a single [protected sqlite3_value] object
   4473 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   4474 **
   4475 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   4476 ** in the native byte-order of the host machine.  ^The
   4477 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   4478 ** extract UTF-16 strings as big-endian and little-endian respectively.
   4479 **
   4480 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   4481 ** numeric affinity to the value.  This means that an attempt is
   4482 ** made to convert the value to an integer or floating point.  If
   4483 ** such a conversion is possible without loss of information (in other
   4484 ** words, if the value is a string that looks like a number)
   4485 ** then the conversion is performed.  Otherwise no conversion occurs.
   4486 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   4487 **
   4488 ** Please pay particular attention to the fact that the pointer returned
   4489 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   4490 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   4491 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   4492 ** or [sqlite3_value_text16()].
   4493 **
   4494 ** These routines must be called from the same thread as
   4495 ** the SQL function that supplied the [sqlite3_value*] parameters.
   4496 */
   4497 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   4498 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   4499 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   4500 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   4501 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   4502 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   4503 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   4504 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   4505 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   4506 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   4507 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   4508 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   4509 
   4510 /*
   4511 ** CAPI3REF: Obtain Aggregate Function Context
   4512 **
   4513 ** Implementations of aggregate SQL functions use this
   4514 ** routine to allocate memory for storing their state.
   4515 **
   4516 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   4517 ** for a particular aggregate function, SQLite
   4518 ** allocates N of memory, zeroes out that memory, and returns a pointer
   4519 ** to the new memory. ^On second and subsequent calls to
   4520 ** sqlite3_aggregate_context() for the same aggregate function instance,
   4521 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   4522 ** called once for each invocation of the xStep callback and then one
   4523 ** last time when the xFinal callback is invoked.  ^(When no rows match
   4524 ** an aggregate query, the xStep() callback of the aggregate function
   4525 ** implementation is never called and xFinal() is called exactly once.
   4526 ** In those cases, sqlite3_aggregate_context() might be called for the
   4527 ** first time from within xFinal().)^
   4528 **
   4529 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
   4530 ** less than or equal to zero or if a memory allocate error occurs.
   4531 **
   4532 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   4533 ** determined by the N parameter on first successful call.  Changing the
   4534 ** value of N in subsequent call to sqlite3_aggregate_context() within
   4535 ** the same aggregate function instance will not resize the memory
   4536 ** allocation.)^
   4537 **
   4538 ** ^SQLite automatically frees the memory allocated by
   4539 ** sqlite3_aggregate_context() when the aggregate query concludes.
   4540 **
   4541 ** The first parameter must be a copy of the
   4542 ** [sqlite3_context | SQL function context] that is the first parameter
   4543 ** to the xStep or xFinal callback routine that implements the aggregate
   4544 ** function.
   4545 **
   4546 ** This routine must be called from the same thread in which
   4547 ** the aggregate SQL function is running.
   4548 */
   4549 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   4550 
   4551 /*
   4552 ** CAPI3REF: User Data For Functions
   4553 **
   4554 ** ^The sqlite3_user_data() interface returns a copy of
   4555 ** the pointer that was the pUserData parameter (the 5th parameter)
   4556 ** of the [sqlite3_create_function()]
   4557 ** and [sqlite3_create_function16()] routines that originally
   4558 ** registered the application defined function.
   4559 **
   4560 ** This routine must be called from the same thread in which
   4561 ** the application-defined function is running.
   4562 */
   4563 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   4564 
   4565 /*
   4566 ** CAPI3REF: Database Connection For Functions
   4567 **
   4568 ** ^The sqlite3_context_db_handle() interface returns a copy of
   4569 ** the pointer to the [database connection] (the 1st parameter)
   4570 ** of the [sqlite3_create_function()]
   4571 ** and [sqlite3_create_function16()] routines that originally
   4572 ** registered the application defined function.
   4573 */
   4574 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   4575 
   4576 /*
   4577 ** CAPI3REF: Function Auxiliary Data
   4578 **
   4579 ** The following two functions may be used by scalar SQL functions to
   4580 ** associate metadata with argument values. If the same value is passed to
   4581 ** multiple invocations of the same SQL function during query execution, under
   4582 ** some circumstances the associated metadata may be preserved. This may
   4583 ** be used, for example, to add a regular-expression matching scalar
   4584 ** function. The compiled version of the regular expression is stored as
   4585 ** metadata associated with the SQL value passed as the regular expression
   4586 ** pattern.  The compiled regular expression can be reused on multiple
   4587 ** invocations of the same function so that the original pattern string
   4588 ** does not need to be recompiled on each invocation.
   4589 **
   4590 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
   4591 ** associated by the sqlite3_set_auxdata() function with the Nth argument
   4592 ** value to the application-defined function. ^If no metadata has been ever
   4593 ** been set for the Nth argument of the function, or if the corresponding
   4594 ** function parameter has changed since the meta-data was set,
   4595 ** then sqlite3_get_auxdata() returns a NULL pointer.
   4596 **
   4597 ** ^The sqlite3_set_auxdata() interface saves the metadata
   4598 ** pointed to by its 3rd parameter as the metadata for the N-th
   4599 ** argument of the application-defined function.  Subsequent
   4600 ** calls to sqlite3_get_auxdata() might return this data, if it has
   4601 ** not been destroyed.
   4602 ** ^If it is not NULL, SQLite will invoke the destructor
   4603 ** function given by the 4th parameter to sqlite3_set_auxdata() on
   4604 ** the metadata when the corresponding function parameter changes
   4605 ** or when the SQL statement completes, whichever comes first.
   4606 **
   4607 ** SQLite is free to call the destructor and drop metadata on any
   4608 ** parameter of any function at any time.  ^The only guarantee is that
   4609 ** the destructor will be called before the metadata is dropped.
   4610 **
   4611 ** ^(In practice, metadata is preserved between function calls for
   4612 ** expressions that are constant at compile time. This includes literal
   4613 ** values and [parameters].)^
   4614 **
   4615 ** These routines must be called from the same thread in which
   4616 ** the SQL function is running.
   4617 */
   4618 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   4619 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   4620 
   4621 
   4622 /*
   4623 ** CAPI3REF: Constants Defining Special Destructor Behavior
   4624 **
   4625 ** These are special values for the destructor that is passed in as the
   4626 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   4627 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   4628 ** and will never change.  It does not need to be destroyed.  ^The
   4629 ** SQLITE_TRANSIENT value means that the content will likely change in
   4630 ** the near future and that SQLite should make its own private copy of
   4631 ** the content before returning.
   4632 **
   4633 ** The typedef is necessary to work around problems in certain
   4634 ** C++ compilers.  See ticket #2191.
   4635 */
   4636 typedef void (*sqlite3_destructor_type)(void*);
   4637 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   4638 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   4639 
   4640 /*
   4641 ** CAPI3REF: Setting The Result Of An SQL Function
   4642 **
   4643 ** These routines are used by the xFunc or xFinal callbacks that
   4644 ** implement SQL functions and aggregates.  See
   4645 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   4646 ** for additional information.
   4647 **
   4648 ** These functions work very much like the [parameter binding] family of
   4649 ** functions used to bind values to host parameters in prepared statements.
   4650 ** Refer to the [SQL parameter] documentation for additional information.
   4651 **
   4652 ** ^The sqlite3_result_blob() interface sets the result from
   4653 ** an application-defined function to be the BLOB whose content is pointed
   4654 ** to by the second parameter and which is N bytes long where N is the
   4655 ** third parameter.
   4656 **
   4657 ** ^The sqlite3_result_zeroblob() interfaces set the result of
   4658 ** the application-defined function to be a BLOB containing all zero
   4659 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
   4660 **
   4661 ** ^The sqlite3_result_double() interface sets the result from
   4662 ** an application-defined function to be a floating point value specified
   4663 ** by its 2nd argument.
   4664 **
   4665 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   4666 ** cause the implemented SQL function to throw an exception.
   4667 ** ^SQLite uses the string pointed to by the
   4668 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   4669 ** as the text of an error message.  ^SQLite interprets the error
   4670 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   4671 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   4672 ** byte order.  ^If the third parameter to sqlite3_result_error()
   4673 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   4674 ** message all text up through the first zero character.
   4675 ** ^If the third parameter to sqlite3_result_error() or
   4676 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   4677 ** bytes (not characters) from the 2nd parameter as the error message.
   4678 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   4679 ** routines make a private copy of the error message text before
   4680 ** they return.  Hence, the calling function can deallocate or
   4681 ** modify the text after they return without harm.
   4682 ** ^The sqlite3_result_error_code() function changes the error code
   4683 ** returned by SQLite as a result of an error in a function.  ^By default,
   4684 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   4685 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   4686 **
   4687 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
   4688 ** indicating that a string or BLOB is too long to represent.
   4689 **
   4690 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
   4691 ** indicating that a memory allocation failed.
   4692 **
   4693 ** ^The sqlite3_result_int() interface sets the return value
   4694 ** of the application-defined function to be the 32-bit signed integer
   4695 ** value given in the 2nd argument.
   4696 ** ^The sqlite3_result_int64() interface sets the return value
   4697 ** of the application-defined function to be the 64-bit signed integer
   4698 ** value given in the 2nd argument.
   4699 **
   4700 ** ^The sqlite3_result_null() interface sets the return value
   4701 ** of the application-defined function to be NULL.
   4702 **
   4703 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   4704 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   4705 ** set the return value of the application-defined function to be
   4706 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   4707 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   4708 ** ^SQLite takes the text result from the application from
   4709 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   4710 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4711 ** is negative, then SQLite takes result text from the 2nd parameter
   4712 ** through the first zero character.
   4713 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4714 ** is non-negative, then as many bytes (not characters) of the text
   4715 ** pointed to by the 2nd parameter are taken as the application-defined
   4716 ** function result.  If the 3rd parameter is non-negative, then it
   4717 ** must be the byte offset into the string where the NUL terminator would
   4718 ** appear if the string where NUL terminated.  If any NUL characters occur
   4719 ** in the string at a byte offset that is less than the value of the 3rd
   4720 ** parameter, then the resulting string will contain embedded NULs and the
   4721 ** result of expressions operating on strings with embedded NULs is undefined.
   4722 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4723 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   4724 ** function as the destructor on the text or BLOB result when it has
   4725 ** finished using that result.
   4726 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   4727 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   4728 ** assumes that the text or BLOB result is in constant space and does not
   4729 ** copy the content of the parameter nor call a destructor on the content
   4730 ** when it has finished using that result.
   4731 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4732 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   4733 ** then SQLite makes a copy of the result into space obtained from
   4734 ** from [sqlite3_malloc()] before it returns.
   4735 **
   4736 ** ^The sqlite3_result_value() interface sets the result of
   4737 ** the application-defined function to be a copy the
   4738 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   4739 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   4740 ** so that the [sqlite3_value] specified in the parameter may change or
   4741 ** be deallocated after sqlite3_result_value() returns without harm.
   4742 ** ^A [protected sqlite3_value] object may always be used where an
   4743 ** [unprotected sqlite3_value] object is required, so either
   4744 ** kind of [sqlite3_value] object can be used with this interface.
   4745 **
   4746 ** If these routines are called from within the different thread
   4747 ** than the one containing the application-defined function that received
   4748 ** the [sqlite3_context] pointer, the results are undefined.
   4749 */
   4750 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   4751 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   4752 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   4753 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   4754 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   4755 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   4756 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   4757 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   4758 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   4759 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   4760 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   4761 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   4762 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   4763 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   4764 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   4765 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   4766 
   4767 /*
   4768 ** CAPI3REF: Define New Collating Sequences
   4769 **
   4770 ** ^These functions add, remove, or modify a [collation] associated
   4771 ** with the [database connection] specified as the first argument.
   4772 **
   4773 ** ^The name of the collation is a UTF-8 string
   4774 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   4775 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
   4776 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
   4777 ** considered to be the same name.
   4778 **
   4779 ** ^(The third argument (eTextRep) must be one of the constants:
   4780 ** <ul>
   4781 ** <li> [SQLITE_UTF8],
   4782 ** <li> [SQLITE_UTF16LE],
   4783 ** <li> [SQLITE_UTF16BE],
   4784 ** <li> [SQLITE_UTF16], or
   4785 ** <li> [SQLITE_UTF16_ALIGNED].
   4786 ** </ul>)^
   4787 ** ^The eTextRep argument determines the encoding of strings passed
   4788 ** to the collating function callback, xCallback.
   4789 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
   4790 ** force strings to be UTF16 with native byte order.
   4791 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
   4792 ** on an even byte address.
   4793 **
   4794 ** ^The fourth argument, pArg, is an application data pointer that is passed
   4795 ** through as the first argument to the collating function callback.
   4796 **
   4797 ** ^The fifth argument, xCallback, is a pointer to the collating function.
   4798 ** ^Multiple collating functions can be registered using the same name but
   4799 ** with different eTextRep parameters and SQLite will use whichever
   4800 ** function requires the least amount of data transformation.
   4801 ** ^If the xCallback argument is NULL then the collating function is
   4802 ** deleted.  ^When all collating functions having the same name are deleted,
   4803 ** that collation is no longer usable.
   4804 **
   4805 ** ^The collating function callback is invoked with a copy of the pArg
   4806 ** application data pointer and with two strings in the encoding specified
   4807 ** by the eTextRep argument.  The collating function must return an
   4808 ** integer that is negative, zero, or positive
   4809 ** if the first string is less than, equal to, or greater than the second,
   4810 ** respectively.  A collating function must always return the same answer
   4811 ** given the same inputs.  If two or more collating functions are registered
   4812 ** to the same collation name (using different eTextRep values) then all
   4813 ** must give an equivalent answer when invoked with equivalent strings.
   4814 ** The collating function must obey the following properties for all
   4815 ** strings A, B, and C:
   4816 **
   4817 ** <ol>
   4818 ** <li> If A==B then B==A.
   4819 ** <li> If A==B and B==C then A==C.
   4820 ** <li> If A&lt;B THEN B&gt;A.
   4821 ** <li> If A&lt;B and B&lt;C then A&lt;C.
   4822 ** </ol>
   4823 **
   4824 ** If a collating function fails any of the above constraints and that
   4825 ** collating function is  registered and used, then the behavior of SQLite
   4826 ** is undefined.
   4827 **
   4828 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   4829 ** with the addition that the xDestroy callback is invoked on pArg when
   4830 ** the collating function is deleted.
   4831 ** ^Collating functions are deleted when they are overridden by later
   4832 ** calls to the collation creation functions or when the
   4833 ** [database connection] is closed using [sqlite3_close()].
   4834 **
   4835 ** ^The xDestroy callback is <u>not</u> called if the
   4836 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
   4837 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
   4838 ** check the return code and dispose of the application data pointer
   4839 ** themselves rather than expecting SQLite to deal with it for them.
   4840 ** This is different from every other SQLite interface.  The inconsistency
   4841 ** is unfortunate but cannot be changed without breaking backwards
   4842 ** compatibility.
   4843 **
   4844 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   4845 */
   4846 SQLITE_API int sqlite3_create_collation(
   4847   sqlite3*,
   4848   const char *zName,
   4849   int eTextRep,
   4850   void *pArg,
   4851   int(*xCompare)(void*,int,const void*,int,const void*)
   4852 );
   4853 SQLITE_API int sqlite3_create_collation_v2(
   4854   sqlite3*,
   4855   const char *zName,
   4856   int eTextRep,
   4857   void *pArg,
   4858   int(*xCompare)(void*,int,const void*,int,const void*),
   4859   void(*xDestroy)(void*)
   4860 );
   4861 SQLITE_API int sqlite3_create_collation16(
   4862   sqlite3*,
   4863   const void *zName,
   4864   int eTextRep,
   4865   void *pArg,
   4866   int(*xCompare)(void*,int,const void*,int,const void*)
   4867 );
   4868 
   4869 /*
   4870 ** CAPI3REF: Collation Needed Callbacks
   4871 **
   4872 ** ^To avoid having to register all collation sequences before a database
   4873 ** can be used, a single callback function may be registered with the
   4874 ** [database connection] to be invoked whenever an undefined collation
   4875 ** sequence is required.
   4876 **
   4877 ** ^If the function is registered using the sqlite3_collation_needed() API,
   4878 ** then it is passed the names of undefined collation sequences as strings
   4879 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   4880 ** the names are passed as UTF-16 in machine native byte order.
   4881 ** ^A call to either function replaces the existing collation-needed callback.
   4882 **
   4883 ** ^(When the callback is invoked, the first argument passed is a copy
   4884 ** of the second argument to sqlite3_collation_needed() or
   4885 ** sqlite3_collation_needed16().  The second argument is the database
   4886 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   4887 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   4888 ** sequence function required.  The fourth parameter is the name of the
   4889 ** required collation sequence.)^
   4890 **
   4891 ** The callback function should register the desired collation using
   4892 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   4893 ** [sqlite3_create_collation_v2()].
   4894 */
   4895 SQLITE_API int sqlite3_collation_needed(
   4896   sqlite3*,
   4897   void*,
   4898   void(*)(void*,sqlite3*,int eTextRep,const char*)
   4899 );
   4900 SQLITE_API int sqlite3_collation_needed16(
   4901   sqlite3*,
   4902   void*,
   4903   void(*)(void*,sqlite3*,int eTextRep,const void*)
   4904 );
   4905 
   4906 #ifdef SQLITE_HAS_CODEC
   4907 /*
   4908 ** Specify the key for an encrypted database.  This routine should be
   4909 ** called right after sqlite3_open().
   4910 **
   4911 ** The code to implement this API is not available in the public release
   4912 ** of SQLite.
   4913 */
   4914 SQLITE_API int sqlite3_key(
   4915   sqlite3 *db,                   /* Database to be rekeyed */
   4916   const void *pKey, int nKey     /* The key */
   4917 );
   4918 
   4919 /*
   4920 ** Change the key on an open database.  If the current database is not
   4921 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   4922 ** database is decrypted.
   4923 **
   4924 ** The code to implement this API is not available in the public release
   4925 ** of SQLite.
   4926 */
   4927 SQLITE_API int sqlite3_rekey(
   4928   sqlite3 *db,                   /* Database to be rekeyed */
   4929   const void *pKey, int nKey     /* The new key */
   4930 );
   4931 
   4932 /*
   4933 ** Specify the activation key for a SEE database.  Unless
   4934 ** activated, none of the SEE routines will work.
   4935 */
   4936 SQLITE_API void sqlite3_activate_see(
   4937   const char *zPassPhrase        /* Activation phrase */
   4938 );
   4939 #endif
   4940 
   4941 #ifdef SQLITE_ENABLE_CEROD
   4942 /*
   4943 ** Specify the activation key for a CEROD database.  Unless
   4944 ** activated, none of the CEROD routines will work.
   4945 */
   4946 SQLITE_API void sqlite3_activate_cerod(
   4947   const char *zPassPhrase        /* Activation phrase */
   4948 );
   4949 #endif
   4950 
   4951 /*
   4952 ** CAPI3REF: Suspend Execution For A Short Time
   4953 **
   4954 ** The sqlite3_sleep() function causes the current thread to suspend execution
   4955 ** for at least a number of milliseconds specified in its parameter.
   4956 **
   4957 ** If the operating system does not support sleep requests with
   4958 ** millisecond time resolution, then the time will be rounded up to
   4959 ** the nearest second. The number of milliseconds of sleep actually
   4960 ** requested from the operating system is returned.
   4961 **
   4962 ** ^SQLite implements this interface by calling the xSleep()
   4963 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
   4964 ** of the default VFS is not implemented correctly, or not implemented at
   4965 ** all, then the behavior of sqlite3_sleep() may deviate from the description
   4966 ** in the previous paragraphs.
   4967 */
   4968 SQLITE_API int sqlite3_sleep(int);
   4969 
   4970 /*
   4971 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   4972 **
   4973 ** ^(If this global variable is made to point to a string which is
   4974 ** the name of a folder (a.k.a. directory), then all temporary files
   4975 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   4976 ** will be placed in that directory.)^  ^If this variable
   4977 ** is a NULL pointer, then SQLite performs a search for an appropriate
   4978 ** temporary file directory.
   4979 **
   4980 ** It is not safe to read or modify this variable in more than one
   4981 ** thread at a time.  It is not safe to read or modify this variable
   4982 ** if a [database connection] is being used at the same time in a separate
   4983 ** thread.
   4984 ** It is intended that this variable be set once
   4985 ** as part of process initialization and before any SQLite interface
   4986 ** routines have been called and that this variable remain unchanged
   4987 ** thereafter.
   4988 **
   4989 ** ^The [temp_store_directory pragma] may modify this variable and cause
   4990 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4991 ** the [temp_store_directory pragma] always assumes that any string
   4992 ** that this variable points to is held in memory obtained from
   4993 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4994 ** using [sqlite3_free].
   4995 ** Hence, if this variable is modified directly, either it should be
   4996 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4997 ** or else the use of the [temp_store_directory pragma] should be avoided.
   4998 */
   4999 SQLITE_API char *sqlite3_temp_directory;
   5000 
   5001 /*
   5002 ** CAPI3REF: Test For Auto-Commit Mode
   5003 ** KEYWORDS: {autocommit mode}
   5004 **
   5005 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   5006 ** zero if the given database connection is or is not in autocommit mode,
   5007 ** respectively.  ^Autocommit mode is on by default.
   5008 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   5009 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   5010 **
   5011 ** If certain kinds of errors occur on a statement within a multi-statement
   5012 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   5013 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   5014 ** transaction might be rolled back automatically.  The only way to
   5015 ** find out whether SQLite automatically rolled back the transaction after
   5016 ** an error is to use this function.
   5017 **
   5018 ** If another thread changes the autocommit status of the database
   5019 ** connection while this routine is running, then the return value
   5020 ** is undefined.
   5021 */
   5022 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   5023 
   5024 /*
   5025 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   5026 **
   5027 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   5028 ** to which a [prepared statement] belongs.  ^The [database connection]
   5029 ** returned by sqlite3_db_handle is the same [database connection]
   5030 ** that was the first argument
   5031 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   5032 ** create the statement in the first place.
   5033 */
   5034 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   5035 
   5036 /*
   5037 ** CAPI3REF: Return The Filename For A Database Connection
   5038 **
   5039 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
   5040 ** associated with database N of connection D.  ^The main database file
   5041 ** has the name "main".  If there is no attached database N on the database
   5042 ** connection D, or if database N is a temporary or in-memory database, then
   5043 ** a NULL pointer is returned.
   5044 **
   5045 ** ^The filename returned by this function is the output of the
   5046 ** xFullPathname method of the [VFS].  ^In other words, the filename
   5047 ** will be an absolute pathname, even if the filename used
   5048 ** to open the database originally was a URI or relative pathname.
   5049 */
   5050 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
   5051 
   5052 /*
   5053 ** CAPI3REF: Determine if a database is read-only
   5054 **
   5055 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
   5056 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
   5057 ** the name of a database on connection D.
   5058 */
   5059 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
   5060 
   5061 /*
   5062 ** CAPI3REF: Find the next prepared statement
   5063 **
   5064 ** ^This interface returns a pointer to the next [prepared statement] after
   5065 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   5066 ** then this interface returns a pointer to the first prepared statement
   5067 ** associated with the database connection pDb.  ^If no prepared statement
   5068 ** satisfies the conditions of this routine, it returns NULL.
   5069 **
   5070 ** The [database connection] pointer D in a call to
   5071 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   5072 ** connection and in particular must not be a NULL pointer.
   5073 */
   5074 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   5075 
   5076 /*
   5077 ** CAPI3REF: Commit And Rollback Notification Callbacks
   5078 **
   5079 ** ^The sqlite3_commit_hook() interface registers a callback
   5080 ** function to be invoked whenever a transaction is [COMMIT | committed].
   5081 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   5082 ** for the same database connection is overridden.
   5083 ** ^The sqlite3_rollback_hook() interface registers a callback
   5084 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   5085 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   5086 ** for the same database connection is overridden.
   5087 ** ^The pArg argument is passed through to the callback.
   5088 ** ^If the callback on a commit hook function returns non-zero,
   5089 ** then the commit is converted into a rollback.
   5090 **
   5091 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   5092 ** return the P argument from the previous call of the same function
   5093 ** on the same [database connection] D, or NULL for
   5094 ** the first call for each function on D.
   5095 **
   5096 ** The commit and rollback hook callbacks are not reentrant.
   5097 ** The callback implementation must not do anything that will modify
   5098 ** the database connection that invoked the callback.  Any actions
   5099 ** to modify the database connection must be deferred until after the
   5100 ** completion of the [sqlite3_step()] call that triggered the commit
   5101 ** or rollback hook in the first place.
   5102 ** Note that running any other SQL statements, including SELECT statements,
   5103 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
   5104 ** the database connections for the meaning of "modify" in this paragraph.
   5105 **
   5106 ** ^Registering a NULL function disables the callback.
   5107 **
   5108 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   5109 ** operation is allowed to continue normally.  ^If the commit hook
   5110 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   5111 ** ^The rollback hook is invoked on a rollback that results from a commit
   5112 ** hook returning non-zero, just as it would be with any other rollback.
   5113 **
   5114 ** ^For the purposes of this API, a transaction is said to have been
   5115 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   5116 ** an error or constraint causes an implicit rollback to occur.
   5117 ** ^The rollback callback is not invoked if a transaction is
   5118 ** automatically rolled back because the database connection is closed.
   5119 **
   5120 ** See also the [sqlite3_update_hook()] interface.
   5121 */
   5122 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   5123 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   5124 
   5125 /*
   5126 ** CAPI3REF: Data Change Notification Callbacks
   5127 **
   5128 ** ^The sqlite3_update_hook() interface registers a callback function
   5129 ** with the [database connection] identified by the first argument
   5130 ** to be invoked whenever a row is updated, inserted or deleted.
   5131 ** ^Any callback set by a previous call to this function
   5132 ** for the same database connection is overridden.
   5133 **
   5134 ** ^The second argument is a pointer to the function to invoke when a
   5135 ** row is updated, inserted or deleted.
   5136 ** ^The first argument to the callback is a copy of the third argument
   5137 ** to sqlite3_update_hook().
   5138 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   5139 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   5140 ** to be invoked.
   5141 ** ^The third and fourth arguments to the callback contain pointers to the
   5142 ** database and table name containing the affected row.
   5143 ** ^The final callback parameter is the [rowid] of the row.
   5144 ** ^In the case of an update, this is the [rowid] after the update takes place.
   5145 **
   5146 ** ^(The update hook is not invoked when internal system tables are
   5147 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   5148 **
   5149 ** ^In the current implementation, the update hook
   5150 ** is not invoked when duplication rows are deleted because of an
   5151 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   5152 ** invoked when rows are deleted using the [truncate optimization].
   5153 ** The exceptions defined in this paragraph might change in a future
   5154 ** release of SQLite.
   5155 **
   5156 ** The update hook implementation must not do anything that will modify
   5157 ** the database connection that invoked the update hook.  Any actions
   5158 ** to modify the database connection must be deferred until after the
   5159 ** completion of the [sqlite3_step()] call that triggered the update hook.
   5160 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   5161 ** database connections for the meaning of "modify" in this paragraph.
   5162 **
   5163 ** ^The sqlite3_update_hook(D,C,P) function
   5164 ** returns the P argument from the previous call
   5165 ** on the same [database connection] D, or NULL for
   5166 ** the first call on D.
   5167 **
   5168 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
   5169 ** interfaces.
   5170 */
   5171 SQLITE_API void *sqlite3_update_hook(
   5172   sqlite3*,
   5173   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   5174   void*
   5175 );
   5176 
   5177 /*
   5178 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   5179 ** KEYWORDS: {shared cache}
   5180 **
   5181 ** ^(This routine enables or disables the sharing of the database cache
   5182 ** and schema data structures between [database connection | connections]
   5183 ** to the same database. Sharing is enabled if the argument is true
   5184 ** and disabled if the argument is false.)^
   5185 **
   5186 ** ^Cache sharing is enabled and disabled for an entire process.
   5187 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
   5188 ** sharing was enabled or disabled for each thread separately.
   5189 **
   5190 ** ^(The cache sharing mode set by this interface effects all subsequent
   5191 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   5192 ** Existing database connections continue use the sharing mode
   5193 ** that was in effect at the time they were opened.)^
   5194 **
   5195 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   5196 ** successfully.  An [error code] is returned otherwise.)^
   5197 **
   5198 ** ^Shared cache is disabled by default. But this might change in
   5199 ** future releases of SQLite.  Applications that care about shared
   5200 ** cache setting should set it explicitly.
   5201 **
   5202 ** See Also:  [SQLite Shared-Cache Mode]
   5203 */
   5204 SQLITE_API int sqlite3_enable_shared_cache(int);
   5205 
   5206 /*
   5207 ** CAPI3REF: Attempt To Free Heap Memory
   5208 **
   5209 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   5210 ** of heap memory by deallocating non-essential memory allocations
   5211 ** held by the database library.   Memory used to cache database
   5212 ** pages to improve performance is an example of non-essential memory.
   5213 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   5214 ** which might be more or less than the amount requested.
   5215 ** ^The sqlite3_release_memory() routine is a no-op returning zero
   5216 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   5217 **
   5218 ** See also: [sqlite3_db_release_memory()]
   5219 */
   5220 SQLITE_API int sqlite3_release_memory(int);
   5221 
   5222 /*
   5223 ** CAPI3REF: Free Memory Used By A Database Connection
   5224 **
   5225 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
   5226 ** memory as possible from database connection D. Unlike the
   5227 ** [sqlite3_release_memory()] interface, this interface is effect even
   5228 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
   5229 ** omitted.
   5230 **
   5231 ** See also: [sqlite3_release_memory()]
   5232 */
   5233 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
   5234 
   5235 /*
   5236 ** CAPI3REF: Impose A Limit On Heap Size
   5237 **
   5238 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
   5239 ** soft limit on the amount of heap memory that may be allocated by SQLite.
   5240 ** ^SQLite strives to keep heap memory utilization below the soft heap
   5241 ** limit by reducing the number of pages held in the page cache
   5242 ** as heap memory usages approaches the limit.
   5243 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
   5244 ** below the limit, it will exceed the limit rather than generate
   5245 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
   5246 ** is advisory only.
   5247 **
   5248 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
   5249 ** the soft heap limit prior to the call, or negative in the case of an
   5250 ** error.  ^If the argument N is negative
   5251 ** then no change is made to the soft heap limit.  Hence, the current
   5252 ** size of the soft heap limit can be determined by invoking
   5253 ** sqlite3_soft_heap_limit64() with a negative argument.
   5254 **
   5255 ** ^If the argument N is zero then the soft heap limit is disabled.
   5256 **
   5257 ** ^(The soft heap limit is not enforced in the current implementation
   5258 ** if one or more of following conditions are true:
   5259 **
   5260 ** <ul>
   5261 ** <li> The soft heap limit is set to zero.
   5262 ** <li> Memory accounting is disabled using a combination of the
   5263 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
   5264 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
   5265 ** <li> An alternative page cache implementation is specified using
   5266 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
   5267 ** <li> The page cache allocates from its own memory pool supplied
   5268 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
   5269 **      from the heap.
   5270 ** </ul>)^
   5271 **
   5272 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
   5273 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
   5274 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
   5275 ** the soft heap limit is enforced on every memory allocation.  Without
   5276 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
   5277 ** when memory is allocated by the page cache.  Testing suggests that because
   5278 ** the page cache is the predominate memory user in SQLite, most
   5279 ** applications will achieve adequate soft heap limit enforcement without
   5280 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   5281 **
   5282 ** The circumstances under which SQLite will enforce the soft heap limit may
   5283 ** changes in future releases of SQLite.
   5284 */
   5285 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
   5286 
   5287 /*
   5288 ** CAPI3REF: Deprecated Soft Heap Limit Interface
   5289 ** DEPRECATED
   5290 **
   5291 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
   5292 ** interface.  This routine is provided for historical compatibility
   5293 ** only.  All new applications should use the
   5294 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
   5295 */
   5296 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
   5297 
   5298 
   5299 /*
   5300 ** CAPI3REF: Extract Metadata About A Column Of A Table
   5301 **
   5302 ** ^This routine returns metadata about a specific column of a specific
   5303 ** database table accessible using the [database connection] handle
   5304 ** passed as the first function argument.
   5305 **
   5306 ** ^The column is identified by the second, third and fourth parameters to
   5307 ** this function. ^The second parameter is either the name of the database
   5308 ** (i.e. "main", "temp", or an attached database) containing the specified
   5309 ** table or NULL. ^If it is NULL, then all attached databases are searched
   5310 ** for the table using the same algorithm used by the database engine to
   5311 ** resolve unqualified table references.
   5312 **
   5313 ** ^The third and fourth parameters to this function are the table and column
   5314 ** name of the desired column, respectively. Neither of these parameters
   5315 ** may be NULL.
   5316 **
   5317 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   5318 ** and subsequent parameters to this function. ^Any of these arguments may be
   5319 ** NULL, in which case the corresponding element of metadata is omitted.
   5320 **
   5321 ** ^(<blockquote>
   5322 ** <table border="1">
   5323 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   5324 **
   5325 ** <tr><td> 5th <td> const char* <td> Data type
   5326 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   5327 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   5328 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   5329 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   5330 ** </table>
   5331 ** </blockquote>)^
   5332 **
   5333 ** ^The memory pointed to by the character pointers returned for the
   5334 ** declaration type and collation sequence is valid only until the next
   5335 ** call to any SQLite API function.
   5336 **
   5337 ** ^If the specified table is actually a view, an [error code] is returned.
   5338 **
   5339 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
   5340 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   5341 ** parameters are set for the explicitly declared column. ^(If there is no
   5342 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
   5343 ** parameters are set as follows:
   5344 **
   5345 ** <pre>
   5346 **     data type: "INTEGER"
   5347 **     collation sequence: "BINARY"
   5348 **     not null: 0
   5349 **     primary key: 1
   5350 **     auto increment: 0
   5351 ** </pre>)^
   5352 **
   5353 ** ^(This function may load one or more schemas from database files. If an
   5354 ** error occurs during this process, or if the requested table or column
   5355 ** cannot be found, an [error code] is returned and an error message left
   5356 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
   5357 **
   5358 ** ^This API is only available if the library was compiled with the
   5359 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
   5360 */
   5361 SQLITE_API int sqlite3_table_column_metadata(
   5362   sqlite3 *db,                /* Connection handle */
   5363   const char *zDbName,        /* Database name or NULL */
   5364   const char *zTableName,     /* Table name */
   5365   const char *zColumnName,    /* Column name */
   5366   char const **pzDataType,    /* OUTPUT: Declared data type */
   5367   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   5368   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   5369   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   5370   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   5371 );
   5372 
   5373 /*
   5374 ** CAPI3REF: Load An Extension
   5375 **
   5376 ** ^This interface loads an SQLite extension library from the named file.
   5377 **
   5378 ** ^The sqlite3_load_extension() interface attempts to load an
   5379 ** SQLite extension library contained in the file zFile.
   5380 **
   5381 ** ^The entry point is zProc.
   5382 ** ^zProc may be 0, in which case the name of the entry point
   5383 ** defaults to "sqlite3_extension_init".
   5384 ** ^The sqlite3_load_extension() interface returns
   5385 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   5386 ** ^If an error occurs and pzErrMsg is not 0, then the
   5387 ** [sqlite3_load_extension()] interface shall attempt to
   5388 ** fill *pzErrMsg with error message text stored in memory
   5389 ** obtained from [sqlite3_malloc()]. The calling function
   5390 ** should free this memory by calling [sqlite3_free()].
   5391 **
   5392 ** ^Extension loading must be enabled using
   5393 ** [sqlite3_enable_load_extension()] prior to calling this API,
   5394 ** otherwise an error will be returned.
   5395 **
   5396 ** See also the [load_extension() SQL function].
   5397 */
   5398 SQLITE_API int sqlite3_load_extension(
   5399   sqlite3 *db,          /* Load the extension into this database connection */
   5400   const char *zFile,    /* Name of the shared library containing extension */
   5401   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   5402   char **pzErrMsg       /* Put error message here if not 0 */
   5403 );
   5404 
   5405 /*
   5406 ** CAPI3REF: Enable Or Disable Extension Loading
   5407 **
   5408 ** ^So as not to open security holes in older applications that are
   5409 ** unprepared to deal with extension loading, and as a means of disabling
   5410 ** extension loading while evaluating user-entered SQL, the following API
   5411 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   5412 **
   5413 ** ^Extension loading is off by default. See ticket #1863.
   5414 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   5415 ** to turn extension loading on and call it with onoff==0 to turn
   5416 ** it back off again.
   5417 */
   5418 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   5419 
   5420 /*
   5421 ** CAPI3REF: Automatically Load Statically Linked Extensions
   5422 **
   5423 ** ^This interface causes the xEntryPoint() function to be invoked for
   5424 ** each new [database connection] that is created.  The idea here is that
   5425 ** xEntryPoint() is the entry point for a statically linked SQLite extension
   5426 ** that is to be automatically loaded into all new database connections.
   5427 **
   5428 ** ^(Even though the function prototype shows that xEntryPoint() takes
   5429 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
   5430 ** arguments and expects and integer result as if the signature of the
   5431 ** entry point where as follows:
   5432 **
   5433 ** <blockquote><pre>
   5434 ** &nbsp;  int xEntryPoint(
   5435 ** &nbsp;    sqlite3 *db,
   5436 ** &nbsp;    const char **pzErrMsg,
   5437 ** &nbsp;    const struct sqlite3_api_routines *pThunk
   5438 ** &nbsp;  );
   5439 ** </pre></blockquote>)^
   5440 **
   5441 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
   5442 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
   5443 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
   5444 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
   5445 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
   5446 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
   5447 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
   5448 **
   5449 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
   5450 ** on the list of automatic extensions is a harmless no-op. ^No entry point
   5451 ** will be called more than once for each database connection that is opened.
   5452 **
   5453 ** See also: [sqlite3_reset_auto_extension()].
   5454 */
   5455 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
   5456 
   5457 /*
   5458 ** CAPI3REF: Reset Automatic Extension Loading
   5459 **
   5460 ** ^This interface disables all automatic extensions previously
   5461 ** registered using [sqlite3_auto_extension()].
   5462 */
   5463 SQLITE_API void sqlite3_reset_auto_extension(void);
   5464 
   5465 /*
   5466 ** The interface to the virtual-table mechanism is currently considered
   5467 ** to be experimental.  The interface might change in incompatible ways.
   5468 ** If this is a problem for you, do not use the interface at this time.
   5469 **
   5470 ** When the virtual-table mechanism stabilizes, we will declare the
   5471 ** interface fixed, support it indefinitely, and remove this comment.
   5472 */
   5473 
   5474 /*
   5475 ** Structures used by the virtual table interface
   5476 */
   5477 typedef struct sqlite3_vtab sqlite3_vtab;
   5478 typedef struct sqlite3_index_info sqlite3_index_info;
   5479 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   5480 typedef struct sqlite3_module sqlite3_module;
   5481 
   5482 /*
   5483 ** CAPI3REF: Virtual Table Object
   5484 ** KEYWORDS: sqlite3_module {virtual table module}
   5485 **
   5486 ** This structure, sometimes called a "virtual table module",
   5487 ** defines the implementation of a [virtual tables].
   5488 ** This structure consists mostly of methods for the module.
   5489 **
   5490 ** ^A virtual table module is created by filling in a persistent
   5491 ** instance of this structure and passing a pointer to that instance
   5492 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   5493 ** ^The registration remains valid until it is replaced by a different
   5494 ** module or until the [database connection] closes.  The content
   5495 ** of this structure must not change while it is registered with
   5496 ** any database connection.
   5497 */
   5498 struct sqlite3_module {
   5499   int iVersion;
   5500   int (*xCreate)(sqlite3*, void *pAux,
   5501                int argc, const char *const*argv,
   5502                sqlite3_vtab **ppVTab, char**);
   5503   int (*xConnect)(sqlite3*, void *pAux,
   5504                int argc, const char *const*argv,
   5505                sqlite3_vtab **ppVTab, char**);
   5506   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   5507   int (*xDisconnect)(sqlite3_vtab *pVTab);
   5508   int (*xDestroy)(sqlite3_vtab *pVTab);
   5509   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   5510   int (*xClose)(sqlite3_vtab_cursor*);
   5511   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   5512                 int argc, sqlite3_value **argv);
   5513   int (*xNext)(sqlite3_vtab_cursor*);
   5514   int (*xEof)(sqlite3_vtab_cursor*);
   5515   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   5516   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   5517   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   5518   int (*xBegin)(sqlite3_vtab *pVTab);
   5519   int (*xSync)(sqlite3_vtab *pVTab);
   5520   int (*xCommit)(sqlite3_vtab *pVTab);
   5521   int (*xRollback)(sqlite3_vtab *pVTab);
   5522   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   5523                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   5524                        void **ppArg);
   5525   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   5526   /* The methods above are in version 1 of the sqlite_module object. Those
   5527   ** below are for version 2 and greater. */
   5528   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
   5529   int (*xRelease)(sqlite3_vtab *pVTab, int);
   5530   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
   5531 };
   5532 
   5533 /*
   5534 ** CAPI3REF: Virtual Table Indexing Information
   5535 ** KEYWORDS: sqlite3_index_info
   5536 **
   5537 ** The sqlite3_index_info structure and its substructures is used as part
   5538 ** of the [virtual table] interface to
   5539 ** pass information into and receive the reply from the [xBestIndex]
   5540 ** method of a [virtual table module].  The fields under **Inputs** are the
   5541 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   5542 ** results into the **Outputs** fields.
   5543 **
   5544 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   5545 **
   5546 ** <blockquote>column OP expr</blockquote>
   5547 **
   5548 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   5549 ** stored in aConstraint[].op using one of the
   5550 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
   5551 ** ^(The index of the column is stored in
   5552 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   5553 ** expr on the right-hand side can be evaluated (and thus the constraint
   5554 ** is usable) and false if it cannot.)^
   5555 **
   5556 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   5557 ** and makes other simplifications to the WHERE clause in an attempt to
   5558 ** get as many WHERE clause terms into the form shown above as possible.
   5559 ** ^The aConstraint[] array only reports WHERE clause terms that are
   5560 ** relevant to the particular virtual table being queried.
   5561 **
   5562 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   5563 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   5564 **
   5565 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   5566 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   5567 ** the right-hand side of the corresponding aConstraint[] is evaluated
   5568 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   5569 ** is true, then the constraint is assumed to be fully handled by the
   5570 ** virtual table and is not checked again by SQLite.)^
   5571 **
   5572 ** ^The idxNum and idxPtr values are recorded and passed into the
   5573 ** [xFilter] method.
   5574 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   5575 ** needToFreeIdxPtr is true.
   5576 **
   5577 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   5578 ** the correct order to satisfy the ORDER BY clause so that no separate
   5579 ** sorting step is required.
   5580 **
   5581 ** ^The estimatedCost value is an estimate of the cost of doing the
   5582 ** particular lookup.  A full scan of a table with N entries should have
   5583 ** a cost of N.  A binary search of a table of N entries should have a
   5584 ** cost of approximately log(N).
   5585 */
   5586 struct sqlite3_index_info {
   5587   /* Inputs */
   5588   int nConstraint;           /* Number of entries in aConstraint */
   5589   struct sqlite3_index_constraint {
   5590      int iColumn;              /* Column on left-hand side of constraint */
   5591      unsigned char op;         /* Constraint operator */
   5592      unsigned char usable;     /* True if this constraint is usable */
   5593      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   5594   } *aConstraint;            /* Table of WHERE clause constraints */
   5595   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   5596   struct sqlite3_index_orderby {
   5597      int iColumn;              /* Column number */
   5598      unsigned char desc;       /* True for DESC.  False for ASC. */
   5599   } *aOrderBy;               /* The ORDER BY clause */
   5600   /* Outputs */
   5601   struct sqlite3_index_constraint_usage {
   5602     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   5603     unsigned char omit;      /* Do not code a test for this constraint */
   5604   } *aConstraintUsage;
   5605   int idxNum;                /* Number used to identify the index */
   5606   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   5607   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   5608   int orderByConsumed;       /* True if output is already ordered */
   5609   double estimatedCost;      /* Estimated cost of using this index */
   5610 };
   5611 
   5612 /*
   5613 ** CAPI3REF: Virtual Table Constraint Operator Codes
   5614 **
   5615 ** These macros defined the allowed values for the
   5616 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
   5617 ** an operator that is part of a constraint term in the wHERE clause of
   5618 ** a query that uses a [virtual table].
   5619 */
   5620 #define SQLITE_INDEX_CONSTRAINT_EQ    2
   5621 #define SQLITE_INDEX_CONSTRAINT_GT    4
   5622 #define SQLITE_INDEX_CONSTRAINT_LE    8
   5623 #define SQLITE_INDEX_CONSTRAINT_LT    16
   5624 #define SQLITE_INDEX_CONSTRAINT_GE    32
   5625 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
   5626 
   5627 /*
   5628 ** CAPI3REF: Register A Virtual Table Implementation
   5629 **
   5630 ** ^These routines are used to register a new [virtual table module] name.
   5631 ** ^Module names must be registered before
   5632 ** creating a new [virtual table] using the module and before using a
   5633 ** preexisting [virtual table] for the module.
   5634 **
   5635 ** ^The module name is registered on the [database connection] specified
   5636 ** by the first parameter.  ^The name of the module is given by the
   5637 ** second parameter.  ^The third parameter is a pointer to
   5638 ** the implementation of the [virtual table module].   ^The fourth
   5639 ** parameter is an arbitrary client data pointer that is passed through
   5640 ** into the [xCreate] and [xConnect] methods of the virtual table module
   5641 ** when a new virtual table is be being created or reinitialized.
   5642 **
   5643 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   5644 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   5645 ** invoke the destructor function (if it is not NULL) when SQLite
   5646 ** no longer needs the pClientData pointer.  ^The destructor will also
   5647 ** be invoked if the call to sqlite3_create_module_v2() fails.
   5648 ** ^The sqlite3_create_module()
   5649 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   5650 ** destructor.
   5651 */
   5652 SQLITE_API int sqlite3_create_module(
   5653   sqlite3 *db,               /* SQLite connection to register module with */
   5654   const char *zName,         /* Name of the module */
   5655   const sqlite3_module *p,   /* Methods for the module */
   5656   void *pClientData          /* Client data for xCreate/xConnect */
   5657 );
   5658 SQLITE_API int sqlite3_create_module_v2(
   5659   sqlite3 *db,               /* SQLite connection to register module with */
   5660   const char *zName,         /* Name of the module */
   5661   const sqlite3_module *p,   /* Methods for the module */
   5662   void *pClientData,         /* Client data for xCreate/xConnect */
   5663   void(*xDestroy)(void*)     /* Module destructor function */
   5664 );
   5665 
   5666 /*
   5667 ** CAPI3REF: Virtual Table Instance Object
   5668 ** KEYWORDS: sqlite3_vtab
   5669 **
   5670 ** Every [virtual table module] implementation uses a subclass
   5671 ** of this object to describe a particular instance
   5672 ** of the [virtual table].  Each subclass will
   5673 ** be tailored to the specific needs of the module implementation.
   5674 ** The purpose of this superclass is to define certain fields that are
   5675 ** common to all module implementations.
   5676 **
   5677 ** ^Virtual tables methods can set an error message by assigning a
   5678 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   5679 ** take care that any prior string is freed by a call to [sqlite3_free()]
   5680 ** prior to assigning a new string to zErrMsg.  ^After the error message
   5681 ** is delivered up to the client application, the string will be automatically
   5682 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   5683 */
   5684 struct sqlite3_vtab {
   5685   const sqlite3_module *pModule;  /* The module for this virtual table */
   5686   int nRef;                       /* NO LONGER USED */
   5687   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   5688   /* Virtual table implementations will typically add additional fields */
   5689 };
   5690 
   5691 /*
   5692 ** CAPI3REF: Virtual Table Cursor Object
   5693 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   5694 **
   5695 ** Every [virtual table module] implementation uses a subclass of the
   5696 ** following structure to describe cursors that point into the
   5697 ** [virtual table] and are used
   5698 ** to loop through the virtual table.  Cursors are created using the
   5699 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   5700 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   5701 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   5702 ** of the module.  Each module implementation will define
   5703 ** the content of a cursor structure to suit its own needs.
   5704 **
   5705 ** This superclass exists in order to define fields of the cursor that
   5706 ** are common to all implementations.
   5707 */
   5708 struct sqlite3_vtab_cursor {
   5709   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   5710   /* Virtual table implementations will typically add additional fields */
   5711 };
   5712 
   5713 /*
   5714 ** CAPI3REF: Declare The Schema Of A Virtual Table
   5715 **
   5716 ** ^The [xCreate] and [xConnect] methods of a
   5717 ** [virtual table module] call this interface
   5718 ** to declare the format (the names and datatypes of the columns) of
   5719 ** the virtual tables they implement.
   5720 */
   5721 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   5722 
   5723 /*
   5724 ** CAPI3REF: Overload A Function For A Virtual Table
   5725 **
   5726 ** ^(Virtual tables can provide alternative implementations of functions
   5727 ** using the [xFindFunction] method of the [virtual table module].
   5728 ** But global versions of those functions
   5729 ** must exist in order to be overloaded.)^
   5730 **
   5731 ** ^(This API makes sure a global version of a function with a particular
   5732 ** name and number of parameters exists.  If no such function exists
   5733 ** before this API is called, a new function is created.)^  ^The implementation
   5734 ** of the new function always causes an exception to be thrown.  So
   5735 ** the new function is not good for anything by itself.  Its only
   5736 ** purpose is to be a placeholder function that can be overloaded
   5737 ** by a [virtual table].
   5738 */
   5739 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   5740 
   5741 /*
   5742 ** The interface to the virtual-table mechanism defined above (back up
   5743 ** to a comment remarkably similar to this one) is currently considered
   5744 ** to be experimental.  The interface might change in incompatible ways.
   5745 ** If this is a problem for you, do not use the interface at this time.
   5746 **
   5747 ** When the virtual-table mechanism stabilizes, we will declare the
   5748 ** interface fixed, support it indefinitely, and remove this comment.
   5749 */
   5750 
   5751 /*
   5752 ** CAPI3REF: A Handle To An Open BLOB
   5753 ** KEYWORDS: {BLOB handle} {BLOB handles}
   5754 **
   5755 ** An instance of this object represents an open BLOB on which
   5756 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   5757 ** ^Objects of this type are created by [sqlite3_blob_open()]
   5758 ** and destroyed by [sqlite3_blob_close()].
   5759 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   5760 ** can be used to read or write small subsections of the BLOB.
   5761 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   5762 */
   5763 typedef struct sqlite3_blob sqlite3_blob;
   5764 
   5765 /*
   5766 ** CAPI3REF: Open A BLOB For Incremental I/O
   5767 **
   5768 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   5769 ** in row iRow, column zColumn, table zTable in database zDb;
   5770 ** in other words, the same BLOB that would be selected by:
   5771 **
   5772 ** <pre>
   5773 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   5774 ** </pre>)^
   5775 **
   5776 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   5777 ** and write access. ^If it is zero, the BLOB is opened for read access.
   5778 ** ^It is not possible to open a column that is part of an index or primary
   5779 ** key for writing. ^If [foreign key constraints] are enabled, it is
   5780 ** not possible to open a column that is part of a [child key] for writing.
   5781 **
   5782 ** ^Note that the database name is not the filename that contains
   5783 ** the database but rather the symbolic name of the database that
   5784 ** appears after the AS keyword when the database is connected using [ATTACH].
   5785 ** ^For the main database file, the database name is "main".
   5786 ** ^For TEMP tables, the database name is "temp".
   5787 **
   5788 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
   5789 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
   5790 ** to be a null pointer.)^
   5791 ** ^This function sets the [database connection] error code and message
   5792 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
   5793 ** functions. ^Note that the *ppBlob variable is always initialized in a
   5794 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
   5795 ** regardless of the success or failure of this routine.
   5796 **
   5797 ** ^(If the row that a BLOB handle points to is modified by an
   5798 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   5799 ** then the BLOB handle is marked as "expired".
   5800 ** This is true if any column of the row is changed, even a column
   5801 ** other than the one the BLOB handle is open on.)^
   5802 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   5803 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
   5804 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   5805 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   5806 ** commit if the transaction continues to completion.)^
   5807 **
   5808 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   5809 ** the opened blob.  ^The size of a blob may not be changed by this
   5810 ** interface.  Use the [UPDATE] SQL command to change the size of a
   5811 ** blob.
   5812 **
   5813 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   5814 ** and the built-in [zeroblob] SQL function can be used, if desired,
   5815 ** to create an empty, zero-filled blob in which to read or write using
   5816 ** this interface.
   5817 **
   5818 ** To avoid a resource leak, every open [BLOB handle] should eventually
   5819 ** be released by a call to [sqlite3_blob_close()].
   5820 */
   5821 SQLITE_API int sqlite3_blob_open(
   5822   sqlite3*,
   5823   const char *zDb,
   5824   const char *zTable,
   5825   const char *zColumn,
   5826   sqlite3_int64 iRow,
   5827   int flags,
   5828   sqlite3_blob **ppBlob
   5829 );
   5830 
   5831 /*
   5832 ** CAPI3REF: Move a BLOB Handle to a New Row
   5833 **
   5834 ** ^This function is used to move an existing blob handle so that it points
   5835 ** to a different row of the same database table. ^The new row is identified
   5836 ** by the rowid value passed as the second argument. Only the row can be
   5837 ** changed. ^The database, table and column on which the blob handle is open
   5838 ** remain the same. Moving an existing blob handle to a new row can be
   5839 ** faster than closing the existing handle and opening a new one.
   5840 **
   5841 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
   5842 ** it must exist and there must be either a blob or text value stored in
   5843 ** the nominated column.)^ ^If the new row is not present in the table, or if
   5844 ** it does not contain a blob or text value, or if another error occurs, an
   5845 ** SQLite error code is returned and the blob handle is considered aborted.
   5846 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
   5847 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
   5848 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
   5849 ** always returns zero.
   5850 **
   5851 ** ^This function sets the database handle error code and message.
   5852 */
   5853 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
   5854 
   5855 /*
   5856 ** CAPI3REF: Close A BLOB Handle
   5857 **
   5858 ** ^Closes an open [BLOB handle].
   5859 **
   5860 ** ^Closing a BLOB shall cause the current transaction to commit
   5861 ** if there are no other BLOBs, no pending prepared statements, and the
   5862 ** database connection is in [autocommit mode].
   5863 ** ^If any writes were made to the BLOB, they might be held in cache
   5864 ** until the close operation if they will fit.
   5865 **
   5866 ** ^(Closing the BLOB often forces the changes
   5867 ** out to disk and so if any I/O errors occur, they will likely occur
   5868 ** at the time when the BLOB is closed.  Any errors that occur during
   5869 ** closing are reported as a non-zero return value.)^
   5870 **
   5871 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
   5872 ** an error code, the BLOB is still closed.)^
   5873 **
   5874 ** ^Calling this routine with a null pointer (such as would be returned
   5875 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
   5876 */
   5877 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   5878 
   5879 /*
   5880 ** CAPI3REF: Return The Size Of An Open BLOB
   5881 **
   5882 ** ^Returns the size in bytes of the BLOB accessible via the
   5883 ** successfully opened [BLOB handle] in its only argument.  ^The
   5884 ** incremental blob I/O routines can only read or overwriting existing
   5885 ** blob content; they cannot change the size of a blob.
   5886 **
   5887 ** This routine only works on a [BLOB handle] which has been created
   5888 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5889 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5890 ** to this routine results in undefined and probably undesirable behavior.
   5891 */
   5892 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   5893 
   5894 /*
   5895 ** CAPI3REF: Read Data From A BLOB Incrementally
   5896 **
   5897 ** ^(This function is used to read data from an open [BLOB handle] into a
   5898 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   5899 ** from the open BLOB, starting at offset iOffset.)^
   5900 **
   5901 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5902 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   5903 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   5904 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   5905 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5906 **
   5907 ** ^An attempt to read from an expired [BLOB handle] fails with an
   5908 ** error code of [SQLITE_ABORT].
   5909 **
   5910 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   5911 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   5912 **
   5913 ** This routine only works on a [BLOB handle] which has been created
   5914 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5915 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5916 ** to this routine results in undefined and probably undesirable behavior.
   5917 **
   5918 ** See also: [sqlite3_blob_write()].
   5919 */
   5920 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   5921 
   5922 /*
   5923 ** CAPI3REF: Write Data Into A BLOB Incrementally
   5924 **
   5925 ** ^This function is used to write data into an open [BLOB handle] from a
   5926 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
   5927 ** into the open BLOB, starting at offset iOffset.
   5928 **
   5929 ** ^If the [BLOB handle] passed as the first argument was not opened for
   5930 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   5931 ** this function returns [SQLITE_READONLY].
   5932 **
   5933 ** ^This function may only modify the contents of the BLOB; it is
   5934 ** not possible to increase the size of a BLOB using this API.
   5935 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5936 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
   5937 ** less than zero [SQLITE_ERROR] is returned and no data is written.
   5938 ** The size of the BLOB (and hence the maximum value of N+iOffset)
   5939 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5940 **
   5941 ** ^An attempt to write to an expired [BLOB handle] fails with an
   5942 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   5943 ** before the [BLOB handle] expired are not rolled back by the
   5944 ** expiration of the handle, though of course those changes might
   5945 ** have been overwritten by the statement that expired the BLOB handle
   5946 ** or by other independent statements.
   5947 **
   5948 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   5949 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   5950 **
   5951 ** This routine only works on a [BLOB handle] which has been created
   5952 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5953 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5954 ** to this routine results in undefined and probably undesirable behavior.
   5955 **
   5956 ** See also: [sqlite3_blob_read()].
   5957 */
   5958 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   5959 
   5960 /*
   5961 ** CAPI3REF: Virtual File System Objects
   5962 **
   5963 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   5964 ** that SQLite uses to interact
   5965 ** with the underlying operating system.  Most SQLite builds come with a
   5966 ** single default VFS that is appropriate for the host computer.
   5967 ** New VFSes can be registered and existing VFSes can be unregistered.
   5968 ** The following interfaces are provided.
   5969 **
   5970 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   5971 ** ^Names are case sensitive.
   5972 ** ^Names are zero-terminated UTF-8 strings.
   5973 ** ^If there is no match, a NULL pointer is returned.
   5974 ** ^If zVfsName is NULL then the default VFS is returned.
   5975 **
   5976 ** ^New VFSes are registered with sqlite3_vfs_register().
   5977 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   5978 ** ^The same VFS can be registered multiple times without injury.
   5979 ** ^To make an existing VFS into the default VFS, register it again
   5980 ** with the makeDflt flag set.  If two different VFSes with the
   5981 ** same name are registered, the behavior is undefined.  If a
   5982 ** VFS is registered with a name that is NULL or an empty string,
   5983 ** then the behavior is undefined.
   5984 **
   5985 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   5986 ** ^(If the default VFS is unregistered, another VFS is chosen as
   5987 ** the default.  The choice for the new VFS is arbitrary.)^
   5988 */
   5989 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   5990 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   5991 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   5992 
   5993 /*
   5994 ** CAPI3REF: Mutexes
   5995 **
   5996 ** The SQLite core uses these routines for thread
   5997 ** synchronization. Though they are intended for internal
   5998 ** use by SQLite, code that links against SQLite is
   5999 ** permitted to use any of these routines.
   6000 **
   6001 ** The SQLite source code contains multiple implementations
   6002 ** of these mutex routines.  An appropriate implementation
   6003 ** is selected automatically at compile-time.  ^(The following
   6004 ** implementations are available in the SQLite core:
   6005 **
   6006 ** <ul>
   6007 ** <li>   SQLITE_MUTEX_OS2
   6008 ** <li>   SQLITE_MUTEX_PTHREADS
   6009 ** <li>   SQLITE_MUTEX_W32
   6010 ** <li>   SQLITE_MUTEX_NOOP
   6011 ** </ul>)^
   6012 **
   6013 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
   6014 ** that does no real locking and is appropriate for use in
   6015 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
   6016 ** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
   6017 ** are appropriate for use on OS/2, Unix, and Windows.
   6018 **
   6019 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   6020 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   6021 ** implementation is included with the library. In this case the
   6022 ** application must supply a custom mutex implementation using the
   6023 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   6024 ** before calling sqlite3_initialize() or any other public sqlite3_
   6025 ** function that calls sqlite3_initialize().)^
   6026 **
   6027 ** ^The sqlite3_mutex_alloc() routine allocates a new
   6028 ** mutex and returns a pointer to it. ^If it returns NULL
   6029 ** that means that a mutex could not be allocated.  ^SQLite
   6030 ** will unwind its stack and return an error.  ^(The argument
   6031 ** to sqlite3_mutex_alloc() is one of these integer constants:
   6032 **
   6033 ** <ul>
   6034 ** <li>  SQLITE_MUTEX_FAST
   6035 ** <li>  SQLITE_MUTEX_RECURSIVE
   6036 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   6037 ** <li>  SQLITE_MUTEX_STATIC_MEM
   6038 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   6039 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   6040 ** <li>  SQLITE_MUTEX_STATIC_LRU
   6041 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   6042 ** </ul>)^
   6043 **
   6044 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   6045 ** cause sqlite3_mutex_alloc() to create
   6046 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   6047 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   6048 ** The mutex implementation does not need to make a distinction
   6049 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   6050 ** not want to.  ^SQLite will only request a recursive mutex in
   6051 ** cases where it really needs one.  ^If a faster non-recursive mutex
   6052 ** implementation is available on the host platform, the mutex subsystem
   6053 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   6054 **
   6055 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   6056 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   6057 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
   6058 ** used by the current version of SQLite.  Future versions of SQLite
   6059 ** may add additional static mutexes.  Static mutexes are for internal
   6060 ** use by SQLite only.  Applications that use SQLite mutexes should
   6061 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   6062 ** SQLITE_MUTEX_RECURSIVE.
   6063 **
   6064 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   6065 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   6066 ** returns a different mutex on every call.  ^But for the static
   6067 ** mutex types, the same mutex is returned on every call that has
   6068 ** the same type number.
   6069 **
   6070 ** ^The sqlite3_mutex_free() routine deallocates a previously
   6071 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
   6072 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
   6073 ** use when they are deallocated.  Attempting to deallocate a static
   6074 ** mutex results in undefined behavior.  ^SQLite never deallocates
   6075 ** a static mutex.
   6076 **
   6077 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   6078 ** to enter a mutex.  ^If another thread is already within the mutex,
   6079 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   6080 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   6081 ** upon successful entry.  ^(Mutexes created using
   6082 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   6083 ** In such cases the,
   6084 ** mutex must be exited an equal number of times before another thread
   6085 ** can enter.)^  ^(If the same thread tries to enter any other
   6086 ** kind of mutex more than once, the behavior is undefined.
   6087 ** SQLite will never exhibit
   6088 ** such behavior in its own use of mutexes.)^
   6089 **
   6090 ** ^(Some systems (for example, Windows 95) do not support the operation
   6091 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   6092 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
   6093 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
   6094 **
   6095 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   6096 ** previously entered by the same thread.   ^(The behavior
   6097 ** is undefined if the mutex is not currently entered by the
   6098 ** calling thread or is not currently allocated.  SQLite will
   6099 ** never do either.)^
   6100 **
   6101 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   6102 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   6103 ** behave as no-ops.
   6104 **
   6105 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   6106 */
   6107 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   6108 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   6109 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   6110 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   6111 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   6112 
   6113 /*
   6114 ** CAPI3REF: Mutex Methods Object
   6115 **
   6116 ** An instance of this structure defines the low-level routines
   6117 ** used to allocate and use mutexes.
   6118 **
   6119 ** Usually, the default mutex implementations provided by SQLite are
   6120 ** sufficient, however the user has the option of substituting a custom
   6121 ** implementation for specialized deployments or systems for which SQLite
   6122 ** does not provide a suitable implementation. In this case, the user
   6123 ** creates and populates an instance of this structure to pass
   6124 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   6125 ** Additionally, an instance of this structure can be used as an
   6126 ** output variable when querying the system for the current mutex
   6127 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   6128 **
   6129 ** ^The xMutexInit method defined by this structure is invoked as
   6130 ** part of system initialization by the sqlite3_initialize() function.
   6131 ** ^The xMutexInit routine is called by SQLite exactly once for each
   6132 ** effective call to [sqlite3_initialize()].
   6133 **
   6134 ** ^The xMutexEnd method defined by this structure is invoked as
   6135 ** part of system shutdown by the sqlite3_shutdown() function. The
   6136 ** implementation of this method is expected to release all outstanding
   6137 ** resources obtained by the mutex methods implementation, especially
   6138 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   6139 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   6140 **
   6141 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   6142 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   6143 ** xMutexNotheld) implement the following interfaces (respectively):
   6144 **
   6145 ** <ul>
   6146 **   <li>  [sqlite3_mutex_alloc()] </li>
   6147 **   <li>  [sqlite3_mutex_free()] </li>
   6148 **   <li>  [sqlite3_mutex_enter()] </li>
   6149 **   <li>  [sqlite3_mutex_try()] </li>
   6150 **   <li>  [sqlite3_mutex_leave()] </li>
   6151 **   <li>  [sqlite3_mutex_held()] </li>
   6152 **   <li>  [sqlite3_mutex_notheld()] </li>
   6153 ** </ul>)^
   6154 **
   6155 ** The only difference is that the public sqlite3_XXX functions enumerated
   6156 ** above silently ignore any invocations that pass a NULL pointer instead
   6157 ** of a valid mutex handle. The implementations of the methods defined
   6158 ** by this structure are not required to handle this case, the results
   6159 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   6160 ** (i.e. it is acceptable to provide an implementation that segfaults if
   6161 ** it is passed a NULL pointer).
   6162 **
   6163 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
   6164 ** invoke xMutexInit() multiple times within the same process and without
   6165 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   6166 ** xMutexInit() must be no-ops.
   6167 **
   6168 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   6169 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
   6170 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   6171 ** memory allocation for a fast or recursive mutex.
   6172 **
   6173 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   6174 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   6175 ** If xMutexInit fails in any way, it is expected to clean up after itself
   6176 ** prior to returning.
   6177 */
   6178 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   6179 struct sqlite3_mutex_methods {
   6180   int (*xMutexInit)(void);
   6181   int (*xMutexEnd)(void);
   6182   sqlite3_mutex *(*xMutexAlloc)(int);
   6183   void (*xMutexFree)(sqlite3_mutex *);
   6184   void (*xMutexEnter)(sqlite3_mutex *);
   6185   int (*xMutexTry)(sqlite3_mutex *);
   6186   void (*xMutexLeave)(sqlite3_mutex *);
   6187   int (*xMutexHeld)(sqlite3_mutex *);
   6188   int (*xMutexNotheld)(sqlite3_mutex *);
   6189 };
   6190 
   6191 /*
   6192 ** CAPI3REF: Mutex Verification Routines
   6193 **
   6194 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   6195 ** are intended for use inside assert() statements.  ^The SQLite core
   6196 ** never uses these routines except inside an assert() and applications
   6197 ** are advised to follow the lead of the core.  ^The SQLite core only
   6198 ** provides implementations for these routines when it is compiled
   6199 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
   6200 ** are only required to provide these routines if SQLITE_DEBUG is
   6201 ** defined and if NDEBUG is not defined.
   6202 **
   6203 ** ^These routines should return true if the mutex in their argument
   6204 ** is held or not held, respectively, by the calling thread.
   6205 **
   6206 ** ^The implementation is not required to provide versions of these
   6207 ** routines that actually work. If the implementation does not provide working
   6208 ** versions of these routines, it should at least provide stubs that always
   6209 ** return true so that one does not get spurious assertion failures.
   6210 **
   6211 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
   6212 ** the routine should return 1.   This seems counter-intuitive since
   6213 ** clearly the mutex cannot be held if it does not exist.  But
   6214 ** the reason the mutex does not exist is because the build is not
   6215 ** using mutexes.  And we do not want the assert() containing the
   6216 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   6217 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
   6218 ** interface should also return 1 when given a NULL pointer.
   6219 */
   6220 #ifndef NDEBUG
   6221 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   6222 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   6223 #endif
   6224 
   6225 /*
   6226 ** CAPI3REF: Mutex Types
   6227 **
   6228 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   6229 ** which is one of these integer constants.
   6230 **
   6231 ** The set of static mutexes may change from one SQLite release to the
   6232 ** next.  Applications that override the built-in mutex logic must be
   6233 ** prepared to accommodate additional static mutexes.
   6234 */
   6235 #define SQLITE_MUTEX_FAST             0
   6236 #define SQLITE_MUTEX_RECURSIVE        1
   6237 #define SQLITE_MUTEX_STATIC_MASTER    2
   6238 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   6239 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   6240 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   6241 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
   6242 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   6243 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
   6244 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
   6245 
   6246 /*
   6247 ** CAPI3REF: Retrieve the mutex for a database connection
   6248 **
   6249 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   6250 ** serializes access to the [database connection] given in the argument
   6251 ** when the [threading mode] is Serialized.
   6252 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   6253 ** routine returns a NULL pointer.
   6254 */
   6255 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   6256 
   6257 /*
   6258 ** CAPI3REF: Low-Level Control Of Database Files
   6259 **
   6260 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   6261 ** xFileControl method for the [sqlite3_io_methods] object associated
   6262 ** with a particular database identified by the second argument. ^The
   6263 ** name of the database is "main" for the main database or "temp" for the
   6264 ** TEMP database, or the name that appears after the AS keyword for
   6265 ** databases that are added using the [ATTACH] SQL command.
   6266 ** ^A NULL pointer can be used in place of "main" to refer to the
   6267 ** main database file.
   6268 ** ^The third and fourth parameters to this routine
   6269 ** are passed directly through to the second and third parameters of
   6270 ** the xFileControl method.  ^The return value of the xFileControl
   6271 ** method becomes the return value of this routine.
   6272 **
   6273 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
   6274 ** a pointer to the underlying [sqlite3_file] object to be written into
   6275 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
   6276 ** case is a short-circuit path which does not actually invoke the
   6277 ** underlying sqlite3_io_methods.xFileControl method.
   6278 **
   6279 ** ^If the second parameter (zDbName) does not match the name of any
   6280 ** open database file, then SQLITE_ERROR is returned.  ^This error
   6281 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   6282 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   6283 ** also return SQLITE_ERROR.  There is no way to distinguish between
   6284 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   6285 ** xFileControl method.
   6286 **
   6287 ** See also: [SQLITE_FCNTL_LOCKSTATE]
   6288 */
   6289 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   6290 
   6291 /*
   6292 ** CAPI3REF: Testing Interface
   6293 **
   6294 ** ^The sqlite3_test_control() interface is used to read out internal
   6295 ** state of SQLite and to inject faults into SQLite for testing
   6296 ** purposes.  ^The first parameter is an operation code that determines
   6297 ** the number, meaning, and operation of all subsequent parameters.
   6298 **
   6299 ** This interface is not for use by applications.  It exists solely
   6300 ** for verifying the correct operation of the SQLite library.  Depending
   6301 ** on how the SQLite library is compiled, this interface might not exist.
   6302 **
   6303 ** The details of the operation codes, their meanings, the parameters
   6304 ** they take, and what they do are all subject to change without notice.
   6305 ** Unlike most of the SQLite API, this function is not guaranteed to
   6306 ** operate consistently from one release to the next.
   6307 */
   6308 SQLITE_API int sqlite3_test_control(int op, ...);
   6309 
   6310 /*
   6311 ** CAPI3REF: Testing Interface Operation Codes
   6312 **
   6313 ** These constants are the valid operation code parameters used
   6314 ** as the first argument to [sqlite3_test_control()].
   6315 **
   6316 ** These parameters and their meanings are subject to change
   6317 ** without notice.  These values are for testing purposes only.
   6318 ** Applications should not use any of these parameters or the
   6319 ** [sqlite3_test_control()] interface.
   6320 */
   6321 #define SQLITE_TESTCTRL_FIRST                    5
   6322 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   6323 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   6324 #define SQLITE_TESTCTRL_PRNG_RESET               7
   6325 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   6326 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   6327 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   6328 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   6329 #define SQLITE_TESTCTRL_ASSERT                  12
   6330 #define SQLITE_TESTCTRL_ALWAYS                  13
   6331 #define SQLITE_TESTCTRL_RESERVE                 14
   6332 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   6333 #define SQLITE_TESTCTRL_ISKEYWORD               16
   6334 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
   6335 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
   6336 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
   6337 #define SQLITE_TESTCTRL_LAST                    19
   6338 
   6339 /*
   6340 ** CAPI3REF: SQLite Runtime Status
   6341 **
   6342 ** ^This interface is used to retrieve runtime status information
   6343 ** about the performance of SQLite, and optionally to reset various
   6344 ** highwater marks.  ^The first argument is an integer code for
   6345 ** the specific parameter to measure.  ^(Recognized integer codes
   6346 ** are of the form [status parameters | SQLITE_STATUS_...].)^
   6347 ** ^The current value of the parameter is returned into *pCurrent.
   6348 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   6349 ** resetFlag is true, then the highest record value is reset after
   6350 ** *pHighwater is written.  ^(Some parameters do not record the highest
   6351 ** value.  For those parameters
   6352 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   6353 ** ^(Other parameters record only the highwater mark and not the current
   6354 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   6355 **
   6356 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
   6357 ** non-zero [error code] on failure.
   6358 **
   6359 ** This routine is threadsafe but is not atomic.  This routine can be
   6360 ** called while other threads are running the same or different SQLite
   6361 ** interfaces.  However the values returned in *pCurrent and
   6362 ** *pHighwater reflect the status of SQLite at different points in time
   6363 ** and it is possible that another thread might change the parameter
   6364 ** in between the times when *pCurrent and *pHighwater are written.
   6365 **
   6366 ** See also: [sqlite3_db_status()]
   6367 */
   6368 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   6369 
   6370 
   6371 /*
   6372 ** CAPI3REF: Status Parameters
   6373 ** KEYWORDS: {status parameters}
   6374 **
   6375 ** These integer constants designate various run-time status parameters
   6376 ** that can be returned by [sqlite3_status()].
   6377 **
   6378 ** <dl>
   6379 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   6380 ** <dd>This parameter is the current amount of memory checked out
   6381 ** using [sqlite3_malloc()], either directly or indirectly.  The
   6382 ** figure includes calls made to [sqlite3_malloc()] by the application
   6383 ** and internal memory usage by the SQLite library.  Scratch memory
   6384 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
   6385 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   6386 ** this parameter.  The amount returned is the sum of the allocation
   6387 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   6388 **
   6389 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   6390 ** <dd>This parameter records the largest memory allocation request
   6391 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   6392 ** internal equivalents).  Only the value returned in the
   6393 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6394 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6395 **
   6396 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
   6397 ** <dd>This parameter records the number of separate memory allocations
   6398 ** currently checked out.</dd>)^
   6399 **
   6400 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   6401 ** <dd>This parameter returns the number of pages used out of the
   6402 ** [pagecache memory allocator] that was configured using
   6403 ** [SQLITE_CONFIG_PAGECACHE].  The
   6404 ** value returned is in pages, not in bytes.</dd>)^
   6405 **
   6406 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
   6407 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   6408 ** <dd>This parameter returns the number of bytes of page cache
   6409 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
   6410 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   6411 ** returned value includes allocations that overflowed because they
   6412 ** where too large (they were larger than the "sz" parameter to
   6413 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   6414 ** no space was left in the page cache.</dd>)^
   6415 **
   6416 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   6417 ** <dd>This parameter records the largest memory allocation request
   6418 ** handed to [pagecache memory allocator].  Only the value returned in the
   6419 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6420 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6421 **
   6422 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
   6423 ** <dd>This parameter returns the number of allocations used out of the
   6424 ** [scratch memory allocator] configured using
   6425 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
   6426 ** in bytes.  Since a single thread may only have one scratch allocation
   6427 ** outstanding at time, this parameter also reports the number of threads
   6428 ** using scratch memory at the same time.</dd>)^
   6429 **
   6430 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   6431 ** <dd>This parameter returns the number of bytes of scratch memory
   6432 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
   6433 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
   6434 ** returned include overflows because the requested allocation was too
   6435 ** larger (that is, because the requested allocation was larger than the
   6436 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
   6437 ** slots were available.
   6438 ** </dd>)^
   6439 **
   6440 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   6441 ** <dd>This parameter records the largest memory allocation request
   6442 ** handed to [scratch memory allocator].  Only the value returned in the
   6443 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   6444 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   6445 **
   6446 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   6447 ** <dd>This parameter records the deepest parser stack.  It is only
   6448 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   6449 ** </dl>
   6450 **
   6451 ** New status parameters may be added from time to time.
   6452 */
   6453 #define SQLITE_STATUS_MEMORY_USED          0
   6454 #define SQLITE_STATUS_PAGECACHE_USED       1
   6455 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   6456 #define SQLITE_STATUS_SCRATCH_USED         3
   6457 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
   6458 #define SQLITE_STATUS_MALLOC_SIZE          5
   6459 #define SQLITE_STATUS_PARSER_STACK         6
   6460 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   6461 #define SQLITE_STATUS_SCRATCH_SIZE         8
   6462 #define SQLITE_STATUS_MALLOC_COUNT         9
   6463 
   6464 /*
   6465 ** CAPI3REF: Database Connection Status
   6466 **
   6467 ** ^This interface is used to retrieve runtime status information
   6468 ** about a single [database connection].  ^The first argument is the
   6469 ** database connection object to be interrogated.  ^The second argument
   6470 ** is an integer constant, taken from the set of
   6471 ** [SQLITE_DBSTATUS options], that
   6472 ** determines the parameter to interrogate.  The set of
   6473 ** [SQLITE_DBSTATUS options] is likely
   6474 ** to grow in future releases of SQLite.
   6475 **
   6476 ** ^The current value of the requested parameter is written into *pCur
   6477 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   6478 ** the resetFlg is true, then the highest instantaneous value is
   6479 ** reset back down to the current value.
   6480 **
   6481 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   6482 ** non-zero [error code] on failure.
   6483 **
   6484 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   6485 */
   6486 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   6487 
   6488 /*
   6489 ** CAPI3REF: Status Parameters for database connections
   6490 ** KEYWORDS: {SQLITE_DBSTATUS options}
   6491 **
   6492 ** These constants are the available integer "verbs" that can be passed as
   6493 ** the second argument to the [sqlite3_db_status()] interface.
   6494 **
   6495 ** New verbs may be added in future releases of SQLite. Existing verbs
   6496 ** might be discontinued. Applications should check the return code from
   6497 ** [sqlite3_db_status()] to make sure that the call worked.
   6498 ** The [sqlite3_db_status()] interface will return a non-zero error code
   6499 ** if a discontinued or unsupported verb is invoked.
   6500 **
   6501 ** <dl>
   6502 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   6503 ** <dd>This parameter returns the number of lookaside memory slots currently
   6504 ** checked out.</dd>)^
   6505 **
   6506 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
   6507 ** <dd>This parameter returns the number malloc attempts that were
   6508 ** satisfied using lookaside memory. Only the high-water value is meaningful;
   6509 ** the current value is always zero.)^
   6510 **
   6511 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
   6512 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
   6513 ** <dd>This parameter returns the number malloc attempts that might have
   6514 ** been satisfied using lookaside memory but failed due to the amount of
   6515 ** memory requested being larger than the lookaside slot size.
   6516 ** Only the high-water value is meaningful;
   6517 ** the current value is always zero.)^
   6518 **
   6519 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
   6520 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
   6521 ** <dd>This parameter returns the number malloc attempts that might have
   6522 ** been satisfied using lookaside memory but failed due to all lookaside
   6523 ** memory already being in use.
   6524 ** Only the high-water value is meaningful;
   6525 ** the current value is always zero.)^
   6526 **
   6527 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
   6528 ** <dd>This parameter returns the approximate number of of bytes of heap
   6529 ** memory used by all pager caches associated with the database connection.)^
   6530 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
   6531 **
   6532 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
   6533 ** <dd>This parameter returns the approximate number of of bytes of heap
   6534 ** memory used to store the schema for all databases associated
   6535 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
   6536 ** ^The full amount of memory used by the schemas is reported, even if the
   6537 ** schema memory is shared with other database connections due to
   6538 ** [shared cache mode] being enabled.
   6539 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
   6540 **
   6541 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
   6542 ** <dd>This parameter returns the approximate number of of bytes of heap
   6543 ** and lookaside memory used by all prepared statements associated with
   6544 ** the database connection.)^
   6545 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
   6546 ** </dd>
   6547 **
   6548 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
   6549 ** <dd>This parameter returns the number of pager cache hits that have
   6550 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
   6551 ** is always 0.
   6552 ** </dd>
   6553 **
   6554 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
   6555 ** <dd>This parameter returns the number of pager cache misses that have
   6556 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
   6557 ** is always 0.
   6558 ** </dd>
   6559 ** </dl>
   6560 */
   6561 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
   6562 #define SQLITE_DBSTATUS_CACHE_USED           1
   6563 #define SQLITE_DBSTATUS_SCHEMA_USED          2
   6564 #define SQLITE_DBSTATUS_STMT_USED            3
   6565 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
   6566 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
   6567 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
   6568 #define SQLITE_DBSTATUS_CACHE_HIT            7
   6569 #define SQLITE_DBSTATUS_CACHE_MISS           8
   6570 #define SQLITE_DBSTATUS_MAX                  8   /* Largest defined DBSTATUS */
   6571 
   6572 
   6573 /*
   6574 ** CAPI3REF: Prepared Statement Status
   6575 **
   6576 ** ^(Each prepared statement maintains various
   6577 ** [SQLITE_STMTSTATUS counters] that measure the number
   6578 ** of times it has performed specific operations.)^  These counters can
   6579 ** be used to monitor the performance characteristics of the prepared
   6580 ** statements.  For example, if the number of table steps greatly exceeds
   6581 ** the number of table searches or result rows, that would tend to indicate
   6582 ** that the prepared statement is using a full table scan rather than
   6583 ** an index.
   6584 **
   6585 ** ^(This interface is used to retrieve and reset counter values from
   6586 ** a [prepared statement].  The first argument is the prepared statement
   6587 ** object to be interrogated.  The second argument
   6588 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
   6589 ** to be interrogated.)^
   6590 ** ^The current value of the requested counter is returned.
   6591 ** ^If the resetFlg is true, then the counter is reset to zero after this
   6592 ** interface call returns.
   6593 **
   6594 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   6595 */
   6596 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   6597 
   6598 /*
   6599 ** CAPI3REF: Status Parameters for prepared statements
   6600 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
   6601 **
   6602 ** These preprocessor macros define integer codes that name counter
   6603 ** values associated with the [sqlite3_stmt_status()] interface.
   6604 ** The meanings of the various counters are as follows:
   6605 **
   6606 ** <dl>
   6607 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   6608 ** <dd>^This is the number of times that SQLite has stepped forward in
   6609 ** a table as part of a full table scan.  Large numbers for this counter
   6610 ** may indicate opportunities for performance improvement through
   6611 ** careful use of indices.</dd>
   6612 **
   6613 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
   6614 ** <dd>^This is the number of sort operations that have occurred.
   6615 ** A non-zero value in this counter may indicate an opportunity to
   6616 ** improvement performance through careful use of indices.</dd>
   6617 **
   6618 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
   6619 ** <dd>^This is the number of rows inserted into transient indices that
   6620 ** were created automatically in order to help joins run faster.
   6621 ** A non-zero value in this counter may indicate an opportunity to
   6622 ** improvement performance by adding permanent indices that do not
   6623 ** need to be reinitialized each time the statement is run.</dd>
   6624 ** </dl>
   6625 */
   6626 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   6627 #define SQLITE_STMTSTATUS_SORT              2
   6628 #define SQLITE_STMTSTATUS_AUTOINDEX         3
   6629 
   6630 /*
   6631 ** CAPI3REF: Custom Page Cache Object
   6632 **
   6633 ** The sqlite3_pcache type is opaque.  It is implemented by
   6634 ** the pluggable module.  The SQLite core has no knowledge of
   6635 ** its size or internal structure and never deals with the
   6636 ** sqlite3_pcache object except by holding and passing pointers
   6637 ** to the object.
   6638 **
   6639 ** See [sqlite3_pcache_methods2] for additional information.
   6640 */
   6641 typedef struct sqlite3_pcache sqlite3_pcache;
   6642 
   6643 /*
   6644 ** CAPI3REF: Custom Page Cache Object
   6645 **
   6646 ** The sqlite3_pcache_page object represents a single page in the
   6647 ** page cache.  The page cache will allocate instances of this
   6648 ** object.  Various methods of the page cache use pointers to instances
   6649 ** of this object as parameters or as their return value.
   6650 **
   6651 ** See [sqlite3_pcache_methods2] for additional information.
   6652 */
   6653 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
   6654 struct sqlite3_pcache_page {
   6655   void *pBuf;        /* The content of the page */
   6656   void *pExtra;      /* Extra information associated with the page */
   6657 };
   6658 
   6659 /*
   6660 ** CAPI3REF: Application Defined Page Cache.
   6661 ** KEYWORDS: {page cache}
   6662 **
   6663 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
   6664 ** register an alternative page cache implementation by passing in an
   6665 ** instance of the sqlite3_pcache_methods2 structure.)^
   6666 ** In many applications, most of the heap memory allocated by
   6667 ** SQLite is used for the page cache.
   6668 ** By implementing a
   6669 ** custom page cache using this API, an application can better control
   6670 ** the amount of memory consumed by SQLite, the way in which
   6671 ** that memory is allocated and released, and the policies used to
   6672 ** determine exactly which parts of a database file are cached and for
   6673 ** how long.
   6674 **
   6675 ** The alternative page cache mechanism is an
   6676 ** extreme measure that is only needed by the most demanding applications.
   6677 ** The built-in page cache is recommended for most uses.
   6678 **
   6679 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
   6680 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   6681 ** the application may discard the parameter after the call to
   6682 ** [sqlite3_config()] returns.)^
   6683 **
   6684 ** [[the xInit() page cache method]]
   6685 ** ^(The xInit() method is called once for each effective
   6686 ** call to [sqlite3_initialize()])^
   6687 ** (usually only once during the lifetime of the process). ^(The xInit()
   6688 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
   6689 ** The intent of the xInit() method is to set up global data structures
   6690 ** required by the custom page cache implementation.
   6691 ** ^(If the xInit() method is NULL, then the
   6692 ** built-in default page cache is used instead of the application defined
   6693 ** page cache.)^
   6694 **
   6695 ** [[the xShutdown() page cache method]]
   6696 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
   6697 ** It can be used to clean up
   6698 ** any outstanding resources before process shutdown, if required.
   6699 ** ^The xShutdown() method may be NULL.
   6700 **
   6701 ** ^SQLite automatically serializes calls to the xInit method,
   6702 ** so the xInit method need not be threadsafe.  ^The
   6703 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   6704 ** not need to be threadsafe either.  All other methods must be threadsafe
   6705 ** in multithreaded applications.
   6706 **
   6707 ** ^SQLite will never invoke xInit() more than once without an intervening
   6708 ** call to xShutdown().
   6709 **
   6710 ** [[the xCreate() page cache methods]]
   6711 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
   6712 ** SQLite will typically create one cache instance for each open database file,
   6713 ** though this is not guaranteed. ^The
   6714 ** first parameter, szPage, is the size in bytes of the pages that must
   6715 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
   6716 ** second parameter szExtra is a number of bytes of extra storage
   6717 ** associated with each page cache entry.  ^The szExtra parameter will
   6718 ** a number less than 250.  SQLite will use the
   6719 ** extra szExtra bytes on each page to store metadata about the underlying
   6720 ** database page on disk.  The value passed into szExtra depends
   6721 ** on the SQLite version, the target platform, and how SQLite was compiled.
   6722 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
   6723 ** created will be used to cache database pages of a file stored on disk, or
   6724 ** false if it is used for an in-memory database. The cache implementation
   6725 ** does not have to do anything special based with the value of bPurgeable;
   6726 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   6727 ** never invoke xUnpin() except to deliberately delete a page.
   6728 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
   6729 ** false will always have the "discard" flag set to true.
   6730 ** ^Hence, a cache created with bPurgeable false will
   6731 ** never contain any unpinned pages.
   6732 **
   6733 ** [[the xCachesize() page cache method]]
   6734 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   6735 ** suggested maximum cache-size (number of pages stored by) the cache
   6736 ** instance passed as the first argument. This is the value configured using
   6737 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
   6738 ** parameter, the implementation is not required to do anything with this
   6739 ** value; it is advisory only.
   6740 **
   6741 ** [[the xPagecount() page cache methods]]
   6742 ** The xPagecount() method must return the number of pages currently
   6743 ** stored in the cache, both pinned and unpinned.
   6744 **
   6745 ** [[the xFetch() page cache methods]]
   6746 ** The xFetch() method locates a page in the cache and returns a pointer to
   6747 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
   6748 ** The pBuf element of the returned sqlite3_pcache_page object will be a
   6749 ** pointer to a buffer of szPage bytes used to store the content of a
   6750 ** single database page.  The pExtra element of sqlite3_pcache_page will be
   6751 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
   6752 ** for each entry in the page cache.
   6753 **
   6754 ** The page to be fetched is determined by the key. ^The minimum key value
   6755 ** is 1.  After it has been retrieved using xFetch, the page is considered
   6756 ** to be "pinned".
   6757 **
   6758 ** If the requested page is already in the page cache, then the page cache
   6759 ** implementation must return a pointer to the page buffer with its content
   6760 ** intact.  If the requested page is not already in the cache, then the
   6761 ** cache implementation should use the value of the createFlag
   6762 ** parameter to help it determined what action to take:
   6763 **
   6764 ** <table border=1 width=85% align=center>
   6765 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
   6766 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   6767 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   6768 **                 Otherwise return NULL.
   6769 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   6770 **                 NULL if allocating a new page is effectively impossible.
   6771 ** </table>
   6772 **
   6773 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
   6774 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
   6775 ** failed.)^  In between the to xFetch() calls, SQLite may
   6776 ** attempt to unpin one or more cache pages by spilling the content of
   6777 ** pinned pages to disk and synching the operating system disk cache.
   6778 **
   6779 ** [[the xUnpin() page cache method]]
   6780 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   6781 ** as its second argument.  If the third parameter, discard, is non-zero,
   6782 ** then the page must be evicted from the cache.
   6783 ** ^If the discard parameter is
   6784 ** zero, then the page may be discarded or retained at the discretion of
   6785 ** page cache implementation. ^The page cache implementation
   6786 ** may choose to evict unpinned pages at any time.
   6787 **
   6788 ** The cache must not perform any reference counting. A single
   6789 ** call to xUnpin() unpins the page regardless of the number of prior calls
   6790 ** to xFetch().
   6791 **
   6792 ** [[the xRekey() page cache methods]]
   6793 ** The xRekey() method is used to change the key value associated with the
   6794 ** page passed as the second argument. If the cache
   6795 ** previously contains an entry associated with newKey, it must be
   6796 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   6797 ** to be pinned.
   6798 **
   6799 ** When SQLite calls the xTruncate() method, the cache must discard all
   6800 ** existing cache entries with page numbers (keys) greater than or equal
   6801 ** to the value of the iLimit parameter passed to xTruncate(). If any
   6802 ** of these pages are pinned, they are implicitly unpinned, meaning that
   6803 ** they can be safely discarded.
   6804 **
   6805 ** [[the xDestroy() page cache method]]
   6806 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   6807 ** All resources associated with the specified cache should be freed. ^After
   6808 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   6809 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
   6810 ** functions.
   6811 **
   6812 ** [[the xShrink() page cache method]]
   6813 ** ^SQLite invokes the xShrink() method when it wants the page cache to
   6814 ** free up as much of heap memory as possible.  The page cache implementation
   6815 ** is not obligated to free any memory, but well-behaved implementations should
   6816 ** do their best.
   6817 */
   6818 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
   6819 struct sqlite3_pcache_methods2 {
   6820   int iVersion;
   6821   void *pArg;
   6822   int (*xInit)(void*);
   6823   void (*xShutdown)(void*);
   6824   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
   6825   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   6826   int (*xPagecount)(sqlite3_pcache*);
   6827   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   6828   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
   6829   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
   6830       unsigned oldKey, unsigned newKey);
   6831   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   6832   void (*xDestroy)(sqlite3_pcache*);
   6833   void (*xShrink)(sqlite3_pcache*);
   6834 };
   6835 
   6836 /*
   6837 ** This is the obsolete pcache_methods object that has now been replaced
   6838 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
   6839 ** retained in the header file for backwards compatibility only.
   6840 */
   6841 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   6842 struct sqlite3_pcache_methods {
   6843   void *pArg;
   6844   int (*xInit)(void*);
   6845   void (*xShutdown)(void*);
   6846   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   6847   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   6848   int (*xPagecount)(sqlite3_pcache*);
   6849   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   6850   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   6851   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   6852   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   6853   void (*xDestroy)(sqlite3_pcache*);
   6854 };
   6855 
   6856 
   6857 /*
   6858 ** CAPI3REF: Online Backup Object
   6859 **
   6860 ** The sqlite3_backup object records state information about an ongoing
   6861 ** online backup operation.  ^The sqlite3_backup object is created by
   6862 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   6863 ** [sqlite3_backup_finish()].
   6864 **
   6865 ** See Also: [Using the SQLite Online Backup API]
   6866 */
   6867 typedef struct sqlite3_backup sqlite3_backup;
   6868 
   6869 /*
   6870 ** CAPI3REF: Online Backup API.
   6871 **
   6872 ** The backup API copies the content of one database into another.
   6873 ** It is useful either for creating backups of databases or
   6874 ** for copying in-memory databases to or from persistent files.
   6875 **
   6876 ** See Also: [Using the SQLite Online Backup API]
   6877 **
   6878 ** ^SQLite holds a write transaction open on the destination database file
   6879 ** for the duration of the backup operation.
   6880 ** ^The source database is read-locked only while it is being read;
   6881 ** it is not locked continuously for the entire backup operation.
   6882 ** ^Thus, the backup may be performed on a live source database without
   6883 ** preventing other database connections from
   6884 ** reading or writing to the source database while the backup is underway.
   6885 **
   6886 ** ^(To perform a backup operation:
   6887 **   <ol>
   6888 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   6889 **         backup,
   6890 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   6891 **         the data between the two databases, and finally
   6892 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   6893 **         associated with the backup operation.
   6894 **   </ol>)^
   6895 ** There should be exactly one call to sqlite3_backup_finish() for each
   6896 ** successful call to sqlite3_backup_init().
   6897 **
   6898 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
   6899 **
   6900 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   6901 ** [database connection] associated with the destination database
   6902 ** and the database name, respectively.
   6903 ** ^The database name is "main" for the main database, "temp" for the
   6904 ** temporary database, or the name specified after the AS keyword in
   6905 ** an [ATTACH] statement for an attached database.
   6906 ** ^The S and M arguments passed to
   6907 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   6908 ** and database name of the source database, respectively.
   6909 ** ^The source and destination [database connections] (parameters S and D)
   6910 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
   6911 ** an error.
   6912 **
   6913 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   6914 ** returned and an error code and error message are stored in the
   6915 ** destination [database connection] D.
   6916 ** ^The error code and message for the failed call to sqlite3_backup_init()
   6917 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   6918 ** [sqlite3_errmsg16()] functions.
   6919 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   6920 ** [sqlite3_backup] object.
   6921 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   6922 ** sqlite3_backup_finish() functions to perform the specified backup
   6923 ** operation.
   6924 **
   6925 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
   6926 **
   6927 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   6928 ** the source and destination databases specified by [sqlite3_backup] object B.
   6929 ** ^If N is negative, all remaining source pages are copied.
   6930 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   6931 ** are still more pages to be copied, then the function returns [SQLITE_OK].
   6932 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   6933 ** from source to destination, then it returns [SQLITE_DONE].
   6934 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   6935 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   6936 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   6937 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   6938 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   6939 **
   6940 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
   6941 ** <ol>
   6942 ** <li> the destination database was opened read-only, or
   6943 ** <li> the destination database is using write-ahead-log journaling
   6944 ** and the destination and source page sizes differ, or
   6945 ** <li> the destination database is an in-memory database and the
   6946 ** destination and source page sizes differ.
   6947 ** </ol>)^
   6948 **
   6949 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   6950 ** the [sqlite3_busy_handler | busy-handler function]
   6951 ** is invoked (if one is specified). ^If the
   6952 ** busy-handler returns non-zero before the lock is available, then
   6953 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   6954 ** sqlite3_backup_step() can be retried later. ^If the source
   6955 ** [database connection]
   6956 ** is being used to write to the source database when sqlite3_backup_step()
   6957 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   6958 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   6959 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   6960 ** [SQLITE_READONLY] is returned, then
   6961 ** there is no point in retrying the call to sqlite3_backup_step(). These
   6962 ** errors are considered fatal.)^  The application must accept
   6963 ** that the backup operation has failed and pass the backup operation handle
   6964 ** to the sqlite3_backup_finish() to release associated resources.
   6965 **
   6966 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   6967 ** on the destination file. ^The exclusive lock is not released until either
   6968 ** sqlite3_backup_finish() is called or the backup operation is complete
   6969 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   6970 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   6971 ** lasts for the duration of the sqlite3_backup_step() call.
   6972 ** ^Because the source database is not locked between calls to
   6973 ** sqlite3_backup_step(), the source database may be modified mid-way
   6974 ** through the backup process.  ^If the source database is modified by an
   6975 ** external process or via a database connection other than the one being
   6976 ** used by the backup operation, then the backup will be automatically
   6977 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   6978 ** database is modified by the using the same database connection as is used
   6979 ** by the backup operation, then the backup database is automatically
   6980 ** updated at the same time.
   6981 **
   6982 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
   6983 **
   6984 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   6985 ** application wishes to abandon the backup operation, the application
   6986 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   6987 ** ^The sqlite3_backup_finish() interfaces releases all
   6988 ** resources associated with the [sqlite3_backup] object.
   6989 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   6990 ** active write-transaction on the destination database is rolled back.
   6991 ** The [sqlite3_backup] object is invalid
   6992 ** and may not be used following a call to sqlite3_backup_finish().
   6993 **
   6994 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   6995 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   6996 ** sqlite3_backup_step() completed.
   6997 ** ^If an out-of-memory condition or IO error occurred during any prior
   6998 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   6999 ** sqlite3_backup_finish() returns the corresponding [error code].
   7000 **
   7001 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   7002 ** is not a permanent error and does not affect the return value of
   7003 ** sqlite3_backup_finish().
   7004 **
   7005 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
   7006 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
   7007 **
   7008 ** ^Each call to sqlite3_backup_step() sets two values inside
   7009 ** the [sqlite3_backup] object: the number of pages still to be backed
   7010 ** up and the total number of pages in the source database file.
   7011 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
   7012 ** retrieve these two values, respectively.
   7013 **
   7014 ** ^The values returned by these functions are only updated by
   7015 ** sqlite3_backup_step(). ^If the source database is modified during a backup
   7016 ** operation, then the values are not updated to account for any extra
   7017 ** pages that need to be updated or the size of the source database file
   7018 ** changing.
   7019 **
   7020 ** <b>Concurrent Usage of Database Handles</b>
   7021 **
   7022 ** ^The source [database connection] may be used by the application for other
   7023 ** purposes while a backup operation is underway or being initialized.
   7024 ** ^If SQLite is compiled and configured to support threadsafe database
   7025 ** connections, then the source database connection may be used concurrently
   7026 ** from within other threads.
   7027 **
   7028 ** However, the application must guarantee that the destination
   7029 ** [database connection] is not passed to any other API (by any thread) after
   7030 ** sqlite3_backup_init() is called and before the corresponding call to
   7031 ** sqlite3_backup_finish().  SQLite does not currently check to see
   7032 ** if the application incorrectly accesses the destination [database connection]
   7033 ** and so no error code is reported, but the operations may malfunction
   7034 ** nevertheless.  Use of the destination database connection while a
   7035 ** backup is in progress might also also cause a mutex deadlock.
   7036 **
   7037 ** If running in [shared cache mode], the application must
   7038 ** guarantee that the shared cache used by the destination database
   7039 ** is not accessed while the backup is running. In practice this means
   7040 ** that the application must guarantee that the disk file being
   7041 ** backed up to is not accessed by any connection within the process,
   7042 ** not just the specific connection that was passed to sqlite3_backup_init().
   7043 **
   7044 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   7045 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   7046 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   7047 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   7048 ** same time as another thread is invoking sqlite3_backup_step() it is
   7049 ** possible that they return invalid values.
   7050 */
   7051 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   7052   sqlite3 *pDest,                        /* Destination database handle */
   7053   const char *zDestName,                 /* Destination database name */
   7054   sqlite3 *pSource,                      /* Source database handle */
   7055   const char *zSourceName                /* Source database name */
   7056 );
   7057 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   7058 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   7059 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   7060 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   7061 
   7062 /*
   7063 ** CAPI3REF: Unlock Notification
   7064 **
   7065 ** ^When running in shared-cache mode, a database operation may fail with
   7066 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   7067 ** individual tables within the shared-cache cannot be obtained. See
   7068 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   7069 ** ^This API may be used to register a callback that SQLite will invoke
   7070 ** when the connection currently holding the required lock relinquishes it.
   7071 ** ^This API is only available if the library was compiled with the
   7072 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   7073 **
   7074 ** See Also: [Using the SQLite Unlock Notification Feature].
   7075 **
   7076 ** ^Shared-cache locks are released when a database connection concludes
   7077 ** its current transaction, either by committing it or rolling it back.
   7078 **
   7079 ** ^When a connection (known as the blocked connection) fails to obtain a
   7080 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   7081 ** identity of the database connection (the blocking connection) that
   7082 ** has locked the required resource is stored internally. ^After an
   7083 ** application receives an SQLITE_LOCKED error, it may call the
   7084 ** sqlite3_unlock_notify() method with the blocked connection handle as
   7085 ** the first argument to register for a callback that will be invoked
   7086 ** when the blocking connections current transaction is concluded. ^The
   7087 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   7088 ** call that concludes the blocking connections transaction.
   7089 **
   7090 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   7091 ** there is a chance that the blocking connection will have already
   7092 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   7093 ** If this happens, then the specified callback is invoked immediately,
   7094 ** from within the call to sqlite3_unlock_notify().)^
   7095 **
   7096 ** ^If the blocked connection is attempting to obtain a write-lock on a
   7097 ** shared-cache table, and more than one other connection currently holds
   7098 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   7099 ** the other connections to use as the blocking connection.
   7100 **
   7101 ** ^(There may be at most one unlock-notify callback registered by a
   7102 ** blocked connection. If sqlite3_unlock_notify() is called when the
   7103 ** blocked connection already has a registered unlock-notify callback,
   7104 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   7105 ** called with a NULL pointer as its second argument, then any existing
   7106 ** unlock-notify callback is canceled. ^The blocked connections
   7107 ** unlock-notify callback may also be canceled by closing the blocked
   7108 ** connection using [sqlite3_close()].
   7109 **
   7110 ** The unlock-notify callback is not reentrant. If an application invokes
   7111 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   7112 ** crash or deadlock may be the result.
   7113 **
   7114 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   7115 ** returns SQLITE_OK.
   7116 **
   7117 ** <b>Callback Invocation Details</b>
   7118 **
   7119 ** When an unlock-notify callback is registered, the application provides a
   7120 ** single void* pointer that is passed to the callback when it is invoked.
   7121 ** However, the signature of the callback function allows SQLite to pass
   7122 ** it an array of void* context pointers. The first argument passed to
   7123 ** an unlock-notify callback is a pointer to an array of void* pointers,
   7124 ** and the second is the number of entries in the array.
   7125 **
   7126 ** When a blocking connections transaction is concluded, there may be
   7127 ** more than one blocked connection that has registered for an unlock-notify
   7128 ** callback. ^If two or more such blocked connections have specified the
   7129 ** same callback function, then instead of invoking the callback function
   7130 ** multiple times, it is invoked once with the set of void* context pointers
   7131 ** specified by the blocked connections bundled together into an array.
   7132 ** This gives the application an opportunity to prioritize any actions
   7133 ** related to the set of unblocked database connections.
   7134 **
   7135 ** <b>Deadlock Detection</b>
   7136 **
   7137 ** Assuming that after registering for an unlock-notify callback a
   7138 ** database waits for the callback to be issued before taking any further
   7139 ** action (a reasonable assumption), then using this API may cause the
   7140 ** application to deadlock. For example, if connection X is waiting for
   7141 ** connection Y's transaction to be concluded, and similarly connection
   7142 ** Y is waiting on connection X's transaction, then neither connection
   7143 ** will proceed and the system may remain deadlocked indefinitely.
   7144 **
   7145 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   7146 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   7147 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   7148 ** unlock-notify callback is registered. The system is said to be in
   7149 ** a deadlocked state if connection A has registered for an unlock-notify
   7150 ** callback on the conclusion of connection B's transaction, and connection
   7151 ** B has itself registered for an unlock-notify callback when connection
   7152 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   7153 ** the system is also considered to be deadlocked if connection B has
   7154 ** registered for an unlock-notify callback on the conclusion of connection
   7155 ** C's transaction, where connection C is waiting on connection A. ^Any
   7156 ** number of levels of indirection are allowed.
   7157 **
   7158 ** <b>The "DROP TABLE" Exception</b>
   7159 **
   7160 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   7161 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   7162 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   7163 ** SQLite checks if there are any currently executing SELECT statements
   7164 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   7165 ** returned. In this case there is no "blocking connection", so invoking
   7166 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   7167 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   7168 ** or "DROP INDEX" query, an infinite loop might be the result.
   7169 **
   7170 ** One way around this problem is to check the extended error code returned
   7171 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   7172 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   7173 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   7174 ** SQLITE_LOCKED.)^
   7175 */
   7176 SQLITE_API int sqlite3_unlock_notify(
   7177   sqlite3 *pBlocked,                          /* Waiting connection */
   7178   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   7179   void *pNotifyArg                            /* Argument to pass to xNotify */
   7180 );
   7181 
   7182 
   7183 /*
   7184 ** CAPI3REF: String Comparison
   7185 **
   7186 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
   7187 ** and extensions to compare the contents of two buffers containing UTF-8
   7188 ** strings in a case-independent fashion, using the same definition of "case
   7189 ** independence" that SQLite uses internally when comparing identifiers.
   7190 */
   7191 SQLITE_API int sqlite3_stricmp(const char *, const char *);
   7192 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   7193 
   7194 /*
   7195 ** CAPI3REF: Error Logging Interface
   7196 **
   7197 ** ^The [sqlite3_log()] interface writes a message into the error log
   7198 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
   7199 ** ^If logging is enabled, the zFormat string and subsequent arguments are
   7200 ** used with [sqlite3_snprintf()] to generate the final output string.
   7201 **
   7202 ** The sqlite3_log() interface is intended for use by extensions such as
   7203 ** virtual tables, collating functions, and SQL functions.  While there is
   7204 ** nothing to prevent an application from calling sqlite3_log(), doing so
   7205 ** is considered bad form.
   7206 **
   7207 ** The zFormat string must not be NULL.
   7208 **
   7209 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   7210 ** will not use dynamically allocated memory.  The log message is stored in
   7211 ** a fixed-length buffer on the stack.  If the log message is longer than
   7212 ** a few hundred characters, it will be truncated to the length of the
   7213 ** buffer.
   7214 */
   7215 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   7216 
   7217 /*
   7218 ** CAPI3REF: Write-Ahead Log Commit Hook
   7219 **
   7220 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
   7221 ** will be invoked each time a database connection commits data to a
   7222 ** [write-ahead log] (i.e. whenever a transaction is committed in
   7223 ** [journal_mode | journal_mode=WAL mode]).
   7224 **
   7225 ** ^The callback is invoked by SQLite after the commit has taken place and
   7226 ** the associated write-lock on the database released, so the implementation
   7227 ** may read, write or [checkpoint] the database as required.
   7228 **
   7229 ** ^The first parameter passed to the callback function when it is invoked
   7230 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
   7231 ** registering the callback. ^The second is a copy of the database handle.
   7232 ** ^The third parameter is the name of the database that was written to -
   7233 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
   7234 ** is the number of pages currently in the write-ahead log file,
   7235 ** including those that were just committed.
   7236 **
   7237 ** The callback function should normally return [SQLITE_OK].  ^If an error
   7238 ** code is returned, that error will propagate back up through the
   7239 ** SQLite code base to cause the statement that provoked the callback
   7240 ** to report an error, though the commit will have still occurred. If the
   7241 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
   7242 ** that does not correspond to any valid SQLite error code, the results
   7243 ** are undefined.
   7244 **
   7245 ** A single database handle may have at most a single write-ahead log callback
   7246 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
   7247 ** previously registered write-ahead log callback. ^Note that the
   7248 ** [sqlite3_wal_autocheckpoint()] interface and the
   7249 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
   7250 ** those overwrite any prior [sqlite3_wal_hook()] settings.
   7251 */
   7252 SQLITE_API void *sqlite3_wal_hook(
   7253   sqlite3*,
   7254   int(*)(void *,sqlite3*,const char*,int),
   7255   void*
   7256 );
   7257 
   7258 /*
   7259 ** CAPI3REF: Configure an auto-checkpoint
   7260 **
   7261 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
   7262 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
   7263 ** to automatically [checkpoint]
   7264 ** after committing a transaction if there are N or
   7265 ** more frames in the [write-ahead log] file.  ^Passing zero or
   7266 ** a negative value as the nFrame parameter disables automatic
   7267 ** checkpoints entirely.
   7268 **
   7269 ** ^The callback registered by this function replaces any existing callback
   7270 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
   7271 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
   7272 ** configured by this function.
   7273 **
   7274 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
   7275 ** from SQL.
   7276 **
   7277 ** ^Every new [database connection] defaults to having the auto-checkpoint
   7278 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
   7279 ** pages.  The use of this interface
   7280 ** is only necessary if the default setting is found to be suboptimal
   7281 ** for a particular application.
   7282 */
   7283 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
   7284 
   7285 /*
   7286 ** CAPI3REF: Checkpoint a database
   7287 **
   7288 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
   7289 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
   7290 ** empty string, then a checkpoint is run on all databases of
   7291 ** connection D.  ^If the database connection D is not in
   7292 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
   7293 **
   7294 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
   7295 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
   7296 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
   7297 ** run whenever the WAL reaches a certain size threshold.
   7298 **
   7299 ** See also: [sqlite3_wal_checkpoint_v2()]
   7300 */
   7301 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
   7302 
   7303 /*
   7304 ** CAPI3REF: Checkpoint a database
   7305 **
   7306 ** Run a checkpoint operation on WAL database zDb attached to database
   7307 ** handle db. The specific operation is determined by the value of the
   7308 ** eMode parameter:
   7309 **
   7310 ** <dl>
   7311 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
   7312 **   Checkpoint as many frames as possible without waiting for any database
   7313 **   readers or writers to finish. Sync the db file if all frames in the log
   7314 **   are checkpointed. This mode is the same as calling
   7315 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
   7316 **
   7317 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
   7318 **   This mode blocks (calls the busy-handler callback) until there is no
   7319 **   database writer and all readers are reading from the most recent database
   7320 **   snapshot. It then checkpoints all frames in the log file and syncs the
   7321 **   database file. This call blocks database writers while it is running,
   7322 **   but not database readers.
   7323 **
   7324 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
   7325 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
   7326 **   checkpointing the log file it blocks (calls the 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 **
   7465 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
   7466 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
   7467 ** is for the SQL statement being evaluated.
   7468 **
   7469 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
   7470 ** return value from the [sqlite3_set_authorizer()] callback and that
   7471 ** [SQLITE_ABORT] is also a [result code].
   7472 */
   7473 #define SQLITE_ROLLBACK 1
   7474 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
   7475 #define SQLITE_FAIL     3
   7476 /* #define SQLITE_ABORT 4  // Also an error code */
   7477 #define SQLITE_REPLACE  5
   7478 
   7479 
   7480 
   7481 /*
   7482 ** Undo the hack that converts floating point types to integer for
   7483 ** builds on processors without floating point support.
   7484 */
   7485 #ifdef SQLITE_OMIT_FLOATING_POINT
   7486 # undef double
   7487 #endif
   7488 
   7489 #if 0
   7490 }  /* End of the 'extern "C"' block */
   7491 #endif
   7492 #endif
   7493 
   7494 /*
   7495 ** 2010 August 30
   7496 **
   7497 ** The author disclaims copyright to this source code.  In place of
   7498 ** a legal notice, here is a blessing:
   7499 **
   7500 **    May you do good and not evil.
   7501 **    May you find forgiveness for yourself and forgive others.
   7502 **    May you share freely, never taking more than you give.
   7503 **
   7504 *************************************************************************
   7505 */
   7506 
   7507 #ifndef _SQLITE3RTREE_H_
   7508 #define _SQLITE3RTREE_H_
   7509 
   7510 
   7511 #if 0
   7512 extern "C" {
   7513 #endif
   7514 
   7515 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
   7516 
   7517 /*
   7518 ** Register a geometry callback named zGeom that can be used as part of an
   7519 ** R-Tree geometry query as follows:
   7520 **
   7521 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
   7522 */
   7523 SQLITE_API int sqlite3_rtree_geometry_callback(
   7524   sqlite3 *db,
   7525   const char *zGeom,
   7526   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
   7527   void *pContext
   7528 );
   7529 
   7530 
   7531 /*
   7532 ** A pointer to a structure of the following type is passed as the first
   7533 ** argument to callbacks registered using rtree_geometry_callback().
   7534 */
   7535 struct sqlite3_rtree_geometry {
   7536   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
   7537   int nParam;                     /* Size of array aParam[] */
   7538   double *aParam;                 /* Parameters passed to SQL geom function */
   7539   void *pUser;                    /* Callback implementation user data */
   7540   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
   7541 };
   7542 
   7543 
   7544 #if 0
   7545 }  /* end of the 'extern "C"' block */
   7546 #endif
   7547 
   7548 #endif  /* ifndef _SQLITE3RTREE_H_ */
   7549 
   7550 
   7551 /************** End of sqlite3.h *********************************************/
   7552 /************** Continuing where we left off in sqliteInt.h ******************/
   7553 /************** Include hash.h in the middle of sqliteInt.h ******************/
   7554 /************** Begin file hash.h ********************************************/
   7555 /*
   7556 ** 2001 September 22
   7557 **
   7558 ** The author disclaims copyright to this source code.  In place of
   7559 ** a legal notice, here is a blessing:
   7560 **
   7561 **    May you do good and not evil.
   7562 **    May you find forgiveness for yourself and forgive others.
   7563 **    May you share freely, never taking more than you give.
   7564 **
   7565 *************************************************************************
   7566 ** This is the header file for the generic hash-table implemenation
   7567 ** used in SQLite.
   7568 */
   7569 #ifndef _SQLITE_HASH_H_
   7570 #define _SQLITE_HASH_H_
   7571 
   7572 /* Forward declarations of structures. */
   7573 typedef struct Hash Hash;
   7574 typedef struct HashElem HashElem;
   7575 
   7576 /* A complete hash table is an instance of the following structure.
   7577 ** The internals of this structure are intended to be opaque -- client
   7578 ** code should not attempt to access or modify the fields of this structure
   7579 ** directly.  Change this structure only by using the routines below.
   7580 ** However, some of the "procedures" and "functions" for modifying and
   7581 ** accessing this structure are really macros, so we can't really make
   7582 ** this structure opaque.
   7583 **
   7584 ** All elements of the hash table are on a single doubly-linked list.
   7585 ** Hash.first points to the head of this list.
   7586 **
   7587 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   7588 ** the global doubly-linked list.  The contents of the bucket are the
   7589 ** element pointed to plus the next _ht.count-1 elements in the list.
   7590 **
   7591 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   7592 ** by a linear search of the global list.  For small tables, the
   7593 ** Hash.ht table is never allocated because if there are few elements
   7594 ** in the table, it is faster to do a linear search than to manage
   7595 ** the hash table.
   7596 */
   7597 struct Hash {
   7598   unsigned int htsize;      /* Number of buckets in the hash table */
   7599   unsigned int count;       /* Number of entries in this table */
   7600   HashElem *first;          /* The first element of the array */
   7601   struct _ht {              /* the hash table */
   7602     int count;                 /* Number of entries with this hash */
   7603     HashElem *chain;           /* Pointer to first entry with this hash */
   7604   } *ht;
   7605 };
   7606 
   7607 /* Each element in the hash table is an instance of the following
   7608 ** structure.  All elements are stored on a single doubly-linked list.
   7609 **
   7610 ** Again, this structure is intended to be opaque, but it can't really
   7611 ** be opaque because it is used by macros.
   7612 */
   7613 struct HashElem {
   7614   HashElem *next, *prev;       /* Next and previous elements in the table */
   7615   void *data;                  /* Data associated with this element */
   7616   const char *pKey; int nKey;  /* Key associated with this element */
   7617 };
   7618 
   7619 /*
   7620 ** Access routines.  To delete, insert a NULL pointer.
   7621 */
   7622 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   7623 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
   7624 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
   7625 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   7626 
   7627 /*
   7628 ** Macros for looping over all elements of a hash table.  The idiom is
   7629 ** like this:
   7630 **
   7631 **   Hash h;
   7632 **   HashElem *p;
   7633 **   ...
   7634 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   7635 **     SomeStructure *pData = sqliteHashData(p);
   7636 **     // do something with pData
   7637 **   }
   7638 */
   7639 #define sqliteHashFirst(H)  ((H)->first)
   7640 #define sqliteHashNext(E)   ((E)->next)
   7641 #define sqliteHashData(E)   ((E)->data)
   7642 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   7643 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   7644 
   7645 /*
   7646 ** Number of entries in a hash table
   7647 */
   7648 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   7649 
   7650 #endif /* _SQLITE_HASH_H_ */
   7651 
   7652 /************** End of hash.h ************************************************/
   7653 /************** Continuing where we left off in sqliteInt.h ******************/
   7654 /************** Include parse.h in the middle of sqliteInt.h *****************/
   7655 /************** Begin file parse.h *******************************************/
   7656 #define TK_SEMI                            1
   7657 #define TK_EXPLAIN                         2
   7658 #define TK_QUERY                           3
   7659 #define TK_PLAN                            4
   7660 #define TK_BEGIN                           5
   7661 #define TK_TRANSACTION                     6
   7662 #define TK_DEFERRED                        7
   7663 #define TK_IMMEDIATE                       8
   7664 #define TK_EXCLUSIVE                       9
   7665 #define TK_COMMIT                         10
   7666 #define TK_END                            11
   7667 #define TK_ROLLBACK                       12
   7668 #define TK_SAVEPOINT                      13
   7669 #define TK_RELEASE                        14
   7670 #define TK_TO                             15
   7671 #define TK_TABLE                          16
   7672 #define TK_CREATE                         17
   7673 #define TK_IF                             18
   7674 #define TK_NOT                            19
   7675 #define TK_EXISTS                         20
   7676 #define TK_TEMP                           21
   7677 #define TK_LP                             22
   7678 #define TK_RP                             23
   7679 #define TK_AS                             24
   7680 #define TK_COMMA                          25
   7681 #define TK_ID                             26
   7682 #define TK_INDEXED                        27
   7683 #define TK_ABORT                          28
   7684 #define TK_ACTION                         29
   7685 #define TK_AFTER                          30
   7686 #define TK_ANALYZE                        31
   7687 #define TK_ASC                            32
   7688 #define TK_ATTACH                         33
   7689 #define TK_BEFORE                         34
   7690 #define TK_BY                             35
   7691 #define TK_CASCADE                        36
   7692 #define TK_CAST                           37
   7693 #define TK_COLUMNKW                       38
   7694 #define TK_CONFLICT                       39
   7695 #define TK_DATABASE                       40
   7696 #define TK_DESC                           41
   7697 #define TK_DETACH                         42
   7698 #define TK_EACH                           43
   7699 #define TK_FAIL                           44
   7700 #define TK_FOR                            45
   7701 #define TK_IGNORE                         46
   7702 #define TK_INITIALLY                      47
   7703 #define TK_INSTEAD                        48
   7704 #define TK_LIKE_KW                        49
   7705 #define TK_MATCH                          50
   7706 #define TK_NO                             51
   7707 #define TK_KEY                            52
   7708 #define TK_OF                             53
   7709 #define TK_OFFSET                         54
   7710 #define TK_PRAGMA                         55
   7711 #define TK_RAISE                          56
   7712 #define TK_REPLACE                        57
   7713 #define TK_RESTRICT                       58
   7714 #define TK_ROW                            59
   7715 #define TK_TRIGGER                        60
   7716 #define TK_VACUUM                         61
   7717 #define TK_VIEW                           62
   7718 #define TK_VIRTUAL                        63
   7719 #define TK_REINDEX                        64
   7720 #define TK_RENAME                         65
   7721 #define TK_CTIME_KW                       66
   7722 #define TK_ANY                            67
   7723 #define TK_OR                             68
   7724 #define TK_AND                            69
   7725 #define TK_IS                             70
   7726 #define TK_BETWEEN                        71
   7727 #define TK_IN                             72
   7728 #define TK_ISNULL                         73
   7729 #define TK_NOTNULL                        74
   7730 #define TK_NE                             75
   7731 #define TK_EQ                             76
   7732 #define TK_GT                             77
   7733 #define TK_LE                             78
   7734 #define TK_LT                             79
   7735 #define TK_GE                             80
   7736 #define TK_ESCAPE                         81
   7737 #define TK_BITAND                         82
   7738 #define TK_BITOR                          83
   7739 #define TK_LSHIFT                         84
   7740 #define TK_RSHIFT                         85
   7741 #define TK_PLUS                           86
   7742 #define TK_MINUS                          87
   7743 #define TK_STAR                           88
   7744 #define TK_SLASH                          89
   7745 #define TK_REM                            90
   7746 #define TK_CONCAT                         91
   7747 #define TK_COLLATE                        92
   7748 #define TK_BITNOT                         93
   7749 #define TK_STRING                         94
   7750 #define TK_JOIN_KW                        95
   7751 #define TK_CONSTRAINT                     96
   7752 #define TK_DEFAULT                        97
   7753 #define TK_NULL                           98
   7754 #define TK_PRIMARY                        99
   7755 #define TK_UNIQUE                         100
   7756 #define TK_CHECK                          101
   7757 #define TK_REFERENCES                     102
   7758 #define TK_AUTOINCR                       103
   7759 #define TK_ON                             104
   7760 #define TK_INSERT                         105
   7761 #define TK_DELETE                         106
   7762 #define TK_UPDATE                         107
   7763 #define TK_SET                            108
   7764 #define TK_DEFERRABLE                     109
   7765 #define TK_FOREIGN                        110
   7766 #define TK_DROP                           111
   7767 #define TK_UNION                          112
   7768 #define TK_ALL                            113
   7769 #define TK_EXCEPT                         114
   7770 #define TK_INTERSECT                      115
   7771 #define TK_SELECT                         116
   7772 #define TK_DISTINCT                       117
   7773 #define TK_DOT                            118
   7774 #define TK_FROM                           119
   7775 #define TK_JOIN                           120
   7776 #define TK_USING                          121
   7777 #define TK_ORDER                          122
   7778 #define TK_GROUP                          123
   7779 #define TK_HAVING                         124
   7780 #define TK_LIMIT                          125
   7781 #define TK_WHERE                          126
   7782 #define TK_INTO                           127
   7783 #define TK_VALUES                         128
   7784 #define TK_INTEGER                        129
   7785 #define TK_FLOAT                          130
   7786 #define TK_BLOB                           131
   7787 #define TK_REGISTER                       132
   7788 #define TK_VARIABLE                       133
   7789 #define TK_CASE                           134
   7790 #define TK_WHEN                           135
   7791 #define TK_THEN                           136
   7792 #define TK_ELSE                           137
   7793 #define TK_INDEX                          138
   7794 #define TK_ALTER                          139
   7795 #define TK_ADD                            140
   7796 #define TK_TO_TEXT                        141
   7797 #define TK_TO_BLOB                        142
   7798 #define TK_TO_NUMERIC                     143
   7799 #define TK_TO_INT                         144
   7800 #define TK_TO_REAL                        145
   7801 #define TK_ISNOT                          146
   7802 #define TK_END_OF_FILE                    147
   7803 #define TK_ILLEGAL                        148
   7804 #define TK_SPACE                          149
   7805 #define TK_UNCLOSED_STRING                150
   7806 #define TK_FUNCTION                       151
   7807 #define TK_COLUMN                         152
   7808 #define TK_AGG_FUNCTION                   153
   7809 #define TK_AGG_COLUMN                     154
   7810 #define TK_CONST_FUNC                     155
   7811 #define TK_UMINUS                         156
   7812 #define TK_UPLUS                          157
   7813 
   7814 /************** End of parse.h ***********************************************/
   7815 /************** Continuing where we left off in sqliteInt.h ******************/
   7816 #include <stdio.h>
   7817 #include <stdlib.h>
   7818 #include <string.h>
   7819 #include <assert.h>
   7820 #include <stddef.h>
   7821 
   7822 /*
   7823 ** If compiling for a processor that lacks floating point support,
   7824 ** substitute integer for floating-point
   7825 */
   7826 #ifdef SQLITE_OMIT_FLOATING_POINT
   7827 # define double sqlite_int64
   7828 # define float sqlite_int64
   7829 # define LONGDOUBLE_TYPE sqlite_int64
   7830 # ifndef SQLITE_BIG_DBL
   7831 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   7832 # endif
   7833 # define SQLITE_OMIT_DATETIME_FUNCS 1
   7834 # define SQLITE_OMIT_TRACE 1
   7835 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   7836 # undef SQLITE_HAVE_ISNAN
   7837 #endif
   7838 #ifndef SQLITE_BIG_DBL
   7839 # define SQLITE_BIG_DBL (1e99)
   7840 #endif
   7841 
   7842 /*
   7843 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   7844 ** afterward. Having this macro allows us to cause the C compiler
   7845 ** to omit code used by TEMP tables without messy #ifndef statements.
   7846 */
   7847 #ifdef SQLITE_OMIT_TEMPDB
   7848 #define OMIT_TEMPDB 1
   7849 #else
   7850 #define OMIT_TEMPDB 0
   7851 #endif
   7852 
   7853 /*
   7854 ** The "file format" number is an integer that is incremented whenever
   7855 ** the VDBE-level file format changes.  The following macros define the
   7856 ** the default file format for new databases and the maximum file format
   7857 ** that the library can read.
   7858 */
   7859 #define SQLITE_MAX_FILE_FORMAT 4
   7860 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   7861 # define SQLITE_DEFAULT_FILE_FORMAT 4
   7862 #endif
   7863 
   7864 /*
   7865 ** Determine whether triggers are recursive by default.  This can be
   7866 ** changed at run-time using a pragma.
   7867 */
   7868 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   7869 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   7870 #endif
   7871 
   7872 /*
   7873 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   7874 ** on the command-line
   7875 */
   7876 #ifndef SQLITE_TEMP_STORE
   7877 # define SQLITE_TEMP_STORE 1
   7878 #endif
   7879 
   7880 /*
   7881 ** GCC does not define the offsetof() macro so we'll have to do it
   7882 ** ourselves.
   7883 */
   7884 #ifndef offsetof
   7885 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   7886 #endif
   7887 
   7888 /*
   7889 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   7890 ** not, there are still machines out there that use EBCDIC.)
   7891 */
   7892 #if 'A' == '\301'
   7893 # define SQLITE_EBCDIC 1
   7894 #else
   7895 # define SQLITE_ASCII 1
   7896 #endif
   7897 
   7898 /*
   7899 ** Integers of known sizes.  These typedefs might change for architectures
   7900 ** where the sizes very.  Preprocessor macros are available so that the
   7901 ** types can be conveniently redefined at compile-type.  Like this:
   7902 **
   7903 **         cc '-DUINTPTR_TYPE=long long int' ...
   7904 */
   7905 #ifndef UINT32_TYPE
   7906 # ifdef HAVE_UINT32_T
   7907 #  define UINT32_TYPE uint32_t
   7908 # else
   7909 #  define UINT32_TYPE unsigned int
   7910 # endif
   7911 #endif
   7912 #ifndef UINT16_TYPE
   7913 # ifdef HAVE_UINT16_T
   7914 #  define UINT16_TYPE uint16_t
   7915 # else
   7916 #  define UINT16_TYPE unsigned short int
   7917 # endif
   7918 #endif
   7919 #ifndef INT16_TYPE
   7920 # ifdef HAVE_INT16_T
   7921 #  define INT16_TYPE int16_t
   7922 # else
   7923 #  define INT16_TYPE short int
   7924 # endif
   7925 #endif
   7926 #ifndef UINT8_TYPE
   7927 # ifdef HAVE_UINT8_T
   7928 #  define UINT8_TYPE uint8_t
   7929 # else
   7930 #  define UINT8_TYPE unsigned char
   7931 # endif
   7932 #endif
   7933 #ifndef INT8_TYPE
   7934 # ifdef HAVE_INT8_T
   7935 #  define INT8_TYPE int8_t
   7936 # else
   7937 #  define INT8_TYPE signed char
   7938 # endif
   7939 #endif
   7940 #ifndef LONGDOUBLE_TYPE
   7941 # define LONGDOUBLE_TYPE long double
   7942 #endif
   7943 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   7944 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   7945 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   7946 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   7947 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   7948 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   7949 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   7950 
   7951 /*
   7952 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   7953 ** that can be stored in a u32 without loss of data.  The value
   7954 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   7955 ** have to specify the value in the less intuitive manner shown:
   7956 */
   7957 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   7958 
   7959 /*
   7960 ** The datatype used to store estimates of the number of rows in a
   7961 ** table or index.  This is an unsigned integer type.  For 99.9% of
   7962 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
   7963 ** can be used at compile-time if desired.
   7964 */
   7965 #ifdef SQLITE_64BIT_STATS
   7966  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
   7967 #else
   7968  typedef u32 tRowcnt;    /* 32-bit is the default */
   7969 #endif
   7970 
   7971 /*
   7972 ** Macros to determine whether the machine is big or little endian,
   7973 ** evaluated at runtime.
   7974 */
   7975 #ifdef SQLITE_AMALGAMATION
   7976 SQLITE_PRIVATE const int sqlite3one = 1;
   7977 #else
   7978 SQLITE_PRIVATE const int sqlite3one;
   7979 #endif
   7980 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
   7981                              || defined(__x86_64) || defined(__x86_64__)
   7982 # define SQLITE_BIGENDIAN    0
   7983 # define SQLITE_LITTLEENDIAN 1
   7984 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   7985 #else
   7986 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   7987 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   7988 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   7989 #endif
   7990 
   7991 /*
   7992 ** Constants for the largest and smallest possible 64-bit signed integers.
   7993 ** These macros are designed to work correctly on both 32-bit and 64-bit
   7994 ** compilers.
   7995 */
   7996 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   7997 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   7998 
   7999 /*
   8000 ** Round up a number to the next larger multiple of 8.  This is used
   8001 ** to force 8-byte alignment on 64-bit architectures.
   8002 */
   8003 #define ROUND8(x)     (((x)+7)&~7)
   8004 
   8005 /*
   8006 ** Round down to the nearest multiple of 8
   8007 */
   8008 #define ROUNDDOWN8(x) ((x)&~7)
   8009 
   8010 /*
   8011 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   8012 ** macro is used only within assert() to verify that the code gets
   8013 ** all alignment restrictions correct.
   8014 **
   8015 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   8016 ** underlying malloc() implemention might return us 4-byte aligned
   8017 ** pointers.  In that case, only verify 4-byte alignment.
   8018 */
   8019 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   8020 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   8021 #else
   8022 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   8023 #endif
   8024 
   8025 
   8026 /*
   8027 ** An instance of the following structure is used to store the busy-handler
   8028 ** callback for a given sqlite handle.
   8029 **
   8030 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   8031 ** callback for the database handle. Each pager opened via the sqlite
   8032 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   8033 ** callback is currently invoked only from within pager.c.
   8034 */
   8035 typedef struct BusyHandler BusyHandler;
   8036 struct BusyHandler {
   8037   int (*xFunc)(void *,int);  /* The busy callback */
   8038   void *pArg;                /* First arg to busy callback */
   8039   int nBusy;                 /* Incremented with each busy call */
   8040 };
   8041 
   8042 /*
   8043 ** Name of the master database table.  The master database table
   8044 ** is a special table that holds the names and attributes of all
   8045 ** user tables and indices.
   8046 */
   8047 #define MASTER_NAME       "sqlite_master"
   8048 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   8049 
   8050 /*
   8051 ** The root-page of the master database table.
   8052 */
   8053 #define MASTER_ROOT       1
   8054 
   8055 /*
   8056 ** The name of the schema table.
   8057 */
   8058 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   8059 
   8060 /*
   8061 ** A convenience macro that returns the number of elements in
   8062 ** an array.
   8063 */
   8064 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   8065 
   8066 /*
   8067 ** The following value as a destructor means to use sqlite3DbFree().
   8068 ** The sqlite3DbFree() routine requires two parameters instead of the
   8069 ** one parameter that destructors normally want.  So we have to introduce
   8070 ** this magic value that the code knows to handle differently.  Any
   8071 ** pointer will work here as long as it is distinct from SQLITE_STATIC
   8072 ** and SQLITE_TRANSIENT.
   8073 */
   8074 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
   8075 
   8076 /*
   8077 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   8078 ** not support Writable Static Data (WSD) such as global and static variables.
   8079 ** All variables must either be on the stack or dynamically allocated from
   8080 ** the heap.  When WSD is unsupported, the variable declarations scattered
   8081 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   8082 ** macro is used for this purpose.  And instead of referencing the variable
   8083 ** directly, we use its constant as a key to lookup the run-time allocated
   8084 ** buffer that holds real variable.  The constant is also the initializer
   8085 ** for the run-time allocated buffer.
   8086 **
   8087 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   8088 ** macros become no-ops and have zero performance impact.
   8089 */
   8090 #ifdef SQLITE_OMIT_WSD
   8091   #define SQLITE_WSD const
   8092   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   8093   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   8094 SQLITE_API   int sqlite3_wsd_init(int N, int J);
   8095 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
   8096 #else
   8097   #define SQLITE_WSD
   8098   #define GLOBAL(t,v) v
   8099   #define sqlite3GlobalConfig sqlite3Config
   8100 #endif
   8101 
   8102 /*
   8103 ** The following macros are used to suppress compiler warnings and to
   8104 ** make it clear to human readers when a function parameter is deliberately
   8105 ** left unused within the body of a function. This usually happens when
   8106 ** a function is called via a function pointer. For example the
   8107 ** implementation of an SQL aggregate step callback may not use the
   8108 ** parameter indicating the number of arguments passed to the aggregate,
   8109 ** if it knows that this is enforced elsewhere.
   8110 **
   8111 ** When a function parameter is not used at all within the body of a function,
   8112 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   8113 ** However, these macros may also be used to suppress warnings related to
   8114 ** parameters that may or may not be used depending on compilation options.
   8115 ** For example those parameters only used in assert() statements. In these
   8116 ** cases the parameters are named as per the usual conventions.
   8117 */
   8118 #define UNUSED_PARAMETER(x) (void)(x)
   8119 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   8120 
   8121 /*
   8122 ** Forward references to structures
   8123 */
   8124 typedef struct AggInfo AggInfo;
   8125 typedef struct AuthContext AuthContext;
   8126 typedef struct AutoincInfo AutoincInfo;
   8127 typedef struct Bitvec Bitvec;
   8128 typedef struct CollSeq CollSeq;
   8129 typedef struct Column Column;
   8130 typedef struct Db Db;
   8131 typedef struct Schema Schema;
   8132 typedef struct Expr Expr;
   8133 typedef struct ExprList ExprList;
   8134 typedef struct ExprSpan ExprSpan;
   8135 typedef struct FKey FKey;
   8136 typedef struct FuncDestructor FuncDestructor;
   8137 typedef struct FuncDef FuncDef;
   8138 typedef struct FuncDefHash FuncDefHash;
   8139 typedef struct IdList IdList;
   8140 typedef struct Index Index;
   8141 typedef struct IndexSample IndexSample;
   8142 typedef struct KeyClass KeyClass;
   8143 typedef struct KeyInfo KeyInfo;
   8144 typedef struct Lookaside Lookaside;
   8145 typedef struct LookasideSlot LookasideSlot;
   8146 typedef struct Module Module;
   8147 typedef struct NameContext NameContext;
   8148 typedef struct Parse Parse;
   8149 typedef struct RowSet RowSet;
   8150 typedef struct Savepoint Savepoint;
   8151 typedef struct Select Select;
   8152 typedef struct SrcList SrcList;
   8153 typedef struct StrAccum StrAccum;
   8154 typedef struct Table Table;
   8155 typedef struct TableLock TableLock;
   8156 typedef struct Token Token;
   8157 typedef struct Trigger Trigger;
   8158 typedef struct TriggerPrg TriggerPrg;
   8159 typedef struct TriggerStep TriggerStep;
   8160 typedef struct UnpackedRecord UnpackedRecord;
   8161 typedef struct VTable VTable;
   8162 typedef struct VtabCtx VtabCtx;
   8163 typedef struct Walker Walker;
   8164 typedef struct WherePlan WherePlan;
   8165 typedef struct WhereInfo WhereInfo;
   8166 typedef struct WhereLevel WhereLevel;
   8167 
   8168 /*
   8169 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   8170 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   8171 ** pointer types (i.e. FuncDef) defined above.
   8172 */
   8173 /************** Include btree.h in the middle of sqliteInt.h *****************/
   8174 /************** Begin file btree.h *******************************************/
   8175 /*
   8176 ** 2001 September 15
   8177 **
   8178 ** The author disclaims copyright to this source code.  In place of
   8179 ** a legal notice, here is a blessing:
   8180 **
   8181 **    May you do good and not evil.
   8182 **    May you find forgiveness for yourself and forgive others.
   8183 **    May you share freely, never taking more than you give.
   8184 **
   8185 *************************************************************************
   8186 ** This header file defines the interface that the sqlite B-Tree file
   8187 ** subsystem.  See comments in the source code for a detailed description
   8188 ** of what each interface routine does.
   8189 */
   8190 #ifndef _BTREE_H_
   8191 #define _BTREE_H_
   8192 
   8193 /* TODO: This definition is just included so other modules compile. It
   8194 ** needs to be revisited.
   8195 */
   8196 #define SQLITE_N_BTREE_META 10
   8197 
   8198 /*
   8199 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   8200 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   8201 */
   8202 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   8203   #define SQLITE_DEFAULT_AUTOVACUUM 0
   8204 #endif
   8205 
   8206 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   8207 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   8208 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   8209 
   8210 /*
   8211 ** Forward declarations of structure
   8212 */
   8213 typedef struct Btree Btree;
   8214 typedef struct BtCursor BtCursor;
   8215 typedef struct BtShared BtShared;
   8216 
   8217 
   8218 SQLITE_PRIVATE int sqlite3BtreeOpen(
   8219   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
   8220   const char *zFilename,   /* Name of database file to open */
   8221   sqlite3 *db,             /* Associated database connection */
   8222   Btree **ppBtree,         /* Return open Btree* here */
   8223   int flags,               /* Flags */
   8224   int vfsFlags             /* Flags passed through to VFS open */
   8225 );
   8226 
   8227 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   8228 ** following values.
   8229 **
   8230 ** NOTE:  These values must match the corresponding PAGER_ values in
   8231 ** pager.h.
   8232 */
   8233 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
   8234 #define BTREE_MEMORY        2  /* This is an in-memory DB */
   8235 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
   8236 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
   8237 
   8238 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   8239 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   8240 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
   8241 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
   8242 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   8243 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   8244 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   8245 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
   8246 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
   8247 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
   8248 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   8249 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   8250 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   8251 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   8252 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
   8253 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   8254 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
   8255 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   8256 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   8257 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   8258 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   8259 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   8260 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   8261 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   8262 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   8263 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   8264 
   8265 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   8266 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   8267 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   8268 
   8269 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   8270 
   8271 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   8272 ** of the flags shown below.
   8273 **
   8274 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
   8275 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
   8276 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
   8277 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
   8278 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
   8279 ** indices.)
   8280 */
   8281 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   8282 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
   8283 
   8284 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   8285 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   8286 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
   8287 
   8288 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   8289 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   8290 
   8291 /*
   8292 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   8293 ** should be one of the following values. The integer values are assigned
   8294 ** to constants so that the offset of the corresponding field in an
   8295 ** SQLite database header may be found using the following formula:
   8296 **
   8297 **   offset = 36 + (idx * 4)
   8298 **
   8299 ** For example, the free-page-count field is located at byte offset 36 of
   8300 ** the database file header. The incr-vacuum-flag field is located at
   8301 ** byte offset 64 (== 36+4*7).
   8302 */
   8303 #define BTREE_FREE_PAGE_COUNT     0
   8304 #define BTREE_SCHEMA_VERSION      1
   8305 #define BTREE_FILE_FORMAT         2
   8306 #define BTREE_DEFAULT_CACHE_SIZE  3
   8307 #define BTREE_LARGEST_ROOT_PAGE   4
   8308 #define BTREE_TEXT_ENCODING       5
   8309 #define BTREE_USER_VERSION        6
   8310 #define BTREE_INCR_VACUUM         7
   8311 
   8312 SQLITE_PRIVATE int sqlite3BtreeCursor(
   8313   Btree*,                              /* BTree containing table to open */
   8314   int iTable,                          /* Index of root page */
   8315   int wrFlag,                          /* 1 for writing.  0 for read-only */
   8316   struct KeyInfo*,                     /* First argument to compare function */
   8317   BtCursor *pCursor                    /* Space to write cursor structure */
   8318 );
   8319 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   8320 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   8321 
   8322 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   8323 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   8324   BtCursor*,
   8325   UnpackedRecord *pUnKey,
   8326   i64 intKey,
   8327   int bias,
   8328   int *pRes
   8329 );
   8330 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
   8331 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
   8332 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
   8333                                   const void *pData, int nData,
   8334                                   int nZero, int bias, int seekResult);
   8335 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   8336 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   8337 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
   8338 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   8339 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
   8340 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   8341 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   8342 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
   8343 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
   8344 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   8345 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   8346 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
   8347 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
   8348 
   8349 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   8350 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   8351 
   8352 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   8353 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
   8354 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   8355 
   8356 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
   8357 
   8358 #ifndef NDEBUG
   8359 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   8360 #endif
   8361 
   8362 #ifndef SQLITE_OMIT_BTREECOUNT
   8363 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   8364 #endif
   8365 
   8366 #ifdef SQLITE_TEST
   8367 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   8368 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   8369 #endif
   8370 
   8371 #ifndef SQLITE_OMIT_WAL
   8372 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
   8373 #endif
   8374 
   8375 /*
   8376 ** If we are not using shared cache, then there is no need to
   8377 ** use mutexes to access the BtShared structures.  So make the
   8378 ** Enter and Leave procedures no-ops.
   8379 */
   8380 #ifndef SQLITE_OMIT_SHARED_CACHE
   8381 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   8382 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   8383 #else
   8384 # define sqlite3BtreeEnter(X)
   8385 # define sqlite3BtreeEnterAll(X)
   8386 #endif
   8387 
   8388 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   8389 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
   8390 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   8391 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   8392 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   8393 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   8394 #ifndef NDEBUG
   8395   /* These routines are used inside assert() statements only. */
   8396 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   8397 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   8398 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
   8399 #endif
   8400 #else
   8401 
   8402 # define sqlite3BtreeSharable(X) 0
   8403 # define sqlite3BtreeLeave(X)
   8404 # define sqlite3BtreeEnterCursor(X)
   8405 # define sqlite3BtreeLeaveCursor(X)
   8406 # define sqlite3BtreeLeaveAll(X)
   8407 
   8408 # define sqlite3BtreeHoldsMutex(X) 1
   8409 # define sqlite3BtreeHoldsAllMutexes(X) 1
   8410 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
   8411 #endif
   8412 
   8413 
   8414 #endif /* _BTREE_H_ */
   8415 
   8416 /************** End of btree.h ***********************************************/
   8417 /************** Continuing where we left off in sqliteInt.h ******************/
   8418 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   8419 /************** Begin file vdbe.h ********************************************/
   8420 /*
   8421 ** 2001 September 15
   8422 **
   8423 ** The author disclaims copyright to this source code.  In place of
   8424 ** a legal notice, here is a blessing:
   8425 **
   8426 **    May you do good and not evil.
   8427 **    May you find forgiveness for yourself and forgive others.
   8428 **    May you share freely, never taking more than you give.
   8429 **
   8430 *************************************************************************
   8431 ** Header file for the Virtual DataBase Engine (VDBE)
   8432 **
   8433 ** This header defines the interface to the virtual database engine
   8434 ** or VDBE.  The VDBE implements an abstract machine that runs a
   8435 ** simple program to access and modify the underlying database.
   8436 */
   8437 #ifndef _SQLITE_VDBE_H_
   8438 #define _SQLITE_VDBE_H_
   8439 /* #include <stdio.h> */
   8440 
   8441 /*
   8442 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   8443 ** in the source file sqliteVdbe.c are allowed to see the insides
   8444 ** of this structure.
   8445 */
   8446 typedef struct Vdbe Vdbe;
   8447 
   8448 /*
   8449 ** The names of the following types declared in vdbeInt.h are required
   8450 ** for the VdbeOp definition.
   8451 */
   8452 typedef struct VdbeFunc VdbeFunc;
   8453 typedef struct Mem Mem;
   8454 typedef struct SubProgram SubProgram;
   8455 
   8456 /*
   8457 ** A single instruction of the virtual machine has an opcode
   8458 ** and as many as three operands.  The instruction is recorded
   8459 ** as an instance of the following structure:
   8460 */
   8461 struct VdbeOp {
   8462   u8 opcode;          /* What operation to perform */
   8463   signed char p4type; /* One of the P4_xxx constants for p4 */
   8464   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
   8465   u8 p5;              /* Fifth parameter is an unsigned character */
   8466   int p1;             /* First operand */
   8467   int p2;             /* Second parameter (often the jump destination) */
   8468   int p3;             /* The third parameter */
   8469   union {             /* fourth parameter */
   8470     int i;                 /* Integer value if p4type==P4_INT32 */
   8471     void *p;               /* Generic pointer */
   8472     char *z;               /* Pointer to data for string (char array) types */
   8473     i64 *pI64;             /* Used when p4type is P4_INT64 */
   8474     double *pReal;         /* Used when p4type is P4_REAL */
   8475     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   8476     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
   8477     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   8478     Mem *pMem;             /* Used when p4type is P4_MEM */
   8479     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   8480     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   8481     int *ai;               /* Used when p4type is P4_INTARRAY */
   8482     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   8483     int (*xAdvance)(BtCursor *, int *);
   8484   } p4;
   8485 #ifdef SQLITE_DEBUG
   8486   char *zComment;          /* Comment to improve readability */
   8487 #endif
   8488 #ifdef VDBE_PROFILE
   8489   int cnt;                 /* Number of times this instruction was executed */
   8490   u64 cycles;              /* Total time spent executing this instruction */
   8491 #endif
   8492 };
   8493 typedef struct VdbeOp VdbeOp;
   8494 
   8495 
   8496 /*
   8497 ** A sub-routine used to implement a trigger program.
   8498 */
   8499 struct SubProgram {
   8500   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   8501   int nOp;                      /* Elements in aOp[] */
   8502   int nMem;                     /* Number of memory cells required */
   8503   int nCsr;                     /* Number of cursors required */
   8504   int nOnce;                    /* Number of OP_Once instructions */
   8505   void *token;                  /* id that may be used to recursive triggers */
   8506   SubProgram *pNext;            /* Next sub-program already visited */
   8507 };
   8508 
   8509 /*
   8510 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   8511 ** it takes up less space.
   8512 */
   8513 struct VdbeOpList {
   8514   u8 opcode;          /* What operation to perform */
   8515   signed char p1;     /* First operand */
   8516   signed char p2;     /* Second parameter (often the jump destination) */
   8517   signed char p3;     /* Third parameter */
   8518 };
   8519 typedef struct VdbeOpList VdbeOpList;
   8520 
   8521 /*
   8522 ** Allowed values of VdbeOp.p4type
   8523 */
   8524 #define P4_NOTUSED    0   /* The P4 parameter is not used */
   8525 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
   8526 #define P4_STATIC   (-2)  /* Pointer to a static string */
   8527 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
   8528 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
   8529 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
   8530 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
   8531 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
   8532 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
   8533 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   8534 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   8535 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   8536 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   8537 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   8538 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
   8539 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   8540 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
   8541 
   8542 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
   8543 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
   8544 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
   8545 ** gets freed when the Vdbe is finalized so it still should be obtained
   8546 ** from a single sqliteMalloc().  But no copy is made and the calling
   8547 ** function should *not* try to free the KeyInfo.
   8548 */
   8549 #define P4_KEYINFO_HANDOFF (-16)
   8550 #define P4_KEYINFO_STATIC  (-17)
   8551 
   8552 /*
   8553 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   8554 ** number of columns of data returned by the statement.
   8555 */
   8556 #define COLNAME_NAME     0
   8557 #define COLNAME_DECLTYPE 1
   8558 #define COLNAME_DATABASE 2
   8559 #define COLNAME_TABLE    3
   8560 #define COLNAME_COLUMN   4
   8561 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   8562 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   8563 #else
   8564 # ifdef SQLITE_OMIT_DECLTYPE
   8565 #   define COLNAME_N      1      /* Store only the name */
   8566 # else
   8567 #   define COLNAME_N      2      /* Store the name and decltype */
   8568 # endif
   8569 #endif
   8570 
   8571 /*
   8572 ** The following macro converts a relative address in the p2 field
   8573 ** of a VdbeOp structure into a negative number so that
   8574 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   8575 ** the macro again restores the address.
   8576 */
   8577 #define ADDR(X)  (-1-(X))
   8578 
   8579 /*
   8580 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   8581 ** header file that defines a number for each opcode used by the VDBE.
   8582 */
   8583 /************** Include opcodes.h in the middle of vdbe.h ********************/
   8584 /************** Begin file opcodes.h *****************************************/
   8585 /* Automatically generated.  Do not edit */
   8586 /* See the mkopcodeh.awk script for details */
   8587 #define OP_Goto                                 1
   8588 #define OP_Gosub                                2
   8589 #define OP_Return                               3
   8590 #define OP_Yield                                4
   8591 #define OP_HaltIfNull                           5
   8592 #define OP_Halt                                 6
   8593 #define OP_Integer                              7
   8594 #define OP_Int64                                8
   8595 #define OP_Real                               130   /* same as TK_FLOAT    */
   8596 #define OP_String8                             94   /* same as TK_STRING   */
   8597 #define OP_String                               9
   8598 #define OP_Null                                10
   8599 #define OP_Blob                                11
   8600 #define OP_Variable                            12
   8601 #define OP_Move                                13
   8602 #define OP_Copy                                14
   8603 #define OP_SCopy                               15
   8604 #define OP_ResultRow                           16
   8605 #define OP_Concat                              91   /* same as TK_CONCAT   */
   8606 #define OP_Add                                 86   /* same as TK_PLUS     */
   8607 #define OP_Subtract                            87   /* same as TK_MINUS    */
   8608 #define OP_Multiply                            88   /* same as TK_STAR     */
   8609 #define OP_Divide                              89   /* same as TK_SLASH    */
   8610 #define OP_Remainder                           90   /* same as TK_REM      */
   8611 #define OP_CollSeq                             17
   8612 #define OP_Function                            18
   8613 #define OP_BitAnd                              82   /* same as TK_BITAND   */
   8614 #define OP_BitOr                               83   /* same as TK_BITOR    */
   8615 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
   8616 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
   8617 #define OP_AddImm                              20
   8618 #define OP_MustBeInt                           21
   8619 #define OP_RealAffinity                        22
   8620 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
   8621 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
   8622 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
   8623 #define OP_ToInt                              144   /* same as TK_TO_INT   */
   8624 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
   8625 #define OP_Eq                                  76   /* same as TK_EQ       */
   8626 #define OP_Ne                                  75   /* same as TK_NE       */
   8627 #define OP_Lt                                  79   /* same as TK_LT       */
   8628 #define OP_Le                                  78   /* same as TK_LE       */
   8629 #define OP_Gt                                  77   /* same as TK_GT       */
   8630 #define OP_Ge                                  80   /* same as TK_GE       */
   8631 #define OP_Permutation                         23
   8632 #define OP_Compare                             24
   8633 #define OP_Jump                                25
   8634 #define OP_And                                 69   /* same as TK_AND      */
   8635 #define OP_Or                                  68   /* same as TK_OR       */
   8636 #define OP_Not                                 19   /* same as TK_NOT      */
   8637 #define OP_BitNot                              93   /* same as TK_BITNOT   */
   8638 #define OP_Once                                26
   8639 #define OP_If                                  27
   8640 #define OP_IfNot                               28
   8641 #define OP_IsNull                              73   /* same as TK_ISNULL   */
   8642 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
   8643 #define OP_Column                              29
   8644 #define OP_Affinity                            30
   8645 #define OP_MakeRecord                          31
   8646 #define OP_Count                               32
   8647 #define OP_Savepoint                           33
   8648 #define OP_AutoCommit                          34
   8649 #define OP_Transaction                         35
   8650 #define OP_ReadCookie                          36
   8651 #define OP_SetCookie                           37
   8652 #define OP_VerifyCookie                        38
   8653 #define OP_OpenRead                            39
   8654 #define OP_OpenWrite                           40
   8655 #define OP_OpenAutoindex                       41
   8656 #define OP_OpenEphemeral                       42
   8657 #define OP_SorterOpen                          43
   8658 #define OP_OpenPseudo                          44
   8659 #define OP_Close                               45
   8660 #define OP_SeekLt                              46
   8661 #define OP_SeekLe                              47
   8662 #define OP_SeekGe                              48
   8663 #define OP_SeekGt                              49
   8664 #define OP_Seek                                50
   8665 #define OP_NotFound                            51
   8666 #define OP_Found                               52
   8667 #define OP_IsUnique                            53
   8668 #define OP_NotExists                           54
   8669 #define OP_Sequence                            55
   8670 #define OP_NewRowid                            56
   8671 #define OP_Insert                              57
   8672 #define OP_InsertInt                           58
   8673 #define OP_Delete                              59
   8674 #define OP_ResetCount                          60
   8675 #define OP_SorterCompare                       61
   8676 #define OP_SorterData                          62
   8677 #define OP_RowKey                              63
   8678 #define OP_RowData                             64
   8679 #define OP_Rowid                               65
   8680 #define OP_NullRow                             66
   8681 #define OP_Last                                67
   8682 #define OP_SorterSort                          70
   8683 #define OP_Sort                                71
   8684 #define OP_Rewind                              72
   8685 #define OP_SorterNext                          81
   8686 #define OP_Prev                                92
   8687 #define OP_Next                                95
   8688 #define OP_SorterInsert                        96
   8689 #define OP_IdxInsert                           97
   8690 #define OP_IdxDelete                           98
   8691 #define OP_IdxRowid                            99
   8692 #define OP_IdxLT                              100
   8693 #define OP_IdxGE                              101
   8694 #define OP_Destroy                            102
   8695 #define OP_Clear                              103
   8696 #define OP_CreateIndex                        104
   8697 #define OP_CreateTable                        105
   8698 #define OP_ParseSchema                        106
   8699 #define OP_LoadAnalysis                       107
   8700 #define OP_DropTable                          108
   8701 #define OP_DropIndex                          109
   8702 #define OP_DropTrigger                        110
   8703 #define OP_IntegrityCk                        111
   8704 #define OP_RowSetAdd                          112
   8705 #define OP_RowSetRead                         113
   8706 #define OP_RowSetTest                         114
   8707 #define OP_Program                            115
   8708 #define OP_Param                              116
   8709 #define OP_FkCounter                          117
   8710 #define OP_FkIfZero                           118
   8711 #define OP_MemMax                             119
   8712 #define OP_IfPos                              120
   8713 #define OP_IfNeg                              121
   8714 #define OP_IfZero                             122
   8715 #define OP_AggStep                            123
   8716 #define OP_AggFinal                           124
   8717 #define OP_Checkpoint                         125
   8718 #define OP_JournalMode                        126
   8719 #define OP_Vacuum                             127
   8720 #define OP_IncrVacuum                         128
   8721 #define OP_Expire                             129
   8722 #define OP_TableLock                          131
   8723 #define OP_VBegin                             132
   8724 #define OP_VCreate                            133
   8725 #define OP_VDestroy                           134
   8726 #define OP_VOpen                              135
   8727 #define OP_VFilter                            136
   8728 #define OP_VColumn                            137
   8729 #define OP_VNext                              138
   8730 #define OP_VRename                            139
   8731 #define OP_VUpdate                            140
   8732 #define OP_Pagecount                          146
   8733 #define OP_MaxPgcnt                           147
   8734 #define OP_Trace                              148
   8735 #define OP_Noop                               149
   8736 #define OP_Explain                            150
   8737 
   8738 
   8739 /* Properties such as "out2" or "jump" that are specified in
   8740 ** comments following the "case" for each opcode in the vdbe.c
   8741 ** are encoded into bitvectors as follows:
   8742 */
   8743 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
   8744 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
   8745 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
   8746 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
   8747 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
   8748 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
   8749 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
   8750 #define OPFLG_INITIALIZER {\
   8751 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
   8752 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
   8753 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
   8754 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
   8755 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
   8756 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
   8757 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
   8758 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   8759 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
   8760 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
   8761 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
   8762 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
   8763 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
   8764 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   8765 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
   8766 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
   8767 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
   8768 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
   8769 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
   8770 
   8771 /************** End of opcodes.h *********************************************/
   8772 /************** Continuing where we left off in vdbe.h ***********************/
   8773 
   8774 /*
   8775 ** Prototypes for the VDBE interface.  See comments on the implementation
   8776 ** for a description of what each of these routines does.
   8777 */
   8778 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
   8779 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   8780 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   8781 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   8782 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   8783 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   8784 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   8785 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
   8786 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
   8787 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
   8788 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
   8789 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
   8790 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   8791 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   8792 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
   8793 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   8794 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   8795 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   8796 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   8797 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   8798 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   8799 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
   8800 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
   8801 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   8802 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   8803 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   8804 #ifdef SQLITE_DEBUG
   8805 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   8806 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
   8807 #endif
   8808 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   8809 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
   8810 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   8811 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   8812 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   8813 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   8814 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   8815 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   8816 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   8817 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   8818 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
   8819 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   8820 #ifndef SQLITE_OMIT_TRACE
   8821 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   8822 #endif
   8823 
   8824 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
   8825 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
   8826 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
   8827 
   8828 #ifndef SQLITE_OMIT_TRIGGER
   8829 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
   8830 #endif
   8831 
   8832 
   8833 #ifndef NDEBUG
   8834 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   8835 # define VdbeComment(X)  sqlite3VdbeComment X
   8836 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   8837 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   8838 #else
   8839 # define VdbeComment(X)
   8840 # define VdbeNoopComment(X)
   8841 #endif
   8842 
   8843 #endif
   8844 
   8845 /************** End of vdbe.h ************************************************/
   8846 /************** Continuing where we left off in sqliteInt.h ******************/
   8847 /************** Include pager.h in the middle of sqliteInt.h *****************/
   8848 /************** Begin file pager.h *******************************************/
   8849 /*
   8850 ** 2001 September 15
   8851 **
   8852 ** The author disclaims copyright to this source code.  In place of
   8853 ** a legal notice, here is a blessing:
   8854 **
   8855 **    May you do good and not evil.
   8856 **    May you find forgiveness for yourself and forgive others.
   8857 **    May you share freely, never taking more than you give.
   8858 **
   8859 *************************************************************************
   8860 ** This header file defines the interface that the sqlite page cache
   8861 ** subsystem.  The page cache subsystem reads and writes a file a page
   8862 ** at a time and provides a journal for rollback.
   8863 */
   8864 
   8865 #ifndef _PAGER_H_
   8866 #define _PAGER_H_
   8867 
   8868 /*
   8869 ** Default maximum size for persistent journal files. A negative
   8870 ** value means no limit. This value may be overridden using the
   8871 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   8872 */
   8873 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   8874   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   8875 #endif
   8876 
   8877 /*
   8878 ** The type used to represent a page number.  The first page in a file
   8879 ** is called page 1.  0 is used to represent "not a page".
   8880 */
   8881 typedef u32 Pgno;
   8882 
   8883 /*
   8884 ** Each open file is managed by a separate instance of the "Pager" structure.
   8885 */
   8886 typedef struct Pager Pager;
   8887 
   8888 /*
   8889 ** Handle type for pages.
   8890 */
   8891 typedef struct PgHdr DbPage;
   8892 
   8893 /*
   8894 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   8895 ** reserved for working around a windows/posix incompatibility). It is
   8896 ** used in the journal to signify that the remainder of the journal file
   8897 ** is devoted to storing a master journal name - there are no more pages to
   8898 ** roll back. See comments for function writeMasterJournal() in pager.c
   8899 ** for details.
   8900 */
   8901 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   8902 
   8903 /*
   8904 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   8905 **
   8906 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   8907 */
   8908 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   8909 #define PAGER_MEMORY        0x0002    /* In-memory database */
   8910 
   8911 /*
   8912 ** Valid values for the second argument to sqlite3PagerLockingMode().
   8913 */
   8914 #define PAGER_LOCKINGMODE_QUERY      -1
   8915 #define PAGER_LOCKINGMODE_NORMAL      0
   8916 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   8917 
   8918 /*
   8919 ** Numeric constants that encode the journalmode.
   8920 */
   8921 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
   8922 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   8923 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   8924 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   8925 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   8926 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   8927 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
   8928 
   8929 /*
   8930 ** The remainder of this file contains the declarations of the functions
   8931 ** that make up the Pager sub-system API. See source code comments for
   8932 ** a detailed description of each routine.
   8933 */
   8934 
   8935 /* Open and close a Pager connection. */
   8936 SQLITE_PRIVATE int sqlite3PagerOpen(
   8937   sqlite3_vfs*,
   8938   Pager **ppPager,
   8939   const char*,
   8940   int,
   8941   int,
   8942   int,
   8943   void(*)(DbPage*)
   8944 );
   8945 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
   8946 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   8947 
   8948 /* Functions used to configure a Pager object. */
   8949 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   8950 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
   8951 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   8952 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   8953 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
   8954 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
   8955 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   8956 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
   8957 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
   8958 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
   8959 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   8960 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   8961 
   8962 /* Functions used to obtain and release page references. */
   8963 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   8964 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
   8965 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   8966 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   8967 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   8968 
   8969 /* Operations on page references. */
   8970 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   8971 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   8972 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   8973 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   8974 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   8975 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   8976 
   8977 /* Functions used to manage pager transactions and savepoints. */
   8978 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
   8979 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   8980 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   8981 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
   8982 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
   8983 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   8984 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   8985 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   8986 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   8987 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   8988 
   8989 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
   8990 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
   8991 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
   8992 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
   8993 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
   8994 #ifdef SQLITE_ENABLE_ZIPVFS
   8995 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
   8996 #endif
   8997 
   8998 /* Functions used to query pager state and configuration. */
   8999 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   9000 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
   9001 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
   9002 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
   9003 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
   9004 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   9005 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   9006 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
   9007 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   9008 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   9009 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
   9010 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
   9011 
   9012 /* Functions used to truncate the database file. */
   9013 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   9014 
   9015 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
   9016 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
   9017 #endif
   9018 
   9019 /* Functions to support testing and debugging. */
   9020 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   9021 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   9022 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   9023 #endif
   9024 #ifdef SQLITE_TEST
   9025 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   9026 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   9027   void disable_simulated_io_errors(void);
   9028   void enable_simulated_io_errors(void);
   9029 #else
   9030 # define disable_simulated_io_errors()
   9031 # define enable_simulated_io_errors()
   9032 #endif
   9033 
   9034 #endif /* _PAGER_H_ */
   9035 
   9036 /************** End of pager.h ***********************************************/
   9037 /************** Continuing where we left off in sqliteInt.h ******************/
   9038 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   9039 /************** Begin file pcache.h ******************************************/
   9040 /*
   9041 ** 2008 August 05
   9042 **
   9043 ** The author disclaims copyright to this source code.  In place of
   9044 ** a legal notice, here is a blessing:
   9045 **
   9046 **    May you do good and not evil.
   9047 **    May you find forgiveness for yourself and forgive others.
   9048 **    May you share freely, never taking more than you give.
   9049 **
   9050 *************************************************************************
   9051 ** This header file defines the interface that the sqlite page cache
   9052 ** subsystem.
   9053 */
   9054 
   9055 #ifndef _PCACHE_H_
   9056 
   9057 typedef struct PgHdr PgHdr;
   9058 typedef struct PCache PCache;
   9059 
   9060 /*
   9061 ** Every page in the cache is controlled by an instance of the following
   9062 ** structure.
   9063 */
   9064 struct PgHdr {
   9065   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
   9066   void *pData;                   /* Page data */
   9067   void *pExtra;                  /* Extra content */
   9068   PgHdr *pDirty;                 /* Transient list of dirty pages */
   9069   Pager *pPager;                 /* The pager this page is part of */
   9070   Pgno pgno;                     /* Page number for this page */
   9071 #ifdef SQLITE_CHECK_PAGES
   9072   u32 pageHash;                  /* Hash of page content */
   9073 #endif
   9074   u16 flags;                     /* PGHDR flags defined below */
   9075 
   9076   /**********************************************************************
   9077   ** Elements above are public.  All that follows is private to pcache.c
   9078   ** and should not be accessed by other modules.
   9079   */
   9080   i16 nRef;                      /* Number of users of this page */
   9081   PCache *pCache;                /* Cache that owns this page */
   9082 
   9083   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   9084   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   9085 };
   9086 
   9087 /* Bit values for PgHdr.flags */
   9088 #define PGHDR_DIRTY             0x002  /* Page has changed */
   9089 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
   9090                                        ** writing this page to the database */
   9091 #define PGHDR_NEED_READ         0x008  /* Content is unread */
   9092 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
   9093 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
   9094 
   9095 /* Initialize and shutdown the page cache subsystem */
   9096 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   9097 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   9098 
   9099 /* Page cache buffer management:
   9100 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   9101 */
   9102 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   9103 
   9104 /* Create a new pager cache.
   9105 ** Under memory stress, invoke xStress to try to make pages clean.
   9106 ** Only clean and unpinned pages can be reclaimed.
   9107 */
   9108 SQLITE_PRIVATE void sqlite3PcacheOpen(
   9109   int szPage,                    /* Size of every page */
   9110   int szExtra,                   /* Extra space associated with each page */
   9111   int bPurgeable,                /* True if pages are on backing store */
   9112   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   9113   void *pStress,                 /* Argument to xStress */
   9114   PCache *pToInit                /* Preallocated space for the PCache */
   9115 );
   9116 
   9117 /* Modify the page-size after the cache has been created. */
   9118 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
   9119 
   9120 /* Return the size in bytes of a PCache object.  Used to preallocate
   9121 ** storage space.
   9122 */
   9123 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   9124 
   9125 /* One release per successful fetch.  Page is pinned until released.
   9126 ** Reference counted.
   9127 */
   9128 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
   9129 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   9130 
   9131 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   9132 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   9133 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   9134 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   9135 
   9136 /* Change a page number.  Used by incr-vacuum. */
   9137 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   9138 
   9139 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   9140 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   9141 
   9142 /* Get a list of all dirty pages in the cache, sorted by page number */
   9143 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   9144 
   9145 /* Reset and close the cache object */
   9146 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   9147 
   9148 /* Clear flags from pages of the page cache */
   9149 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   9150 
   9151 /* Discard the contents of the cache */
   9152 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   9153 
   9154 /* Return the total number of outstanding page references */
   9155 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   9156 
   9157 /* Increment the reference count of an existing page */
   9158 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   9159 
   9160 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   9161 
   9162 /* Return the total number of pages stored in the cache */
   9163 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   9164 
   9165 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   9166 /* Iterate through all dirty pages currently stored in the cache. This
   9167 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   9168 ** library is built.
   9169 */
   9170 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   9171 #endif
   9172 
   9173 /* Set and get the suggested cache-size for the specified pager-cache.
   9174 **
   9175 ** If no global maximum is configured, then the system attempts to limit
   9176 ** the total number of pages cached by purgeable pager-caches to the sum
   9177 ** of the suggested cache-sizes.
   9178 */
   9179 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   9180 #ifdef SQLITE_TEST
   9181 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   9182 #endif
   9183 
   9184 /* Free up as much memory as possible from the page cache */
   9185 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
   9186 
   9187 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   9188 /* Try to return memory used by the pcache module to the main memory heap */
   9189 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   9190 #endif
   9191 
   9192 #ifdef SQLITE_TEST
   9193 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   9194 #endif
   9195 
   9196 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   9197 
   9198 #endif /* _PCACHE_H_ */
   9199 
   9200 /************** End of pcache.h **********************************************/
   9201 /************** Continuing where we left off in sqliteInt.h ******************/
   9202 
   9203 /************** Include os.h in the middle of sqliteInt.h ********************/
   9204 /************** Begin file os.h **********************************************/
   9205 /*
   9206 ** 2001 September 16
   9207 **
   9208 ** The author disclaims copyright to this source code.  In place of
   9209 ** a legal notice, here is a blessing:
   9210 **
   9211 **    May you do good and not evil.
   9212 **    May you find forgiveness for yourself and forgive others.
   9213 **    May you share freely, never taking more than you give.
   9214 **
   9215 ******************************************************************************
   9216 **
   9217 ** This header file (together with is companion C source-code file
   9218 ** "os.c") attempt to abstract the underlying operating system so that
   9219 ** the SQLite library will work on both POSIX and windows systems.
   9220 **
   9221 ** This header file is #include-ed by sqliteInt.h and thus ends up
   9222 ** being included by every source file.
   9223 */
   9224 #ifndef _SQLITE_OS_H_
   9225 #define _SQLITE_OS_H_
   9226 
   9227 /*
   9228 ** Figure out if we are dealing with Unix, Windows, or some other
   9229 ** operating system.  After the following block of preprocess macros,
   9230 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
   9231 ** will defined to either 1 or 0.  One of the four will be 1.  The other
   9232 ** three will be 0.
   9233 */
   9234 #if defined(SQLITE_OS_OTHER)
   9235 # if SQLITE_OS_OTHER==1
   9236 #   undef SQLITE_OS_UNIX
   9237 #   define SQLITE_OS_UNIX 0
   9238 #   undef SQLITE_OS_WIN
   9239 #   define SQLITE_OS_WIN 0
   9240 #   undef SQLITE_OS_OS2
   9241 #   define SQLITE_OS_OS2 0
   9242 # else
   9243 #   undef SQLITE_OS_OTHER
   9244 # endif
   9245 #endif
   9246 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   9247 # define SQLITE_OS_OTHER 0
   9248 # ifndef SQLITE_OS_WIN
   9249 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
   9250 #     define SQLITE_OS_WIN 1
   9251 #     define SQLITE_OS_UNIX 0
   9252 #     define SQLITE_OS_OS2 0
   9253 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
   9254 #     define SQLITE_OS_WIN 0
   9255 #     define SQLITE_OS_UNIX 0
   9256 #     define SQLITE_OS_OS2 1
   9257 #   else
   9258 #     define SQLITE_OS_WIN 0
   9259 #     define SQLITE_OS_UNIX 1
   9260 #     define SQLITE_OS_OS2 0
   9261 #  endif
   9262 # else
   9263 #  define SQLITE_OS_UNIX 0
   9264 #  define SQLITE_OS_OS2 0
   9265 # endif
   9266 #else
   9267 # ifndef SQLITE_OS_WIN
   9268 #  define SQLITE_OS_WIN 0
   9269 # endif
   9270 #endif
   9271 
   9272 /*
   9273 ** Define the maximum size of a temporary filename
   9274 */
   9275 #if SQLITE_OS_WIN
   9276 # include <windows.h>
   9277 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
   9278 #elif SQLITE_OS_OS2
   9279 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
   9280 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
   9281 # endif
   9282 # define INCL_DOSDATETIME
   9283 # define INCL_DOSFILEMGR
   9284 # define INCL_DOSERRORS
   9285 # define INCL_DOSMISC
   9286 # define INCL_DOSPROCESS
   9287 # define INCL_DOSMODULEMGR
   9288 # define INCL_DOSSEMAPHORES
   9289 # include <os2.h>
   9290 # include <uconv.h>
   9291 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
   9292 #else
   9293 # define SQLITE_TEMPNAME_SIZE 200
   9294 #endif
   9295 
   9296 /*
   9297 ** Determine if we are dealing with Windows NT.
   9298 **
   9299 ** We ought to be able to determine if we are compiling for win98 or winNT
   9300 ** using the _WIN32_WINNT macro as follows:
   9301 **
   9302 ** #if defined(_WIN32_WINNT)
   9303 ** # define SQLITE_OS_WINNT 1
   9304 ** #else
   9305 ** # define SQLITE_OS_WINNT 0
   9306 ** #endif
   9307 **
   9308 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
   9309 ** so the above test does not work.  We'll just assume that everything is
   9310 ** winNT unless the programmer explicitly says otherwise by setting
   9311 ** SQLITE_OS_WINNT to 0.
   9312 */
   9313 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
   9314 # define SQLITE_OS_WINNT 1
   9315 #endif
   9316 
   9317 /*
   9318 ** Determine if we are dealing with WindowsCE - which has a much
   9319 ** reduced API.
   9320 */
   9321 #if defined(_WIN32_WCE)
   9322 # define SQLITE_OS_WINCE 1
   9323 #else
   9324 # define SQLITE_OS_WINCE 0
   9325 #endif
   9326 
   9327 /* If the SET_FULLSYNC macro is not defined above, then make it
   9328 ** a no-op
   9329 */
   9330 #ifndef SET_FULLSYNC
   9331 # define SET_FULLSYNC(x,y)
   9332 #endif
   9333 
   9334 /*
   9335 ** The default size of a disk sector
   9336 */
   9337 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   9338 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
   9339 #endif
   9340 
   9341 /*
   9342 ** Temporary files are named starting with this prefix followed by 16 random
   9343 ** alphanumeric characters, and no file extension. They are stored in the
   9344 ** OS's standard temporary file directory, and are deleted prior to exit.
   9345 ** If sqlite is being embedded in another program, you may wish to change the
   9346 ** prefix to reflect your program's name, so that if your program exits
   9347 ** prematurely, old temporary files can be easily identified. This can be done
   9348 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   9349 **
   9350 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   9351 ** Mcafee started using SQLite in their anti-virus product and it
   9352 ** started putting files with the "sqlite" name in the c:/temp folder.
   9353 ** This annoyed many windows users.  Those users would then do a
   9354 ** Google search for "sqlite", find the telephone numbers of the
   9355 ** developers and call to wake them up at night and complain.
   9356 ** For this reason, the default name prefix is changed to be "sqlite"
   9357 ** spelled backwards.  So the temp files are still identified, but
   9358 ** anybody smart enough to figure out the code is also likely smart
   9359 ** enough to know that calling the developer will not help get rid
   9360 ** of the file.
   9361 */
   9362 #ifndef SQLITE_TEMP_FILE_PREFIX
   9363 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   9364 #endif
   9365 
   9366 /*
   9367 ** The following values may be passed as the second argument to
   9368 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   9369 **
   9370 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   9371 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   9372 **            any time. Other processes may hold and obtain new SHARED locks.
   9373 ** PENDING:   A single process may hold a PENDING lock on a file at
   9374 **            any one time. Existing SHARED locks may persist, but no new
   9375 **            SHARED locks may be obtained by other processes.
   9376 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   9377 **
   9378 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   9379 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   9380 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   9381 ** sqlite3OsLock().
   9382 */
   9383 #define NO_LOCK         0
   9384 #define SHARED_LOCK     1
   9385 #define RESERVED_LOCK   2
   9386 #define PENDING_LOCK    3
   9387 #define EXCLUSIVE_LOCK  4
   9388 
   9389 /*
   9390 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   9391 **
   9392 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   9393 ** those functions are not available.  So we use only LockFile() and
   9394 ** UnlockFile().
   9395 **
   9396 ** LockFile() prevents not just writing but also reading by other processes.
   9397 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   9398 ** byte out of a specific range of bytes. The lock byte is obtained at
   9399 ** random so two separate readers can probably access the file at the
   9400 ** same time, unless they are unlucky and choose the same lock byte.
   9401 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   9402 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   9403 ** a single byte of the file that is designated as the reserved lock byte.
   9404 ** A PENDING_LOCK is obtained by locking a designated byte different from
   9405 ** the RESERVED_LOCK byte.
   9406 **
   9407 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   9408 ** which means we can use reader/writer locks.  When reader/writer locks
   9409 ** are used, the lock is placed on the same range of bytes that is used
   9410 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   9411 ** will support two or more Win95 readers or two or more WinNT readers.
   9412 ** But a single Win95 reader will lock out all WinNT readers and a single
   9413 ** WinNT reader will lock out all other Win95 readers.
   9414 **
   9415 ** The following #defines specify the range of bytes used for locking.
   9416 ** SHARED_SIZE is the number of bytes available in the pool from which
   9417 ** a random byte is selected for a shared lock.  The pool of bytes for
   9418 ** shared locks begins at SHARED_FIRST.
   9419 **
   9420 ** The same locking strategy and
   9421 ** byte ranges are used for Unix.  This leaves open the possiblity of having
   9422 ** clients on win95, winNT, and unix all talking to the same shared file
   9423 ** and all locking correctly.  To do so would require that samba (or whatever
   9424 ** tool is being used for file sharing) implements locks correctly between
   9425 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   9426 ** using the same locking range we are at least open to the possibility.
   9427 **
   9428 ** Locking in windows is manditory.  For this reason, we cannot store
   9429 ** actual data in the bytes used for locking.  The pager never allocates
   9430 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   9431 ** that all locks will fit on a single page even at the minimum page size.
   9432 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   9433 ** is set high so that we don't have to allocate an unused page except
   9434 ** for very large databases.  But one should test the page skipping logic
   9435 ** by setting PENDING_BYTE low and running the entire regression suite.
   9436 **
   9437 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   9438 ** file format.  Depending on how it is changed, you might not notice
   9439 ** the incompatibility right away, even running a full regression test.
   9440 ** The default location of PENDING_BYTE is the first byte past the
   9441 ** 1GB boundary.
   9442 **
   9443 */
   9444 #ifdef SQLITE_OMIT_WSD
   9445 # define PENDING_BYTE     (0x40000000)
   9446 #else
   9447 # define PENDING_BYTE      sqlite3PendingByte
   9448 #endif
   9449 #define RESERVED_BYTE     (PENDING_BYTE+1)
   9450 #define SHARED_FIRST      (PENDING_BYTE+2)
   9451 #define SHARED_SIZE       510
   9452 
   9453 /*
   9454 ** Wrapper around OS specific sqlite3_os_init() function.
   9455 */
   9456 SQLITE_PRIVATE int sqlite3OsInit(void);
   9457 
   9458 /*
   9459 ** Functions for accessing sqlite3_file methods
   9460 */
   9461 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
   9462 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   9463 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   9464 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   9465 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   9466 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   9467 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   9468 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   9469 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   9470 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   9471 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
   9472 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   9473 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   9474 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   9475 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
   9476 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
   9477 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
   9478 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
   9479 
   9480 
   9481 /*
   9482 ** Functions for accessing sqlite3_vfs methods
   9483 */
   9484 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   9485 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   9486 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   9487 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   9488 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   9489 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   9490 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   9491 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   9492 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   9493 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   9494 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   9495 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   9496 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
   9497 
   9498 /*
   9499 ** Convenience functions for opening and closing files using
   9500 ** sqlite3_malloc() to obtain space for the file-handle structure.
   9501 */
   9502 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   9503 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
   9504 
   9505 #endif /* _SQLITE_OS_H_ */
   9506 
   9507 /************** End of os.h **************************************************/
   9508 /************** Continuing where we left off in sqliteInt.h ******************/
   9509 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   9510 /************** Begin file mutex.h *******************************************/
   9511 /*
   9512 ** 2007 August 28
   9513 **
   9514 ** The author disclaims copyright to this source code.  In place of
   9515 ** a legal notice, here is a blessing:
   9516 **
   9517 **    May you do good and not evil.
   9518 **    May you find forgiveness for yourself and forgive others.
   9519 **    May you share freely, never taking more than you give.
   9520 **
   9521 *************************************************************************
   9522 **
   9523 ** This file contains the common header for all mutex implementations.
   9524 ** The sqliteInt.h header #includes this file so that it is available
   9525 ** to all source files.  We break it out in an effort to keep the code
   9526 ** better organized.
   9527 **
   9528 ** NOTE:  source files should *not* #include this header file directly.
   9529 ** Source files should #include the sqliteInt.h file and let that file
   9530 ** include this one indirectly.
   9531 */
   9532 
   9533 
   9534 /*
   9535 ** Figure out what version of the code to use.  The choices are
   9536 **
   9537 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   9538 **                             mutexes implemention cannot be overridden
   9539 **                             at start-time.
   9540 **
   9541 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   9542 **                             mutual exclusion is provided.  But this
   9543 **                             implementation can be overridden at
   9544 **                             start-time.
   9545 **
   9546 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   9547 **
   9548 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   9549 **
   9550 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
   9551 */
   9552 #if !SQLITE_THREADSAFE
   9553 # define SQLITE_MUTEX_OMIT
   9554 #endif
   9555 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   9556 #  if SQLITE_OS_UNIX
   9557 #    define SQLITE_MUTEX_PTHREADS
   9558 #  elif SQLITE_OS_WIN
   9559 #    define SQLITE_MUTEX_W32
   9560 #  elif SQLITE_OS_OS2
   9561 #    define SQLITE_MUTEX_OS2
   9562 #  else
   9563 #    define SQLITE_MUTEX_NOOP
   9564 #  endif
   9565 #endif
   9566 
   9567 #ifdef SQLITE_MUTEX_OMIT
   9568 /*
   9569 ** If this is a no-op implementation, implement everything as macros.
   9570 */
   9571 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   9572 #define sqlite3_mutex_free(X)
   9573 #define sqlite3_mutex_enter(X)
   9574 #define sqlite3_mutex_try(X)      SQLITE_OK
   9575 #define sqlite3_mutex_leave(X)
   9576 #define sqlite3_mutex_held(X)     ((void)(X),1)
   9577 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
   9578 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   9579 #define sqlite3MutexInit()        SQLITE_OK
   9580 #define sqlite3MutexEnd()
   9581 #define MUTEX_LOGIC(X)
   9582 #else
   9583 #define MUTEX_LOGIC(X)            X
   9584 #endif /* defined(SQLITE_MUTEX_OMIT) */
   9585 
   9586 /************** End of mutex.h ***********************************************/
   9587 /************** Continuing where we left off in sqliteInt.h ******************/
   9588 
   9589 
   9590 /*
   9591 ** Each database file to be accessed by the system is an instance
   9592 ** of the following structure.  There are normally two of these structures
   9593 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   9594 ** aDb[1] is the database file used to hold temporary tables.  Additional
   9595 ** databases may be attached.
   9596 */
   9597 struct Db {
   9598   char *zName;         /* Name of this database */
   9599   Btree *pBt;          /* The B*Tree structure for this database file */
   9600   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
   9601   u8 safety_level;     /* How aggressive at syncing data to disk */
   9602   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   9603 };
   9604 
   9605 /*
   9606 ** An instance of the following structure stores a database schema.
   9607 **
   9608 ** Most Schema objects are associated with a Btree.  The exception is
   9609 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
   9610 ** In shared cache mode, a single Schema object can be shared by multiple
   9611 ** Btrees that refer to the same underlying BtShared object.
   9612 **
   9613 ** Schema objects are automatically deallocated when the last Btree that
   9614 ** references them is destroyed.   The TEMP Schema is manually freed by
   9615 ** sqlite3_close().
   9616 *
   9617 ** A thread must be holding a mutex on the corresponding Btree in order
   9618 ** to access Schema content.  This implies that the thread must also be
   9619 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
   9620 ** For a TEMP Schema, only the connection mutex is required.
   9621 */
   9622 struct Schema {
   9623   int schema_cookie;   /* Database schema version number for this file */
   9624   int iGeneration;     /* Generation counter.  Incremented with each change */
   9625   Hash tblHash;        /* All tables indexed by name */
   9626   Hash idxHash;        /* All (named) indices indexed by name */
   9627   Hash trigHash;       /* All triggers indexed by name */
   9628   Hash fkeyHash;       /* All foreign keys by referenced table name */
   9629   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   9630   u8 file_format;      /* Schema format version for this file */
   9631   u8 enc;              /* Text encoding used by this database */
   9632   u16 flags;           /* Flags associated with this schema */
   9633   int cache_size;      /* Number of pages to use in the cache */
   9634 };
   9635 
   9636 /*
   9637 ** These macros can be used to test, set, or clear bits in the
   9638 ** Db.pSchema->flags field.
   9639 */
   9640 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
   9641 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
   9642 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
   9643 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
   9644 
   9645 /*
   9646 ** Allowed values for the DB.pSchema->flags field.
   9647 **
   9648 ** The DB_SchemaLoaded flag is set after the database schema has been
   9649 ** read into internal hash tables.
   9650 **
   9651 ** DB_UnresetViews means that one or more views have column names that
   9652 ** have been filled out.  If the schema changes, these column names might
   9653 ** changes and so the view will need to be reset.
   9654 */
   9655 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   9656 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   9657 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   9658 
   9659 /*
   9660 ** The number of different kinds of things that can be limited
   9661 ** using the sqlite3_limit() interface.
   9662 */
   9663 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
   9664 
   9665 /*
   9666 ** Lookaside malloc is a set of fixed-size buffers that can be used
   9667 ** to satisfy small transient memory allocation requests for objects
   9668 ** associated with a particular database connection.  The use of
   9669 ** lookaside malloc provides a significant performance enhancement
   9670 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   9671 ** SQL statements.
   9672 **
   9673 ** The Lookaside structure holds configuration information about the
   9674 ** lookaside malloc subsystem.  Each available memory allocation in
   9675 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   9676 ** objects.
   9677 **
   9678 ** Lookaside allocations are only allowed for objects that are associated
   9679 ** with a particular database connection.  Hence, schema information cannot
   9680 ** be stored in lookaside because in shared cache mode the schema information
   9681 ** is shared by multiple database connections.  Therefore, while parsing
   9682 ** schema information, the Lookaside.bEnabled flag is cleared so that
   9683 ** lookaside allocations are not used to construct the schema objects.
   9684 */
   9685 struct Lookaside {
   9686   u16 sz;                 /* Size of each buffer in bytes */
   9687   u8 bEnabled;            /* False to disable new lookaside allocations */
   9688   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   9689   int nOut;               /* Number of buffers currently checked out */
   9690   int mxOut;              /* Highwater mark for nOut */
   9691   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
   9692   LookasideSlot *pFree;   /* List of available buffers */
   9693   void *pStart;           /* First byte of available memory space */
   9694   void *pEnd;             /* First byte past end of available space */
   9695 };
   9696 struct LookasideSlot {
   9697   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   9698 };
   9699 
   9700 /*
   9701 ** A hash table for function definitions.
   9702 **
   9703 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   9704 ** Collisions are on the FuncDef.pHash chain.
   9705 */
   9706 struct FuncDefHash {
   9707   FuncDef *a[23];       /* Hash table for functions */
   9708 };
   9709 
   9710 /*
   9711 ** Each database connection is an instance of the following structure.
   9712 */
   9713 struct sqlite3 {
   9714   sqlite3_vfs *pVfs;            /* OS Interface */
   9715   struct Vdbe *pVdbe;           /* List of active virtual machines */
   9716   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   9717   sqlite3_mutex *mutex;         /* Connection mutex */
   9718   Db *aDb;                      /* All backends */
   9719   int nDb;                      /* Number of backends currently in use */
   9720   int flags;                    /* Miscellaneous flags. See below */
   9721   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   9722   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
   9723   int errCode;                  /* Most recent error code (SQLITE_*) */
   9724   int errMask;                  /* & result codes with this before returning */
   9725   u8 autoCommit;                /* The auto-commit flag. */
   9726   u8 temp_store;                /* 1: file 2: memory 0: default */
   9727   u8 mallocFailed;              /* True if we have seen a malloc failure */
   9728   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   9729   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   9730   u8 suppressErr;               /* Do not issue error messages if true */
   9731   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
   9732   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   9733   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   9734   u32 magic;                    /* Magic number for detect library misuse */
   9735   int nChange;                  /* Value returned by sqlite3_changes() */
   9736   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   9737   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   9738   struct sqlite3InitInfo {      /* Information used during initialization */
   9739     int newTnum;                /* Rootpage of table being initialized */
   9740     u8 iDb;                     /* Which db file is being initialized */
   9741     u8 busy;                    /* TRUE if currently initializing */
   9742     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   9743   } init;
   9744   int activeVdbeCnt;            /* Number of VDBEs currently executing */
   9745   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
   9746   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
   9747   int nExtension;               /* Number of loaded extensions */
   9748   void **aExtension;            /* Array of shared library handles */
   9749   void (*xTrace)(void*,const char*);        /* Trace function */
   9750   void *pTraceArg;                          /* Argument to the trace function */
   9751   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   9752   void *pProfileArg;                        /* Argument to profile function */
   9753   void *pCommitArg;                 /* Argument to xCommitCallback() */
   9754   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   9755   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   9756   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   9757   void *pUpdateArg;
   9758   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   9759 #ifndef SQLITE_OMIT_WAL
   9760   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
   9761   void *pWalArg;
   9762 #endif
   9763   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   9764   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   9765   void *pCollNeededArg;
   9766   sqlite3_value *pErr;          /* Most recent error message */
   9767   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
   9768   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
   9769   union {
   9770     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   9771     double notUsed1;            /* Spacer */
   9772   } u1;
   9773   Lookaside lookaside;          /* Lookaside malloc configuration */
   9774 #ifndef SQLITE_OMIT_AUTHORIZATION
   9775   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   9776                                 /* Access authorization function */
   9777   void *pAuthArg;               /* 1st argument to the access auth function */
   9778 #endif
   9779 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   9780   int (*xProgress)(void *);     /* The progress callback */
   9781   void *pProgressArg;           /* Argument to the progress callback */
   9782   int nProgressOps;             /* Number of opcodes for progress callback */
   9783 #endif
   9784 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9785   int nVTrans;                  /* Allocated size of aVTrans */
   9786   Hash aModule;                 /* populated by sqlite3_create_module() */
   9787   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
   9788   VTable **aVTrans;             /* Virtual tables with open transactions */
   9789   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
   9790 #endif
   9791   FuncDefHash aFunc;            /* Hash table of connection functions */
   9792   Hash aCollSeq;                /* All collating sequences */
   9793   BusyHandler busyHandler;      /* Busy callback */
   9794   Db aDbStatic[2];              /* Static space for the 2 default backends */
   9795   Savepoint *pSavepoint;        /* List of active savepoints */
   9796   int busyTimeout;              /* Busy handler timeout, in msec */
   9797   int nSavepoint;               /* Number of non-transaction savepoints */
   9798   int nStatement;               /* Number of nested statement-transactions  */
   9799   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   9800   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
   9801 
   9802 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   9803   /* The following variables are all protected by the STATIC_MASTER
   9804   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   9805   **
   9806   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   9807   ** unlock so that it can proceed.
   9808   **
   9809   ** When X.pBlockingConnection==Y, that means that something that X tried
   9810   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   9811   ** held by Y.
   9812   */
   9813   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   9814   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   9815   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   9816   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   9817   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   9818 #endif
   9819 };
   9820 
   9821 /*
   9822 ** A macro to discover the encoding of a database.
   9823 */
   9824 #define ENC(db) ((db)->aDb[0].pSchema->enc)
   9825 
   9826 /*
   9827 ** Possible values for the sqlite3.flags.
   9828 */
   9829 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
   9830 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
   9831 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
   9832 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
   9833 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
   9834                                           /*   DELETE, or UPDATE and return */
   9835                                           /*   the count using a callback. */
   9836 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
   9837                                           /*   result set is empty */
   9838 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
   9839 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
   9840 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
   9841                          /*   0x00020000  Unused */
   9842 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
   9843 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
   9844 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
   9845 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
   9846 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
   9847 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
   9848 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
   9849 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
   9850 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
   9851 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
   9852 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
   9853 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
   9854 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
   9855 
   9856 /*
   9857 ** Bits of the sqlite3.flags field that are used by the
   9858 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
   9859 ** These must be the low-order bits of the flags field.
   9860 */
   9861 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
   9862 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
   9863 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
   9864 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
   9865 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
   9866 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
   9867 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
   9868 #define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
   9869 #define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
   9870 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
   9871 
   9872 /*
   9873 ** Possible values for the sqlite.magic field.
   9874 ** The numbers are obtained at random and have no special meaning, other
   9875 ** than being distinct from one another.
   9876 */
   9877 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   9878 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   9879 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   9880 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   9881 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   9882 
   9883 /*
   9884 ** Each SQL function is defined by an instance of the following
   9885 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
   9886 ** hash table.  When multiple functions have the same name, the hash table
   9887 ** points to a linked list of these structures.
   9888 */
   9889 struct FuncDef {
   9890   i16 nArg;            /* Number of arguments.  -1 means unlimited */
   9891   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
   9892   u8 flags;            /* Some combination of SQLITE_FUNC_* */
   9893   void *pUserData;     /* User data parameter */
   9894   FuncDef *pNext;      /* Next function with same name */
   9895   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
   9896   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
   9897   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
   9898   char *zName;         /* SQL name of the function. */
   9899   FuncDef *pHash;      /* Next with a different name but the same hash */
   9900   FuncDestructor *pDestructor;   /* Reference counted destructor function */
   9901 };
   9902 
   9903 /*
   9904 ** This structure encapsulates a user-function destructor callback (as
   9905 ** configured using create_function_v2()) and a reference counter. When
   9906 ** create_function_v2() is called to create a function with a destructor,
   9907 ** a single object of this type is allocated. FuncDestructor.nRef is set to
   9908 ** the number of FuncDef objects created (either 1 or 3, depending on whether
   9909 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
   9910 ** member of each of the new FuncDef objects is set to point to the allocated
   9911 ** FuncDestructor.
   9912 **
   9913 ** Thereafter, when one of the FuncDef objects is deleted, the reference
   9914 ** count on this object is decremented. When it reaches 0, the destructor
   9915 ** is invoked and the FuncDestructor structure freed.
   9916 */
   9917 struct FuncDestructor {
   9918   int nRef;
   9919   void (*xDestroy)(void *);
   9920   void *pUserData;
   9921 };
   9922 
   9923 /*
   9924 ** Possible values for FuncDef.flags
   9925 */
   9926 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
   9927 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
   9928 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
   9929 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
   9930 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
   9931 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
   9932 
   9933 /*
   9934 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   9935 ** used to create the initializers for the FuncDef structures.
   9936 **
   9937 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   9938 **     Used to create a scalar function definition of a function zName
   9939 **     implemented by C function xFunc that accepts nArg arguments. The
   9940 **     value passed as iArg is cast to a (void*) and made available
   9941 **     as the user-data (sqlite3_user_data()) for the function. If
   9942 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   9943 **
   9944 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   9945 **     Used to create an aggregate function definition implemented by
   9946 **     the C functions xStep and xFinal. The first four parameters
   9947 **     are interpreted in the same way as the first 4 parameters to
   9948 **     FUNCTION().
   9949 **
   9950 **   LIKEFUNC(zName, nArg, pArg, flags)
   9951 **     Used to create a scalar function definition of a function zName
   9952 **     that accepts nArg arguments and is implemented by a call to C
   9953 **     function likeFunc. Argument pArg is cast to a (void *) and made
   9954 **     available as the function user-data (sqlite3_user_data()). The
   9955 **     FuncDef.flags variable is set to the value passed as the flags
   9956 **     parameter.
   9957 */
   9958 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   9959   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   9960    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
   9961 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   9962   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   9963    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
   9964 #define LIKEFUNC(zName, nArg, arg, flags) \
   9965   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
   9966 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   9967   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
   9968    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
   9969 
   9970 /*
   9971 ** All current savepoints are stored in a linked list starting at
   9972 ** sqlite3.pSavepoint. The first element in the list is the most recently
   9973 ** opened savepoint. Savepoints are added to the list by the vdbe
   9974 ** OP_Savepoint instruction.
   9975 */
   9976 struct Savepoint {
   9977   char *zName;                        /* Savepoint name (nul-terminated) */
   9978   i64 nDeferredCons;                  /* Number of deferred fk violations */
   9979   Savepoint *pNext;                   /* Parent savepoint (if any) */
   9980 };
   9981 
   9982 /*
   9983 ** The following are used as the second parameter to sqlite3Savepoint(),
   9984 ** and as the P1 argument to the OP_Savepoint instruction.
   9985 */
   9986 #define SAVEPOINT_BEGIN      0
   9987 #define SAVEPOINT_RELEASE    1
   9988 #define SAVEPOINT_ROLLBACK   2
   9989 
   9990 
   9991 /*
   9992 ** Each SQLite module (virtual table definition) is defined by an
   9993 ** instance of the following structure, stored in the sqlite3.aModule
   9994 ** hash table.
   9995 */
   9996 struct Module {
   9997   const sqlite3_module *pModule;       /* Callback pointers */
   9998   const char *zName;                   /* Name passed to create_module() */
   9999   void *pAux;                          /* pAux passed to create_module() */
   10000   void (*xDestroy)(void *);            /* Module destructor function */
   10001 };
   10002 
   10003 /*
   10004 ** information about each column of an SQL table is held in an instance
   10005 ** of this structure.
   10006 */
   10007 struct Column {
   10008   char *zName;     /* Name of this column */
   10009   Expr *pDflt;     /* Default value of this column */
   10010   char *zDflt;     /* Original text of the default value */
   10011   char *zType;     /* Data type for this column */
   10012   char *zColl;     /* Collating sequence.  If NULL, use the default */
   10013   u8 notNull;      /* True if there is a NOT NULL constraint */
   10014   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
   10015   char affinity;   /* One of the SQLITE_AFF_... values */
   10016 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10017   u8 isHidden;     /* True if this column is 'hidden' */
   10018 #endif
   10019 };
   10020 
   10021 /*
   10022 ** A "Collating Sequence" is defined by an instance of the following
   10023 ** structure. Conceptually, a collating sequence consists of a name and
   10024 ** a comparison routine that defines the order of that sequence.
   10025 **
   10026 ** There may two separate implementations of the collation function, one
   10027 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
   10028 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
   10029 ** native byte order. When a collation sequence is invoked, SQLite selects
   10030 ** the version that will require the least expensive encoding
   10031 ** translations, if any.
   10032 **
   10033 ** The CollSeq.pUser member variable is an extra parameter that passed in
   10034 ** as the first argument to the UTF-8 comparison function, xCmp.
   10035 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
   10036 ** xCmp16.
   10037 **
   10038 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
   10039 ** collating sequence is undefined.  Indices built on an undefined
   10040 ** collating sequence may not be read or written.
   10041 */
   10042 struct CollSeq {
   10043   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   10044   u8 enc;               /* Text encoding handled by xCmp() */
   10045   void *pUser;          /* First argument to xCmp() */
   10046   int (*xCmp)(void*,int, const void*, int, const void*);
   10047   void (*xDel)(void*);  /* Destructor for pUser */
   10048 };
   10049 
   10050 /*
   10051 ** A sort order can be either ASC or DESC.
   10052 */
   10053 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   10054 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   10055 
   10056 /*
   10057 ** Column affinity types.
   10058 **
   10059 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   10060 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   10061 ** the speed a little by numbering the values consecutively.
   10062 **
   10063 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
   10064 ** when multiple affinity types are concatenated into a string and
   10065 ** used as the P4 operand, they will be more readable.
   10066 **
   10067 ** Note also that the numeric types are grouped together so that testing
   10068 ** for a numeric type is a single comparison.
   10069 */
   10070 #define SQLITE_AFF_TEXT     'a'
   10071 #define SQLITE_AFF_NONE     'b'
   10072 #define SQLITE_AFF_NUMERIC  'c'
   10073 #define SQLITE_AFF_INTEGER  'd'
   10074 #define SQLITE_AFF_REAL     'e'
   10075 
   10076 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   10077 
   10078 /*
   10079 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   10080 ** affinity value.
   10081 */
   10082 #define SQLITE_AFF_MASK     0x67
   10083 
   10084 /*
   10085 ** Additional bit values that can be ORed with an affinity without
   10086 ** changing the affinity.
   10087 */
   10088 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
   10089 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
   10090 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   10091 
   10092 /*
   10093 ** An object of this type is created for each virtual table present in
   10094 ** the database schema.
   10095 **
   10096 ** If the database schema is shared, then there is one instance of this
   10097 ** structure for each database connection (sqlite3*) that uses the shared
   10098 ** schema. This is because each database connection requires its own unique
   10099 ** instance of the sqlite3_vtab* handle used to access the virtual table
   10100 ** implementation. sqlite3_vtab* handles can not be shared between
   10101 ** database connections, even when the rest of the in-memory database
   10102 ** schema is shared, as the implementation often stores the database
   10103 ** connection handle passed to it via the xConnect() or xCreate() method
   10104 ** during initialization internally. This database connection handle may
   10105 ** then be used by the virtual table implementation to access real tables
   10106 ** within the database. So that they appear as part of the callers
   10107 ** transaction, these accesses need to be made via the same database
   10108 ** connection as that used to execute SQL operations on the virtual table.
   10109 **
   10110 ** All VTable objects that correspond to a single table in a shared
   10111 ** database schema are initially stored in a linked-list pointed to by
   10112 ** the Table.pVTable member variable of the corresponding Table object.
   10113 ** When an sqlite3_prepare() operation is required to access the virtual
   10114 ** table, it searches the list for the VTable that corresponds to the
   10115 ** database connection doing the preparing so as to use the correct
   10116 ** sqlite3_vtab* handle in the compiled query.
   10117 **
   10118 ** When an in-memory Table object is deleted (for example when the
   10119 ** schema is being reloaded for some reason), the VTable objects are not
   10120 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   10121 ** immediately. Instead, they are moved from the Table.pVTable list to
   10122 ** another linked list headed by the sqlite3.pDisconnect member of the
   10123 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   10124 ** next time a statement is prepared using said sqlite3*. This is done
   10125 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   10126 ** Refer to comments above function sqlite3VtabUnlockList() for an
   10127 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   10128 ** list without holding the corresponding sqlite3.mutex mutex.
   10129 **
   10130 ** The memory for objects of this type is always allocated by
   10131 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   10132 ** the first argument.
   10133 */
   10134 struct VTable {
   10135   sqlite3 *db;              /* Database connection associated with this table */
   10136   Module *pMod;             /* Pointer to module implementation */
   10137   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   10138   int nRef;                 /* Number of pointers to this structure */
   10139   u8 bConstraint;           /* True if constraints are supported */
   10140   int iSavepoint;           /* Depth of the SAVEPOINT stack */
   10141   VTable *pNext;            /* Next in linked list (see above) */
   10142 };
   10143 
   10144 /*
   10145 ** Each SQL table is represented in memory by an instance of the
   10146 ** following structure.
   10147 **
   10148 ** Table.zName is the name of the table.  The case of the original
   10149 ** CREATE TABLE statement is stored, but case is not significant for
   10150 ** comparisons.
   10151 **
   10152 ** Table.nCol is the number of columns in this table.  Table.aCol is a
   10153 ** pointer to an array of Column structures, one for each column.
   10154 **
   10155 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
   10156 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
   10157 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
   10158 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
   10159 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
   10160 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
   10161 ** the table has any PRIMARY KEY, INTEGER or otherwise.
   10162 **
   10163 ** Table.tnum is the page number for the root BTree page of the table in the
   10164 ** database file.  If Table.iDb is the index of the database table backend
   10165 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
   10166 ** holds temporary tables and indices.  If TF_Ephemeral is set
   10167 ** then the table is stored in a file that is automatically deleted
   10168 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
   10169 ** refers VDBE cursor number that holds the table open, not to the root
   10170 ** page number.  Transient tables are used to hold the results of a
   10171 ** sub-query that appears instead of a real table name in the FROM clause
   10172 ** of a SELECT statement.
   10173 */
   10174 struct Table {
   10175   char *zName;         /* Name of the table or view */
   10176   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
   10177   int nCol;            /* Number of columns in this table */
   10178   Column *aCol;        /* Information about each column */
   10179   Index *pIndex;       /* List of SQL indexes on this table. */
   10180   int tnum;            /* Root BTree node for this table (see note above) */
   10181   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
   10182   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   10183   u16 nRef;            /* Number of pointers to this Table */
   10184   u8 tabFlags;         /* Mask of TF_* values */
   10185   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   10186   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   10187   char *zColAff;       /* String defining the affinity of each column */
   10188 #ifndef SQLITE_OMIT_CHECK
   10189   Expr *pCheck;        /* The AND of all CHECK constraints */
   10190 #endif
   10191 #ifndef SQLITE_OMIT_ALTERTABLE
   10192   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   10193 #endif
   10194 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10195   VTable *pVTable;     /* List of VTable objects. */
   10196   int nModuleArg;      /* Number of arguments to the module */
   10197   char **azModuleArg;  /* Text of all module args. [0] is module name */
   10198 #endif
   10199   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   10200   Schema *pSchema;     /* Schema that contains this table */
   10201   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   10202 };
   10203 
   10204 /*
   10205 ** Allowed values for Tabe.tabFlags.
   10206 */
   10207 #define TF_Readonly        0x01    /* Read-only system table */
   10208 #define TF_Ephemeral       0x02    /* An ephemeral table */
   10209 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
   10210 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
   10211 #define TF_Virtual         0x10    /* Is a virtual table */
   10212 
   10213 
   10214 /*
   10215 ** Test to see whether or not a table is a virtual table.  This is
   10216 ** done as a macro so that it will be optimized out when virtual
   10217 ** table support is omitted from the build.
   10218 */
   10219 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10220 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
   10221 #  define IsHiddenColumn(X) ((X)->isHidden)
   10222 #else
   10223 #  define IsVirtual(X)      0
   10224 #  define IsHiddenColumn(X) 0
   10225 #endif
   10226 
   10227 /*
   10228 ** Each foreign key constraint is an instance of the following structure.
   10229 **
   10230 ** A foreign key is associated with two tables.  The "from" table is
   10231 ** the table that contains the REFERENCES clause that creates the foreign
   10232 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   10233 ** Consider this example:
   10234 **
   10235 **     CREATE TABLE ex1(
   10236 **       a INTEGER PRIMARY KEY,
   10237 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   10238 **     );
   10239 **
   10240 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   10241 **
   10242 ** Each REFERENCES clause generates an instance of the following structure
   10243 ** which is attached to the from-table.  The to-table need not exist when
   10244 ** the from-table is created.  The existence of the to-table is not checked.
   10245 */
   10246 struct FKey {
   10247   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   10248   FKey *pNextFrom;  /* Next foreign key in pFrom */
   10249   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   10250   FKey *pNextTo;    /* Next foreign key on table named zTo */
   10251   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
   10252   int nCol;         /* Number of columns in this key */
   10253   /* EV: R-30323-21917 */
   10254   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
   10255   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
   10256   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
   10257   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
   10258     int iFrom;         /* Index of column in pFrom */
   10259     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
   10260   } aCol[1];        /* One entry for each of nCol column s */
   10261 };
   10262 
   10263 /*
   10264 ** SQLite supports many different ways to resolve a constraint
   10265 ** error.  ROLLBACK processing means that a constraint violation
   10266 ** causes the operation in process to fail and for the current transaction
   10267 ** to be rolled back.  ABORT processing means the operation in process
   10268 ** fails and any prior changes from that one operation are backed out,
   10269 ** but the transaction is not rolled back.  FAIL processing means that
   10270 ** the operation in progress stops and returns an error code.  But prior
   10271 ** changes due to the same operation are not backed out and no rollback
   10272 ** occurs.  IGNORE means that the particular row that caused the constraint
   10273 ** error is not inserted or updated.  Processing continues and no error
   10274 ** is returned.  REPLACE means that preexisting database rows that caused
   10275 ** a UNIQUE constraint violation are removed so that the new insert or
   10276 ** update can proceed.  Processing continues and no error is reported.
   10277 **
   10278 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   10279 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   10280 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   10281 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   10282 ** referenced table row is propagated into the row that holds the
   10283 ** foreign key.
   10284 **
   10285 ** The following symbolic values are used to record which type
   10286 ** of action to take.
   10287 */
   10288 #define OE_None     0   /* There is no constraint to check */
   10289 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   10290 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   10291 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   10292 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   10293 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   10294 
   10295 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   10296 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   10297 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   10298 #define OE_Cascade  9   /* Cascade the changes */
   10299 
   10300 #define OE_Default  99  /* Do whatever the default action is */
   10301 
   10302 
   10303 /*
   10304 ** An instance of the following structure is passed as the first
   10305 ** argument to sqlite3VdbeKeyCompare and is used to control the
   10306 ** comparison of the two index keys.
   10307 */
   10308 struct KeyInfo {
   10309   sqlite3 *db;        /* The database connection */
   10310   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
   10311   u16 nField;         /* Number of entries in aColl[] */
   10312   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
   10313   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   10314 };
   10315 
   10316 /*
   10317 ** An instance of the following structure holds information about a
   10318 ** single index record that has already been parsed out into individual
   10319 ** values.
   10320 **
   10321 ** A record is an object that contains one or more fields of data.
   10322 ** Records are used to store the content of a table row and to store
   10323 ** the key of an index.  A blob encoding of a record is created by
   10324 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   10325 ** OP_Column opcode.
   10326 **
   10327 ** This structure holds a record that has already been disassembled
   10328 ** into its constituent fields.
   10329 */
   10330 struct UnpackedRecord {
   10331   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   10332   u16 nField;         /* Number of entries in apMem[] */
   10333   u8 flags;           /* Boolean settings.  UNPACKED_... below */
   10334   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
   10335   Mem *aMem;          /* Values */
   10336 };
   10337 
   10338 /*
   10339 ** Allowed values of UnpackedRecord.flags
   10340 */
   10341 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
   10342 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
   10343 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
   10344 
   10345 /*
   10346 ** Each SQL index is represented in memory by an
   10347 ** instance of the following structure.
   10348 **
   10349 ** The columns of the table that are to be indexed are described
   10350 ** by the aiColumn[] field of this structure.  For example, suppose
   10351 ** we have the following table and index:
   10352 **
   10353 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   10354 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   10355 **
   10356 ** In the Table structure describing Ex1, nCol==3 because there are
   10357 ** three columns in the table.  In the Index structure describing
   10358 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   10359 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   10360 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   10361 ** The second column to be indexed (c1) has an index of 0 in
   10362 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   10363 **
   10364 ** The Index.onError field determines whether or not the indexed columns
   10365 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   10366 ** it means this is not a unique index.  Otherwise it is a unique index
   10367 ** and the value of Index.onError indicate the which conflict resolution
   10368 ** algorithm to employ whenever an attempt is made to insert a non-unique
   10369 ** element.
   10370 */
   10371 struct Index {
   10372   char *zName;     /* Name of this index */
   10373   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
   10374   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
   10375   Table *pTable;   /* The SQL table being indexed */
   10376   char *zColAff;   /* String defining the affinity of each column */
   10377   Index *pNext;    /* The next index associated with the same table */
   10378   Schema *pSchema; /* Schema containing this index */
   10379   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
   10380   char **azColl;   /* Array of collation sequence names for index */
   10381   int nColumn;     /* Number of columns in the table used by this index */
   10382   int tnum;        /* Page containing root of this index in database file */
   10383   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   10384   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
   10385   u8 bUnordered;   /* Use this index for == or IN queries only */
   10386 #ifdef SQLITE_ENABLE_STAT3
   10387   int nSample;             /* Number of elements in aSample[] */
   10388   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
   10389   IndexSample *aSample;    /* Samples of the left-most key */
   10390 #endif
   10391 };
   10392 
   10393 /*
   10394 ** Each sample stored in the sqlite_stat3 table is represented in memory
   10395 ** using a structure of this type.  See documentation at the top of the
   10396 ** analyze.c source file for additional information.
   10397 */
   10398 struct IndexSample {
   10399   union {
   10400     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
   10401     double r;       /* Value if eType is SQLITE_FLOAT */
   10402     i64 i;          /* Value if eType is SQLITE_INTEGER */
   10403   } u;
   10404   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
   10405   int nByte;        /* Size in byte of text or blob. */
   10406   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
   10407   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
   10408   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
   10409 };
   10410 
   10411 /*
   10412 ** Each token coming out of the lexer is an instance of
   10413 ** this structure.  Tokens are also used as part of an expression.
   10414 **
   10415 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   10416 ** may contain random values.  Do not make any assumptions about Token.dyn
   10417 ** and Token.n when Token.z==0.
   10418 */
   10419 struct Token {
   10420   const char *z;     /* Text of the token.  Not NULL-terminated! */
   10421   unsigned int n;    /* Number of characters in this token */
   10422 };
   10423 
   10424 /*
   10425 ** An instance of this structure contains information needed to generate
   10426 ** code for a SELECT that contains aggregate functions.
   10427 **
   10428 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   10429 ** pointer to this structure.  The Expr.iColumn field is the index in
   10430 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   10431 ** code for that node.
   10432 **
   10433 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   10434 ** original Select structure that describes the SELECT statement.  These
   10435 ** fields do not need to be freed when deallocating the AggInfo structure.
   10436 */
   10437 struct AggInfo {
   10438   u8 directMode;          /* Direct rendering mode means take data directly
   10439                           ** from source tables rather than from accumulators */
   10440   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   10441                           ** than the source table */
   10442   int sortingIdx;         /* Cursor number of the sorting index */
   10443   int sortingIdxPTab;     /* Cursor number of pseudo-table */
   10444   int nSortingColumn;     /* Number of columns in the sorting index */
   10445   ExprList *pGroupBy;     /* The group by clause */
   10446   struct AggInfo_col {    /* For each column used in source tables */
   10447     Table *pTab;             /* Source table */
   10448     int iTable;              /* Cursor number of the source table */
   10449     int iColumn;             /* Column number within the source table */
   10450     int iSorterColumn;       /* Column number in the sorting index */
   10451     int iMem;                /* Memory location that acts as accumulator */
   10452     Expr *pExpr;             /* The original expression */
   10453   } *aCol;
   10454   int nColumn;            /* Number of used entries in aCol[] */
   10455   int nAccumulator;       /* Number of columns that show through to the output.
   10456                           ** Additional columns are used only as parameters to
   10457                           ** aggregate functions */
   10458   struct AggInfo_func {   /* For each aggregate function */
   10459     Expr *pExpr;             /* Expression encoding the function */
   10460     FuncDef *pFunc;          /* The aggregate function implementation */
   10461     int iMem;                /* Memory location that acts as accumulator */
   10462     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   10463   } *aFunc;
   10464   int nFunc;              /* Number of entries in aFunc[] */
   10465 };
   10466 
   10467 /*
   10468 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   10469 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   10470 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   10471 ** it uses less memory in the Expr object, which is a big memory user
   10472 ** in systems with lots of prepared statements.  And few applications
   10473 ** need more than about 10 or 20 variables.  But some extreme users want
   10474 ** to have prepared statements with over 32767 variables, and for them
   10475 ** the option is available (at compile-time).
   10476 */
   10477 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   10478 typedef i16 ynVar;
   10479 #else
   10480 typedef int ynVar;
   10481 #endif
   10482 
   10483 /*
   10484 ** Each node of an expression in the parse tree is an instance
   10485 ** of this structure.
   10486 **
   10487 ** Expr.op is the opcode. The integer parser token codes are reused
   10488 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   10489 ** code representing the ">=" operator. This same integer code is reused
   10490 ** to represent the greater-than-or-equal-to operator in the expression
   10491 ** tree.
   10492 **
   10493 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   10494 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   10495 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   10496 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   10497 ** then Expr.token contains the name of the function.
   10498 **
   10499 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   10500 ** binary operator. Either or both may be NULL.
   10501 **
   10502 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   10503 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   10504 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   10505 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   10506 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   10507 ** valid.
   10508 **
   10509 ** An expression of the form ID or ID.ID refers to a column in a table.
   10510 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   10511 ** the integer cursor number of a VDBE cursor pointing to that table and
   10512 ** Expr.iColumn is the column number for the specific column.  If the
   10513 ** expression is used as a result in an aggregate SELECT, then the
   10514 ** value is also stored in the Expr.iAgg column in the aggregate so that
   10515 ** it can be accessed after all aggregates are computed.
   10516 **
   10517 ** If the expression is an unbound variable marker (a question mark
   10518 ** character '?' in the original SQL) then the Expr.iTable holds the index
   10519 ** number for that variable.
   10520 **
   10521 ** If the expression is a subquery then Expr.iColumn holds an integer
   10522 ** register number containing the result of the subquery.  If the
   10523 ** subquery gives a constant result, then iTable is -1.  If the subquery
   10524 ** gives a different answer at different times during statement processing
   10525 ** then iTable is the address of a subroutine that computes the subquery.
   10526 **
   10527 ** If the Expr is of type OP_Column, and the table it is selecting from
   10528 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   10529 ** corresponding table definition.
   10530 **
   10531 ** ALLOCATION NOTES:
   10532 **
   10533 ** Expr objects can use a lot of memory space in database schema.  To
   10534 ** help reduce memory requirements, sometimes an Expr object will be
   10535 ** truncated.  And to reduce the number of memory allocations, sometimes
   10536 ** two or more Expr objects will be stored in a single memory allocation,
   10537 ** together with Expr.zToken strings.
   10538 **
   10539 ** If the EP_Reduced and EP_TokenOnly flags are set when
   10540 ** an Expr object is truncated.  When EP_Reduced is set, then all
   10541 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   10542 ** are contained within the same memory allocation.  Note, however, that
   10543 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   10544 ** allocated, regardless of whether or not EP_Reduced is set.
   10545 */
   10546 struct Expr {
   10547   u8 op;                 /* Operation performed by this node */
   10548   char affinity;         /* The affinity of the column or 0 if not a column */
   10549   u16 flags;             /* Various flags.  EP_* See below */
   10550   union {
   10551     char *zToken;          /* Token value. Zero terminated and dequoted */
   10552     int iValue;            /* Non-negative integer value if EP_IntValue */
   10553   } u;
   10554 
   10555   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   10556   ** space is allocated for the fields below this point. An attempt to
   10557   ** access them will result in a segfault or malfunction.
   10558   *********************************************************************/
   10559 
   10560   Expr *pLeft;           /* Left subnode */
   10561   Expr *pRight;          /* Right subnode */
   10562   union {
   10563     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
   10564     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
   10565   } x;
   10566   CollSeq *pColl;        /* The collation type of the column or 0 */
   10567 
   10568   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   10569   ** space is allocated for the fields below this point. An attempt to
   10570   ** access them will result in a segfault or malfunction.
   10571   *********************************************************************/
   10572 
   10573   int iTable;            /* TK_COLUMN: cursor number of table holding column
   10574                          ** TK_REGISTER: register number
   10575                          ** TK_TRIGGER: 1 -> new, 0 -> old */
   10576   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   10577                          ** TK_VARIABLE: variable number (always >= 1). */
   10578   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   10579   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   10580   u8 flags2;             /* Second set of flags.  EP2_... */
   10581   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
   10582   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   10583   Table *pTab;           /* Table for TK_COLUMN expressions. */
   10584 #if SQLITE_MAX_EXPR_DEPTH>0
   10585   int nHeight;           /* Height of the tree headed by this node */
   10586 #endif
   10587 };
   10588 
   10589 /*
   10590 ** The following are the meanings of bits in the Expr.flags field.
   10591 */
   10592 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
   10593 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
   10594 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
   10595 #define EP_Error      0x0008  /* Expression contains one or more errors */
   10596 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
   10597 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
   10598 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
   10599 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
   10600 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
   10601 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
   10602 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
   10603 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
   10604 #define EP_Hint       0x1000  /* Optimizer hint. Not required for correctness */
   10605 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
   10606 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
   10607 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
   10608 
   10609 /*
   10610 ** The following are the meanings of bits in the Expr.flags2 field.
   10611 */
   10612 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
   10613 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
   10614 
   10615 /*
   10616 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
   10617 ** flag on an expression structure.  This flag is used for VV&A only.  The
   10618 ** routine is implemented as a macro that only works when in debugging mode,
   10619 ** so as not to burden production code.
   10620 */
   10621 #ifdef SQLITE_DEBUG
   10622 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
   10623 #else
   10624 # define ExprSetIrreducible(X)
   10625 #endif
   10626 
   10627 /*
   10628 ** These macros can be used to test, set, or clear bits in the
   10629 ** Expr.flags field.
   10630 */
   10631 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
   10632 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
   10633 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   10634 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   10635 
   10636 /*
   10637 ** Macros to determine the number of bytes required by a normal Expr
   10638 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   10639 ** and an Expr struct with the EP_TokenOnly flag set.
   10640 */
   10641 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   10642 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   10643 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   10644 
   10645 /*
   10646 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   10647 ** above sqlite3ExprDup() for details.
   10648 */
   10649 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   10650 
   10651 /*
   10652 ** A list of expressions.  Each expression may optionally have a
   10653 ** name.  An expr/name combination can be used in several ways, such
   10654 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   10655 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   10656 ** also be used as the argument to a function, in which case the a.zName
   10657 ** field is not used.
   10658 */
   10659 struct ExprList {
   10660   int nExpr;             /* Number of expressions on the list */
   10661   int iECursor;          /* VDBE Cursor associated with this ExprList */
   10662   struct ExprList_item { /* For each expression in the list */
   10663     Expr *pExpr;           /* The list of expressions */
   10664     char *zName;           /* Token associated with this expression */
   10665     char *zSpan;           /* Original text of the expression */
   10666     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
   10667     u8 done;               /* A flag to indicate when processing is finished */
   10668     u16 iOrderByCol;       /* For ORDER BY, column number in result set */
   10669     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
   10670   } *a;                  /* Alloc a power of two greater or equal to nExpr */
   10671 };
   10672 
   10673 /*
   10674 ** An instance of this structure is used by the parser to record both
   10675 ** the parse tree for an expression and the span of input text for an
   10676 ** expression.
   10677 */
   10678 struct ExprSpan {
   10679   Expr *pExpr;          /* The expression parse tree */
   10680   const char *zStart;   /* First character of input text */
   10681   const char *zEnd;     /* One character past the end of input text */
   10682 };
   10683 
   10684 /*
   10685 ** An instance of this structure can hold a simple list of identifiers,
   10686 ** such as the list "a,b,c" in the following statements:
   10687 **
   10688 **      INSERT INTO t(a,b,c) VALUES ...;
   10689 **      CREATE INDEX idx ON t(a,b,c);
   10690 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   10691 **
   10692 ** The IdList.a.idx field is used when the IdList represents the list of
   10693 ** column names after a table name in an INSERT statement.  In the statement
   10694 **
   10695 **     INSERT INTO t(a,b,c) ...
   10696 **
   10697 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   10698 */
   10699 struct IdList {
   10700   struct IdList_item {
   10701     char *zName;      /* Name of the identifier */
   10702     int idx;          /* Index in some Table.aCol[] of a column named zName */
   10703   } *a;
   10704   int nId;         /* Number of identifiers on the list */
   10705 };
   10706 
   10707 /*
   10708 ** The bitmask datatype defined below is used for various optimizations.
   10709 **
   10710 ** Changing this from a 64-bit to a 32-bit type limits the number of
   10711 ** tables in a join to 32 instead of 64.  But it also reduces the size
   10712 ** of the library by 738 bytes on ix86.
   10713 */
   10714 typedef u64 Bitmask;
   10715 
   10716 /*
   10717 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   10718 */
   10719 #define BMS  ((int)(sizeof(Bitmask)*8))
   10720 
   10721 /*
   10722 ** The following structure describes the FROM clause of a SELECT statement.
   10723 ** Each table or subquery in the FROM clause is a separate element of
   10724 ** the SrcList.a[] array.
   10725 **
   10726 ** With the addition of multiple database support, the following structure
   10727 ** can also be used to describe a particular table such as the table that
   10728 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   10729 ** such a table must be a simple name: ID.  But in SQLite, the table can
   10730 ** now be identified by a database name, a dot, then the table name: ID.ID.
   10731 **
   10732 ** The jointype starts out showing the join type between the current table
   10733 ** and the next table on the list.  The parser builds the list this way.
   10734 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   10735 ** jointype expresses the join between the table and the previous table.
   10736 **
   10737 ** In the colUsed field, the high-order bit (bit 63) is set if the table
   10738 ** contains more than 63 columns and the 64-th or later column is used.
   10739 */
   10740 struct SrcList {
   10741   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
   10742   i16 nAlloc;      /* Number of entries allocated in a[] below */
   10743   struct SrcList_item {
   10744     char *zDatabase;  /* Name of database holding this table */
   10745     char *zName;      /* Name of the table */
   10746     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   10747     Table *pTab;      /* An SQL table corresponding to zName */
   10748     Select *pSelect;  /* A SELECT statement used in place of a table name */
   10749     int addrFillSub;  /* Address of subroutine to manifest a subquery */
   10750     int regReturn;    /* Register holding return address of addrFillSub */
   10751     u8 jointype;      /* Type of join between this able and the previous */
   10752     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
   10753     u8 isCorrelated;  /* True if sub-query is correlated */
   10754 #ifndef SQLITE_OMIT_EXPLAIN
   10755     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
   10756 #endif
   10757     int iCursor;      /* The VDBE cursor number used to access this table */
   10758     Expr *pOn;        /* The ON clause of a join */
   10759     IdList *pUsing;   /* The USING clause of a join */
   10760     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   10761     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
   10762     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
   10763   } a[1];             /* One entry for each identifier on the list */
   10764 };
   10765 
   10766 /*
   10767 ** Permitted values of the SrcList.a.jointype field
   10768 */
   10769 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   10770 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   10771 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   10772 #define JT_LEFT      0x0008    /* Left outer join */
   10773 #define JT_RIGHT     0x0010    /* Right outer join */
   10774 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   10775 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   10776 
   10777 
   10778 /*
   10779 ** A WherePlan object holds information that describes a lookup
   10780 ** strategy.
   10781 **
   10782 ** This object is intended to be opaque outside of the where.c module.
   10783 ** It is included here only so that that compiler will know how big it
   10784 ** is.  None of the fields in this object should be used outside of
   10785 ** the where.c module.
   10786 **
   10787 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
   10788 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
   10789 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
   10790 ** case that more than one of these conditions is true.
   10791 */
   10792 struct WherePlan {
   10793   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
   10794   u32 nEq;                       /* Number of == constraints */
   10795   double nRow;                   /* Estimated number of rows (for EQP) */
   10796   union {
   10797     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
   10798     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
   10799     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
   10800   } u;
   10801 };
   10802 
   10803 /*
   10804 ** For each nested loop in a WHERE clause implementation, the WhereInfo
   10805 ** structure contains a single instance of this structure.  This structure
   10806 ** is intended to be private the the where.c module and should not be
   10807 ** access or modified by other modules.
   10808 **
   10809 ** The pIdxInfo field is used to help pick the best index on a
   10810 ** virtual table.  The pIdxInfo pointer contains indexing
   10811 ** information for the i-th table in the FROM clause before reordering.
   10812 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
   10813 ** All other information in the i-th WhereLevel object for the i-th table
   10814 ** after FROM clause ordering.
   10815 */
   10816 struct WhereLevel {
   10817   WherePlan plan;       /* query plan for this element of the FROM clause */
   10818   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   10819   int iTabCur;          /* The VDBE cursor used to access the table */
   10820   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   10821   int addrBrk;          /* Jump here to break out of the loop */
   10822   int addrNxt;          /* Jump here to start the next IN combination */
   10823   int addrCont;         /* Jump here to continue with the next loop cycle */
   10824   int addrFirst;        /* First instruction of interior of the loop */
   10825   u8 iFrom;             /* Which entry in the FROM clause */
   10826   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
   10827   int p1, p2;           /* Operands of the opcode used to ends the loop */
   10828   union {               /* Information that depends on plan.wsFlags */
   10829     struct {
   10830       int nIn;              /* Number of entries in aInLoop[] */
   10831       struct InLoop {
   10832         int iCur;              /* The VDBE cursor used by this IN operator */
   10833         int addrInTop;         /* Top of the IN loop */
   10834       } *aInLoop;           /* Information about each nested IN operator */
   10835     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
   10836   } u;
   10837 
   10838   /* The following field is really not part of the current level.  But
   10839   ** we need a place to cache virtual table index information for each
   10840   ** virtual table in the FROM clause and the WhereLevel structure is
   10841   ** a convenient place since there is one WhereLevel for each FROM clause
   10842   ** element.
   10843   */
   10844   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
   10845 };
   10846 
   10847 /*
   10848 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   10849 ** and the WhereInfo.wctrlFlags member.
   10850 */
   10851 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   10852 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   10853 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   10854 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   10855 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
   10856 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
   10857 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
   10858 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
   10859 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
   10860 
   10861 /*
   10862 ** The WHERE clause processing routine has two halves.  The
   10863 ** first part does the start of the WHERE loop and the second
   10864 ** half does the tail of the WHERE loop.  An instance of
   10865 ** this structure is returned by the first half and passed
   10866 ** into the second half to give some continuity.
   10867 */
   10868 struct WhereInfo {
   10869   Parse *pParse;       /* Parsing and code generating context */
   10870   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
   10871   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
   10872   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
   10873   u8 eDistinct;
   10874   SrcList *pTabList;             /* List of tables in the join */
   10875   int iTop;                      /* The very beginning of the WHERE loop */
   10876   int iContinue;                 /* Jump here to continue with next record */
   10877   int iBreak;                    /* Jump here to break out of the loop */
   10878   int nLevel;                    /* Number of nested loop */
   10879   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
   10880   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
   10881   double nRowOut;                /* Estimated number of output rows */
   10882   WhereLevel a[1];               /* Information about each nest loop in WHERE */
   10883 };
   10884 
   10885 #define WHERE_DISTINCT_UNIQUE 1
   10886 #define WHERE_DISTINCT_ORDERED 2
   10887 
   10888 /*
   10889 ** A NameContext defines a context in which to resolve table and column
   10890 ** names.  The context consists of a list of tables (the pSrcList) field and
   10891 ** a list of named expression (pEList).  The named expression list may
   10892 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   10893 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   10894 ** pEList corresponds to the result set of a SELECT and is NULL for
   10895 ** other statements.
   10896 **
   10897 ** NameContexts can be nested.  When resolving names, the inner-most
   10898 ** context is searched first.  If no match is found, the next outer
   10899 ** context is checked.  If there is still no match, the next context
   10900 ** is checked.  This process continues until either a match is found
   10901 ** or all contexts are check.  When a match is found, the nRef member of
   10902 ** the context containing the match is incremented.
   10903 **
   10904 ** Each subquery gets a new NameContext.  The pNext field points to the
   10905 ** NameContext in the parent query.  Thus the process of scanning the
   10906 ** NameContext list corresponds to searching through successively outer
   10907 ** subqueries looking for a match.
   10908 */
   10909 struct NameContext {
   10910   Parse *pParse;       /* The parser */
   10911   SrcList *pSrcList;   /* One or more tables used to resolve names */
   10912   ExprList *pEList;    /* Optional list of named expressions */
   10913   int nRef;            /* Number of names resolved by this context */
   10914   int nErr;            /* Number of errors encountered while resolving names */
   10915   u8 allowAgg;         /* Aggregate functions allowed here */
   10916   u8 hasAgg;           /* True if aggregates are seen */
   10917   u8 isCheck;          /* True if resolving names in a CHECK constraint */
   10918   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
   10919   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   10920   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   10921 };
   10922 
   10923 /*
   10924 ** An instance of the following structure contains all information
   10925 ** needed to generate code for a single SELECT statement.
   10926 **
   10927 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   10928 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   10929 ** limit and nOffset to the value of the offset (or 0 if there is not
   10930 ** offset).  But later on, nLimit and nOffset become the memory locations
   10931 ** in the VDBE that record the limit and offset counters.
   10932 **
   10933 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   10934 ** These addresses must be stored so that we can go back and fill in
   10935 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   10936 ** the number of columns in P2 can be computed at the same time
   10937 ** as the OP_OpenEphm instruction is coded because not
   10938 ** enough information about the compound query is known at that point.
   10939 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   10940 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
   10941 ** sequences for the ORDER BY clause.
   10942 */
   10943 struct Select {
   10944   ExprList *pEList;      /* The fields of the result */
   10945   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   10946   char affinity;         /* MakeRecord with this affinity for SRT_Set */
   10947   u16 selFlags;          /* Various SF_* values */
   10948   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   10949   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
   10950   double nSelectRow;     /* Estimated number of result rows */
   10951   SrcList *pSrc;         /* The FROM clause */
   10952   Expr *pWhere;          /* The WHERE clause */
   10953   ExprList *pGroupBy;    /* The GROUP BY clause */
   10954   Expr *pHaving;         /* The HAVING clause */
   10955   ExprList *pOrderBy;    /* The ORDER BY clause */
   10956   Select *pPrior;        /* Prior select in a compound select statement */
   10957   Select *pNext;         /* Next select to the left in a compound */
   10958   Select *pRightmost;    /* Right-most select in a compound select statement */
   10959   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   10960   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
   10961 };
   10962 
   10963 /*
   10964 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   10965 ** "Select Flag".
   10966 */
   10967 #define SF_Distinct        0x01  /* Output should be DISTINCT */
   10968 #define SF_Resolved        0x02  /* Identifiers have been resolved */
   10969 #define SF_Aggregate       0x04  /* Contains aggregate functions */
   10970 #define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */
   10971 #define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */
   10972 #define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */
   10973 #define SF_UseSorter       0x40  /* Sort using a sorter */
   10974 #define SF_Values          0x80  /* Synthesized from VALUES clause */
   10975 
   10976 
   10977 /*
   10978 ** The results of a select can be distributed in several ways.  The
   10979 ** "SRT" prefix means "SELECT Result Type".
   10980 */
   10981 #define SRT_Union        1  /* Store result as keys in an index */
   10982 #define SRT_Except       2  /* Remove result from a UNION index */
   10983 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   10984 #define SRT_Discard      4  /* Do not save the results anywhere */
   10985 
   10986 /* The ORDER BY clause is ignored for all of the above */
   10987 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
   10988 
   10989 #define SRT_Output       5  /* Output each row of result */
   10990 #define SRT_Mem          6  /* Store result in a memory cell */
   10991 #define SRT_Set          7  /* Store results as keys in an index */
   10992 #define SRT_Table        8  /* Store result as data with an automatic rowid */
   10993 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
   10994 #define SRT_Coroutine   10  /* Generate a single row of result */
   10995 
   10996 /*
   10997 ** A structure used to customize the behavior of sqlite3Select(). See
   10998 ** comments above sqlite3Select() for details.
   10999 */
   11000 typedef struct SelectDest SelectDest;
   11001 struct SelectDest {
   11002   u8 eDest;         /* How to dispose of the results */
   11003   u8 affinity;      /* Affinity used when eDest==SRT_Set */
   11004   int iParm;        /* A parameter used by the eDest disposal method */
   11005   int iMem;         /* Base register where results are written */
   11006   int nMem;         /* Number of registers allocated */
   11007 };
   11008 
   11009 /*
   11010 ** During code generation of statements that do inserts into AUTOINCREMENT
   11011 ** tables, the following information is attached to the Table.u.autoInc.p
   11012 ** pointer of each autoincrement table to record some side information that
   11013 ** the code generator needs.  We have to keep per-table autoincrement
   11014 ** information in case inserts are down within triggers.  Triggers do not
   11015 ** normally coordinate their activities, but we do need to coordinate the
   11016 ** loading and saving of autoincrement information.
   11017 */
   11018 struct AutoincInfo {
   11019   AutoincInfo *pNext;   /* Next info block in a list of them all */
   11020   Table *pTab;          /* Table this info block refers to */
   11021   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   11022   int regCtr;           /* Memory register holding the rowid counter */
   11023 };
   11024 
   11025 /*
   11026 ** Size of the column cache
   11027 */
   11028 #ifndef SQLITE_N_COLCACHE
   11029 # define SQLITE_N_COLCACHE 10
   11030 #endif
   11031 
   11032 /*
   11033 ** At least one instance of the following structure is created for each
   11034 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   11035 ** statement. All such objects are stored in the linked list headed at
   11036 ** Parse.pTriggerPrg and deleted once statement compilation has been
   11037 ** completed.
   11038 **
   11039 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   11040 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   11041 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   11042 ** The Parse.pTriggerPrg list never contains two entries with the same
   11043 ** values for both pTrigger and orconf.
   11044 **
   11045 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   11046 ** accessed (or set to 0 for triggers fired as a result of INSERT
   11047 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   11048 ** a mask of new.* columns used by the program.
   11049 */
   11050 struct TriggerPrg {
   11051   Trigger *pTrigger;      /* Trigger this program was coded from */
   11052   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   11053   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   11054   int orconf;             /* Default ON CONFLICT policy */
   11055   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   11056 };
   11057 
   11058 /*
   11059 ** The yDbMask datatype for the bitmask of all attached databases.
   11060 */
   11061 #if SQLITE_MAX_ATTACHED>30
   11062   typedef sqlite3_uint64 yDbMask;
   11063 #else
   11064   typedef unsigned int yDbMask;
   11065 #endif
   11066 
   11067 /*
   11068 ** An SQL parser context.  A copy of this structure is passed through
   11069 ** the parser and down into all the parser action routine in order to
   11070 ** carry around information that is global to the entire parse.
   11071 **
   11072 ** The structure is divided into two parts.  When the parser and code
   11073 ** generate call themselves recursively, the first part of the structure
   11074 ** is constant but the second part is reset at the beginning and end of
   11075 ** each recursion.
   11076 **
   11077 ** The nTableLock and aTableLock variables are only used if the shared-cache
   11078 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   11079 ** used to store the set of table-locks required by the statement being
   11080 ** compiled. Function sqlite3TableLock() is used to add entries to the
   11081 ** list.
   11082 */
   11083 struct Parse {
   11084   sqlite3 *db;         /* The main database structure */
   11085   char *zErrMsg;       /* An error message */
   11086   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   11087   int rc;              /* Return code from execution */
   11088   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   11089   u8 checkSchema;      /* Causes schema cookie check after an error */
   11090   u8 nested;           /* Number of nested calls to the parser/code generator */
   11091   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   11092   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
   11093   u8 nColCache;        /* Number of entries in aColCache[] */
   11094   u8 iColCache;        /* Next entry in aColCache[] to replace */
   11095   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
   11096   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   11097   int aTempReg[8];     /* Holding area for temporary registers */
   11098   int nRangeReg;       /* Size of the temporary register block */
   11099   int iRangeReg;       /* First register in temporary register block */
   11100   int nErr;            /* Number of errors seen */
   11101   int nTab;            /* Number of previously allocated VDBE cursors */
   11102   int nMem;            /* Number of memory cells used so far */
   11103   int nSet;            /* Number of sets used so far */
   11104   int nOnce;           /* Number of OP_Once instructions so far */
   11105   int ckBase;          /* Base register of data during check constraints */
   11106   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   11107   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   11108   struct yColCache {
   11109     int iTable;           /* Table cursor number */
   11110     int iColumn;          /* Table column number */
   11111     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   11112     int iLevel;           /* Nesting level */
   11113     int iReg;             /* Reg with value of this column. 0 means none. */
   11114     int lru;              /* Least recently used entry has the smallest value */
   11115   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   11116   yDbMask writeMask;   /* Start a write transaction on these databases */
   11117   yDbMask cookieMask;  /* Bitmask of schema verified databases */
   11118   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
   11119   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
   11120   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   11121   int regRoot;         /* Register holding root page number for new objects */
   11122   int nMaxArg;         /* Max args passed to user function by sub-program */
   11123 #ifndef SQLITE_OMIT_SHARED_CACHE
   11124   int nTableLock;        /* Number of locks in aTableLock */
   11125   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   11126 #endif
   11127   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   11128 
   11129   /* Information used while coding trigger programs. */
   11130   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   11131   Table *pTriggerTab;  /* Table triggers are being coded for */
   11132   double nQueryLoop;   /* Estimated number of iterations of a query */
   11133   u32 oldmask;         /* Mask of old.* columns referenced */
   11134   u32 newmask;         /* Mask of new.* columns referenced */
   11135   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   11136   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   11137   u8 disableTriggers;  /* True to disable triggers */
   11138 
   11139   /* Above is constant between recursions.  Below is reset before and after
   11140   ** each recursion */
   11141 
   11142   int nVar;                 /* Number of '?' variables seen in the SQL so far */
   11143   int nzVar;                /* Number of available slots in azVar[] */
   11144   u8 explain;               /* True if the EXPLAIN flag is found on the query */
   11145 #ifndef SQLITE_OMIT_VIRTUALTABLE
   11146   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
   11147   int nVtabLock;            /* Number of virtual tables to lock */
   11148 #endif
   11149   int nAlias;               /* Number of aliased result set columns */
   11150   int nHeight;              /* Expression tree height of current sub-select */
   11151 #ifndef SQLITE_OMIT_EXPLAIN
   11152   int iSelectId;            /* ID of current select for EXPLAIN output */
   11153   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
   11154 #endif
   11155   char **azVar;             /* Pointers to names of parameters */
   11156   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
   11157   int *aAlias;              /* Register used to hold aliased result */
   11158   const char *zTail;        /* All SQL text past the last semicolon parsed */
   11159   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
   11160   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   11161   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   11162   Token sNameToken;         /* Token with unqualified schema object name */
   11163   Token sLastToken;         /* The last token parsed */
   11164 #ifndef SQLITE_OMIT_VIRTUALTABLE
   11165   Token sArg;               /* Complete text of a module argument */
   11166   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
   11167 #endif
   11168   Table *pZombieTab;        /* List of Table objects to delete after code gen */
   11169   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
   11170 };
   11171 
   11172 /*
   11173 ** Return true if currently inside an sqlite3_declare_vtab() call.
   11174 */
   11175 #ifdef SQLITE_OMIT_VIRTUALTABLE
   11176   #define IN_DECLARE_VTAB 0
   11177 #else
   11178   #define IN_DECLARE_VTAB (pParse->declareVtab)
   11179 #endif
   11180 
   11181 /*
   11182 ** An instance of the following structure can be declared on a stack and used
   11183 ** to save the Parse.zAuthContext value so that it can be restored later.
   11184 */
   11185 struct AuthContext {
   11186   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   11187   Parse *pParse;              /* The Parse structure */
   11188 };
   11189 
   11190 /*
   11191 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
   11192 */
   11193 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
   11194 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
   11195 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   11196 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   11197 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   11198 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
   11199 
   11200 /*
   11201  * Each trigger present in the database schema is stored as an instance of
   11202  * struct Trigger.
   11203  *
   11204  * Pointers to instances of struct Trigger are stored in two ways.
   11205  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   11206  *    database). This allows Trigger structures to be retrieved by name.
   11207  * 2. All triggers associated with a single table form a linked list, using the
   11208  *    pNext member of struct Trigger. A pointer to the first element of the
   11209  *    linked list is stored as the "pTrigger" member of the associated
   11210  *    struct Table.
   11211  *
   11212  * The "step_list" member points to the first element of a linked list
   11213  * containing the SQL statements specified as the trigger program.
   11214  */
   11215 struct Trigger {
   11216   char *zName;            /* The name of the trigger                        */
   11217   char *table;            /* The table or view to which the trigger applies */
   11218   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   11219   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   11220   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   11221   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   11222                              the <column-list> is stored here */
   11223   Schema *pSchema;        /* Schema containing the trigger */
   11224   Schema *pTabSchema;     /* Schema containing the table */
   11225   TriggerStep *step_list; /* Link list of trigger program steps             */
   11226   Trigger *pNext;         /* Next trigger associated with the table */
   11227 };
   11228 
   11229 /*
   11230 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   11231 ** determine which.
   11232 **
   11233 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   11234 ** In that cases, the constants below can be ORed together.
   11235 */
   11236 #define TRIGGER_BEFORE  1
   11237 #define TRIGGER_AFTER   2
   11238 
   11239 /*
   11240  * An instance of struct TriggerStep is used to store a single SQL statement
   11241  * that is a part of a trigger-program.
   11242  *
   11243  * Instances of struct TriggerStep are stored in a singly linked list (linked
   11244  * using the "pNext" member) referenced by the "step_list" member of the
   11245  * associated struct Trigger instance. The first element of the linked list is
   11246  * the first step of the trigger-program.
   11247  *
   11248  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   11249  * "SELECT" statement. The meanings of the other members is determined by the
   11250  * value of "op" as follows:
   11251  *
   11252  * (op == TK_INSERT)
   11253  * orconf    -> stores the ON CONFLICT algorithm
   11254  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   11255  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   11256  * target    -> A token holding the quoted name of the table to insert into.
   11257  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   11258  *              this stores values to be inserted. Otherwise NULL.
   11259  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   11260  *              statement, then this stores the column-names to be
   11261  *              inserted into.
   11262  *
   11263  * (op == TK_DELETE)
   11264  * target    -> A token holding the quoted name of the table to delete from.
   11265  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   11266  *              Otherwise NULL.
   11267  *
   11268  * (op == TK_UPDATE)
   11269  * target    -> A token holding the quoted name of the table to update rows of.
   11270  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   11271  *              Otherwise NULL.
   11272  * pExprList -> A list of the columns to update and the expressions to update
   11273  *              them to. See sqlite3Update() documentation of "pChanges"
   11274  *              argument.
   11275  *
   11276  */
   11277 struct TriggerStep {
   11278   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   11279   u8 orconf;           /* OE_Rollback etc. */
   11280   Trigger *pTrig;      /* The trigger that this step is a part of */
   11281   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
   11282   Token target;        /* Target table for DELETE, UPDATE, INSERT */
   11283   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   11284   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
   11285   IdList *pIdList;     /* Column names for INSERT */
   11286   TriggerStep *pNext;  /* Next in the link-list */
   11287   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   11288 };
   11289 
   11290 /*
   11291 ** The following structure contains information used by the sqliteFix...
   11292 ** routines as they walk the parse tree to make database references
   11293 ** explicit.
   11294 */
   11295 typedef struct DbFixer DbFixer;
   11296 struct DbFixer {
   11297   Parse *pParse;      /* The parsing context.  Error messages written here */
   11298   const char *zDb;    /* Make sure all objects are contained in this database */
   11299   const char *zType;  /* Type of the container - used for error messages */
   11300   const Token *pName; /* Name of the container - used for error messages */
   11301 };
   11302 
   11303 /*
   11304 ** An objected used to accumulate the text of a string where we
   11305 ** do not necessarily know how big the string will be in the end.
   11306 */
   11307 struct StrAccum {
   11308   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   11309   char *zBase;         /* A base allocation.  Not from malloc. */
   11310   char *zText;         /* The string collected so far */
   11311   int  nChar;          /* Length of the string so far */
   11312   int  nAlloc;         /* Amount of space allocated in zText */
   11313   int  mxAlloc;        /* Maximum allowed string length */
   11314   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
   11315   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
   11316   u8   tooBig;         /* Becomes true if string size exceeds limits */
   11317 };
   11318 
   11319 /*
   11320 ** A pointer to this structure is used to communicate information
   11321 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   11322 */
   11323 typedef struct {
   11324   sqlite3 *db;        /* The database being initialized */
   11325   char **pzErrMsg;    /* Error message stored here */
   11326   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   11327   int rc;             /* Result code stored here */
   11328 } InitData;
   11329 
   11330 /*
   11331 ** Structure containing global configuration data for the SQLite library.
   11332 **
   11333 ** This structure also contains some state information.
   11334 */
   11335 struct Sqlite3Config {
   11336   int bMemstat;                     /* True to enable memory status */
   11337   int bCoreMutex;                   /* True to enable core mutexing */
   11338   int bFullMutex;                   /* True to enable full mutexing */
   11339   int bOpenUri;                     /* True to interpret filenames as URIs */
   11340   int mxStrlen;                     /* Maximum string length */
   11341   int szLookaside;                  /* Default lookaside buffer size */
   11342   int nLookaside;                   /* Default lookaside buffer count */
   11343   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   11344   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   11345   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
   11346   void *pHeap;                      /* Heap storage space */
   11347   int nHeap;                        /* Size of pHeap[] */
   11348   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   11349   void *pScratch;                   /* Scratch memory */
   11350   int szScratch;                    /* Size of each scratch buffer */
   11351   int nScratch;                     /* Number of scratch buffers */
   11352   void *pPage;                      /* Page cache memory */
   11353   int szPage;                       /* Size of each page in pPage[] */
   11354   int nPage;                        /* Number of pages in pPage[] */
   11355   int mxParserStack;                /* maximum depth of the parser stack */
   11356   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   11357   /* The above might be initialized to non-zero.  The following need to always
   11358   ** initially be zero, however. */
   11359   int isInit;                       /* True after initialization has finished */
   11360   int inProgress;                   /* True while initialization in progress */
   11361   int isMutexInit;                  /* True after mutexes are initialized */
   11362   int isMallocInit;                 /* True after malloc is initialized */
   11363   int isPCacheInit;                 /* True after malloc is initialized */
   11364   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   11365   int nRefInitMutex;                /* Number of users of pInitMutex */
   11366   void (*xLog)(void*,int,const char*); /* Function for logging */
   11367   void *pLogArg;                       /* First argument to xLog() */
   11368   int bLocaltimeFault;              /* True to fail localtime() calls */
   11369 };
   11370 
   11371 /*
   11372 ** Context pointer passed down through the tree-walk.
   11373 */
   11374 struct Walker {
   11375   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   11376   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   11377   Parse *pParse;                            /* Parser context.  */
   11378   union {                                   /* Extra data for callback */
   11379     NameContext *pNC;                          /* Naming context */
   11380     int i;                                     /* Integer value */
   11381   } u;
   11382 };
   11383 
   11384 /* Forward declarations */
   11385 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   11386 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   11387 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   11388 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   11389 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   11390 
   11391 /*
   11392 ** Return code from the parse-tree walking primitives and their
   11393 ** callbacks.
   11394 */
   11395 #define WRC_Continue    0   /* Continue down into children */
   11396 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   11397 #define WRC_Abort       2   /* Abandon the tree walk */
   11398 
   11399 /*
   11400 ** Assuming zIn points to the first byte of a UTF-8 character,
   11401 ** advance zIn to point to the first byte of the next UTF-8 character.
   11402 */
   11403 #define SQLITE_SKIP_UTF8(zIn) {                        \
   11404   if( (*(zIn++))>=0xc0 ){                              \
   11405     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   11406   }                                                    \
   11407 }
   11408 
   11409 /*
   11410 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   11411 ** the same name but without the _BKPT suffix.  These macros invoke
   11412 ** routines that report the line-number on which the error originated
   11413 ** using sqlite3_log().  The routines also provide a convenient place
   11414 ** to set a debugger breakpoint.
   11415 */
   11416 SQLITE_PRIVATE int sqlite3CorruptError(int);
   11417 SQLITE_PRIVATE int sqlite3MisuseError(int);
   11418 SQLITE_PRIVATE int sqlite3CantopenError(int);
   11419 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   11420 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   11421 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   11422 
   11423 
   11424 /*
   11425 ** FTS4 is really an extension for FTS3.  It is enabled using the
   11426 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   11427 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   11428 */
   11429 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   11430 # define SQLITE_ENABLE_FTS3
   11431 #endif
   11432 
   11433 /*
   11434 ** The ctype.h header is needed for non-ASCII systems.  It is also
   11435 ** needed by FTS3 when FTS3 is included in the amalgamation.
   11436 */
   11437 #if !defined(SQLITE_ASCII) || \
   11438     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   11439 # include <ctype.h>
   11440 #endif
   11441 
   11442 /*
   11443 ** The following macros mimic the standard library functions toupper(),
   11444 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   11445 ** sqlite versions only work for ASCII characters, regardless of locale.
   11446 */
   11447 #ifdef SQLITE_ASCII
   11448 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   11449 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   11450 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   11451 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   11452 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   11453 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   11454 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   11455 #else
   11456 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   11457 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   11458 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   11459 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   11460 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   11461 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   11462 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   11463 #endif
   11464 
   11465 /*
   11466 ** Internal function prototypes
   11467 */
   11468 #define sqlite3StrICmp sqlite3_stricmp
   11469 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   11470 #define sqlite3StrNICmp sqlite3_strnicmp
   11471 
   11472 SQLITE_PRIVATE int sqlite3MallocInit(void);
   11473 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   11474 SQLITE_PRIVATE void *sqlite3Malloc(int);
   11475 SQLITE_PRIVATE void *sqlite3MallocZero(int);
   11476 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
   11477 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
   11478 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   11479 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
   11480 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
   11481 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
   11482 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
   11483 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   11484 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   11485 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   11486 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
   11487 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
   11488 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   11489 SQLITE_PRIVATE void sqlite3PageFree(void*);
   11490 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   11491 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   11492 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
   11493 
   11494 /*
   11495 ** On systems with ample stack space and that support alloca(), make
   11496 ** use of alloca() to obtain space for large automatic objects.  By default,
   11497 ** obtain space from malloc().
   11498 **
   11499 ** The alloca() routine never returns NULL.  This will cause code paths
   11500 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   11501 */
   11502 #ifdef SQLITE_USE_ALLOCA
   11503 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   11504 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   11505 # define sqlite3StackFree(D,P)
   11506 #else
   11507 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   11508 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   11509 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   11510 #endif
   11511 
   11512 #ifdef SQLITE_ENABLE_MEMSYS3
   11513 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   11514 #endif
   11515 #ifdef SQLITE_ENABLE_MEMSYS5
   11516 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   11517 #endif
   11518 
   11519 
   11520 #ifndef SQLITE_MUTEX_OMIT
   11521 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
   11522 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
   11523 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   11524 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   11525 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   11526 #endif
   11527 
   11528 SQLITE_PRIVATE int sqlite3StatusValue(int);
   11529 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
   11530 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
   11531 
   11532 #ifndef SQLITE_OMIT_FLOATING_POINT
   11533 SQLITE_PRIVATE   int sqlite3IsNaN(double);
   11534 #else
   11535 # define sqlite3IsNaN(X)  0
   11536 #endif
   11537 
   11538 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
   11539 #ifndef SQLITE_OMIT_TRACE
   11540 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
   11541 #endif
   11542 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   11543 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   11544 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
   11545 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   11546 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   11547 #endif
   11548 #if defined(SQLITE_TEST)
   11549 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   11550 #endif
   11551 
   11552 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
   11553 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   11554 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
   11555 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
   11556 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
   11557 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
   11558 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
   11559 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
   11560 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
   11561 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
   11562 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
   11563 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
   11564 #else
   11565 # define sqlite3ExplainBegin(X)
   11566 # define sqlite3ExplainSelect(A,B)
   11567 # define sqlite3ExplainExpr(A,B)
   11568 # define sqlite3ExplainExprList(A,B)
   11569 # define sqlite3ExplainFinish(X)
   11570 # define sqlite3VdbeExplanation(X) 0
   11571 #endif
   11572 
   11573 
   11574 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
   11575 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   11576 SQLITE_PRIVATE int sqlite3Dequote(char*);
   11577 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   11578 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   11579 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   11580 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   11581 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   11582 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   11583 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   11584 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
   11585 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   11586 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   11587 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   11588 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
   11589 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   11590 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   11591 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
   11592 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   11593 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   11594 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   11595 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
   11596 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   11597 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   11598 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   11599 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   11600 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
   11601 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
   11602 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   11603 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   11604 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   11605 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   11606 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
   11607 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   11608 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   11609 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   11610 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
   11611 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
   11612 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   11613 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
   11614 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
   11615                     sqlite3_vfs**,char**,char **);
   11616 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
   11617 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
   11618 
   11619 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   11620 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   11621 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   11622 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   11623 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   11624 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   11625 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   11626 
   11627 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   11628 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   11629 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   11630 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
   11631 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   11632 
   11633 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
   11634 
   11635 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   11636 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   11637 #else
   11638 # define sqlite3ViewGetColumnNames(A,B) 0
   11639 #endif
   11640 
   11641 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   11642 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
   11643 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
   11644 #ifndef SQLITE_OMIT_AUTOINCREMENT
   11645 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   11646 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   11647 #else
   11648 # define sqlite3AutoincrementBegin(X)
   11649 # define sqlite3AutoincrementEnd(X)
   11650 #endif
   11651 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
   11652 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
   11653 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   11654 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   11655 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   11656 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   11657 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   11658                                       Token*, Select*, Expr*, IdList*);
   11659 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   11660 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   11661 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   11662 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   11663 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   11664 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   11665 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   11666                         Token*, int, int);
   11667 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   11668 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   11669 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   11670                          Expr*,ExprList*,int,Expr*,Expr*);
   11671 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   11672 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   11673 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   11674 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   11675 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   11676 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
   11677 #endif
   11678 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
   11679 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
   11680 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
   11681 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   11682 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
   11683 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
   11684 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   11685 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
   11686 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   11687 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   11688 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
   11689 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   11690 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   11691 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   11692 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
   11693 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   11694 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   11695 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   11696 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
   11697 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
   11698 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   11699 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   11700 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   11701 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
   11702 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   11703 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   11704 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   11705 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
   11706 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
   11707 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   11708 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
   11709 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
   11710 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   11711 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   11712 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   11713 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   11714 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   11715 SQLITE_PRIVATE void sqlite3PrngResetState(void);
   11716 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
   11717 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   11718 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
   11719 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   11720 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
   11721 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
   11722 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   11723 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   11724 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   11725 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   11726 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
   11727 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   11728 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   11729 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
   11730 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   11731 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   11732 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
   11733 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
   11734 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
   11735 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
   11736                                      int*,int,int,int,int,int*);
   11737 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
   11738 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
   11739 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   11740 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   11741 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   11742 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
   11743 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   11744 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   11745 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   11746 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   11747 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   11748 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
   11749 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
   11750 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
   11751 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   11752 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
   11753 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   11754 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   11755 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   11756 
   11757 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   11758 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
   11759 #endif
   11760 
   11761 #ifndef SQLITE_OMIT_TRIGGER
   11762 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   11763                            Expr*,int, int);
   11764 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   11765 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   11766 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   11767 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   11768 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   11769 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   11770                             int, int, int);
   11771 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   11772   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   11773 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   11774 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
   11775 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   11776                                         ExprList*,Select*,u8);
   11777 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
   11778 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
   11779 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   11780 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   11781 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   11782 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   11783 #else
   11784 # define sqlite3TriggersExist(B,C,D,E,F) 0
   11785 # define sqlite3DeleteTrigger(A,B)
   11786 # define sqlite3DropTriggerPtr(A,B)
   11787 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   11788 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   11789 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   11790 # define sqlite3TriggerList(X, Y) 0
   11791 # define sqlite3ParseToplevel(p) p
   11792 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   11793 #endif
   11794 
   11795 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   11796 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   11797 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   11798 #ifndef SQLITE_OMIT_AUTHORIZATION
   11799 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   11800 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   11801 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   11802 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   11803 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   11804 #else
   11805 # define sqlite3AuthRead(a,b,c,d)
   11806 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   11807 # define sqlite3AuthContextPush(a,b,c)
   11808 # define sqlite3AuthContextPop(a)  ((void)(a))
   11809 #endif
   11810 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   11811 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   11812 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   11813 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   11814 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   11815 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   11816 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   11817 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   11818 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
   11819 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   11820 SQLITE_PRIVATE int sqlite3Atoi(const char*);
   11821 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   11822 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   11823 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
   11824 
   11825 /*
   11826 ** Routines to read and write variable-length integers.  These used to
   11827 ** be defined locally, but now we use the varint routines in the util.c
   11828 ** file.  Code should use the MACRO forms below, as the Varint32 versions
   11829 ** are coded to assume the single byte case is already handled (which
   11830 ** the MACRO form does).
   11831 */
   11832 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   11833 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
   11834 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   11835 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   11836 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   11837 
   11838 /*
   11839 ** The header of a record consists of a sequence variable-length integers.
   11840 ** These integers are almost always small and are encoded as a single byte.
   11841 ** The following macros take advantage this fact to provide a fast encode
   11842 ** and decode of the integers in a record header.  It is faster for the common
   11843 ** case where the integer is a single byte.  It is a little slower when the
   11844 ** integer is two or more bytes.  But overall it is faster.
   11845 **
   11846 ** The following expressions are equivalent:
   11847 **
   11848 **     x = sqlite3GetVarint32( A, &B );
   11849 **     x = sqlite3PutVarint32( A, B );
   11850 **
   11851 **     x = getVarint32( A, B );
   11852 **     x = putVarint32( A, B );
   11853 **
   11854 */
   11855 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
   11856 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
   11857 #define getVarint    sqlite3GetVarint
   11858 #define putVarint    sqlite3PutVarint
   11859 
   11860 
   11861 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
   11862 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
   11863 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   11864 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   11865 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   11866 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
   11867 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
   11868 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   11869 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
   11870 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   11871 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   11872 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   11873 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   11874 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   11875 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   11876 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
   11877 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
   11878 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   11879 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   11880 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   11881 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
   11882 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
   11883 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
   11884 SQLITE_PRIVATE int sqlite3AbsInt32(int);
   11885 #ifdef SQLITE_ENABLE_8_3_NAMES
   11886 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
   11887 #else
   11888 # define sqlite3FileSuffix3(X,Y)
   11889 #endif
   11890 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
   11891 
   11892 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   11893 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   11894 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   11895                         void(*)(void*));
   11896 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   11897 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   11898 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
   11899 #ifdef SQLITE_ENABLE_STAT3
   11900 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
   11901 #endif
   11902 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   11903 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   11904 #ifndef SQLITE_AMALGAMATION
   11905 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   11906 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   11907 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   11908 SQLITE_PRIVATE const Token sqlite3IntTokens[];
   11909 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   11910 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   11911 #ifndef SQLITE_OMIT_WSD
   11912 SQLITE_PRIVATE int sqlite3PendingByte;
   11913 #endif
   11914 #endif
   11915 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
   11916 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   11917 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
   11918 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   11919 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   11920 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   11921 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   11922 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
   11923 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   11924 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   11925 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   11926 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   11927 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   11928 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   11929 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   11930 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
   11931 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
   11932 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   11933 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   11934 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   11935 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   11936 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   11937 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
   11938 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   11939 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   11940 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   11941 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
   11942 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
   11943 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   11944 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   11945 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
   11946 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   11947   void (*)(sqlite3_context*,int,sqlite3_value **),
   11948   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
   11949   FuncDestructor *pDestructor
   11950 );
   11951 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   11952 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   11953 
   11954 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
   11955 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   11956 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
   11957 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   11958 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   11959 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   11960 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   11961 
   11962 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   11963 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   11964 
   11965 /*
   11966 ** The interface to the LEMON-generated parser
   11967 */
   11968 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
   11969 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
   11970 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   11971 #ifdef YYTRACKMAXSTACKDEPTH
   11972 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   11973 #endif
   11974 
   11975 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   11976 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   11977 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   11978 #else
   11979 # define sqlite3CloseExtensions(X)
   11980 #endif
   11981 
   11982 #ifndef SQLITE_OMIT_SHARED_CACHE
   11983 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   11984 #else
   11985   #define sqlite3TableLock(v,w,x,y,z)
   11986 #endif
   11987 
   11988 #ifdef SQLITE_TEST
   11989 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   11990 #endif
   11991 
   11992 #ifdef SQLITE_OMIT_VIRTUALTABLE
   11993 #  define sqlite3VtabClear(Y)
   11994 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   11995 #  define sqlite3VtabRollback(X)
   11996 #  define sqlite3VtabCommit(X)
   11997 #  define sqlite3VtabInSync(db) 0
   11998 #  define sqlite3VtabLock(X)
   11999 #  define sqlite3VtabUnlock(X)
   12000 #  define sqlite3VtabUnlockList(X)
   12001 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
   12002 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
   12003 #else
   12004 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
   12005 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
   12006 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   12007 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   12008 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   12009 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   12010 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   12011 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
   12012 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
   12013 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   12014 #endif
   12015 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   12016 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
   12017 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   12018 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   12019 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   12020 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   12021 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   12022 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   12023 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   12024 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   12025 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   12026 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   12027 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   12028 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   12029 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   12030 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   12031 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   12032 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
   12033 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
   12034 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
   12035 
   12036 /* Declarations for functions in fkey.c. All of these are replaced by
   12037 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   12038 ** key functionality is available. If OMIT_TRIGGER is defined but
   12039 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   12040 ** this case foreign keys are parsed, but no other functionality is
   12041 ** provided (enforcement of FK constraints requires the triggers sub-system).
   12042 */
   12043 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   12044 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
   12045 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   12046 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
   12047 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   12048 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   12049 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   12050 #else
   12051   #define sqlite3FkActions(a,b,c,d)
   12052   #define sqlite3FkCheck(a,b,c,d)
   12053   #define sqlite3FkDropTable(a,b,c)
   12054   #define sqlite3FkOldmask(a,b)      0
   12055   #define sqlite3FkRequired(a,b,c,d) 0
   12056 #endif
   12057 #ifndef SQLITE_OMIT_FOREIGN_KEY
   12058 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
   12059 #else
   12060   #define sqlite3FkDelete(a,b)
   12061 #endif
   12062 
   12063 
   12064 /*
   12065 ** Available fault injectors.  Should be numbered beginning with 0.
   12066 */
   12067 #define SQLITE_FAULTINJECTOR_MALLOC     0
   12068 #define SQLITE_FAULTINJECTOR_COUNT      1
   12069 
   12070 /*
   12071 ** The interface to the code in fault.c used for identifying "benign"
   12072 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
   12073 ** is not defined.
   12074 */
   12075 #ifndef SQLITE_OMIT_BUILTIN_TEST
   12076 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   12077 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   12078 #else
   12079   #define sqlite3BeginBenignMalloc()
   12080   #define sqlite3EndBenignMalloc()
   12081 #endif
   12082 
   12083 #define IN_INDEX_ROWID           1
   12084 #define IN_INDEX_EPH             2
   12085 #define IN_INDEX_INDEX           3
   12086 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
   12087 
   12088 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   12089 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   12090 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
   12091 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   12092 #else
   12093   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
   12094 #endif
   12095 
   12096 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   12097 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
   12098 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
   12099 
   12100 #if SQLITE_MAX_EXPR_DEPTH>0
   12101 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
   12102 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   12103 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   12104 #else
   12105   #define sqlite3ExprSetHeight(x,y)
   12106   #define sqlite3SelectExprHeight(x) 0
   12107   #define sqlite3ExprCheckHeight(x,y)
   12108 #endif
   12109 
   12110 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   12111 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   12112 
   12113 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   12114 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   12115 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   12116 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   12117 #else
   12118   #define sqlite3ConnectionBlocked(x,y)
   12119   #define sqlite3ConnectionUnlocked(x)
   12120   #define sqlite3ConnectionClosed(x)
   12121 #endif
   12122 
   12123 #ifdef SQLITE_DEBUG
   12124 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   12125 #endif
   12126 
   12127 /*
   12128 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   12129 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   12130 ** print I/O tracing messages.
   12131 */
   12132 #ifdef SQLITE_ENABLE_IOTRACE
   12133 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   12134 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   12135 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
   12136 #else
   12137 # define IOTRACE(A)
   12138 # define sqlite3VdbeIOTraceSql(X)
   12139 #endif
   12140 
   12141 /*
   12142 ** These routines are available for the mem2.c debugging memory allocator
   12143 ** only.  They are used to verify that different "types" of memory
   12144 ** allocations are properly tracked by the system.
   12145 **
   12146 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
   12147 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
   12148 ** a single bit set.
   12149 **
   12150 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
   12151 ** argument match the type set by the previous sqlite3MemdebugSetType().
   12152 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
   12153 **
   12154 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
   12155 ** argument match the type set by the previous sqlite3MemdebugSetType().
   12156 **
   12157 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
   12158 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
   12159 ** it might have been allocated by lookaside, except the allocation was
   12160 ** too large or lookaside was already full.  It is important to verify
   12161 ** that allocations that might have been satisfied by lookaside are not
   12162 ** passed back to non-lookaside free() routines.  Asserts such as the
   12163 ** example above are placed on the non-lookaside free() routines to verify
   12164 ** this constraint.
   12165 **
   12166 ** All of this is no-op for a production build.  It only comes into
   12167 ** play when the SQLITE_MEMDEBUG compile-time option is used.
   12168 */
   12169 #ifdef SQLITE_MEMDEBUG
   12170 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
   12171 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
   12172 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
   12173 #else
   12174 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
   12175 # define sqlite3MemdebugHasType(X,Y)  1
   12176 # define sqlite3MemdebugNoType(X,Y)   1
   12177 #endif
   12178 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
   12179 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
   12180 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
   12181 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
   12182 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
   12183 
   12184 #endif /* _SQLITEINT_H_ */
   12185 
   12186 /************** End of sqliteInt.h *******************************************/
   12187 /************** Begin file global.c ******************************************/
   12188 /*
   12189 ** 2008 June 13
   12190 **
   12191 ** The author disclaims copyright to this source code.  In place of
   12192 ** a legal notice, here is a blessing:
   12193 **
   12194 **    May you do good and not evil.
   12195 **    May you find forgiveness for yourself and forgive others.
   12196 **    May you share freely, never taking more than you give.
   12197 **
   12198 *************************************************************************
   12199 **
   12200 ** This file contains definitions of global variables and contants.
   12201 */
   12202 
   12203 /* An array to map all upper-case characters into their corresponding
   12204 ** lower-case character.
   12205 **
   12206 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   12207 ** handle case conversions for the UTF character set since the tables
   12208 ** involved are nearly as big or bigger than SQLite itself.
   12209 */
   12210 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   12211 #ifdef SQLITE_ASCII
   12212       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   12213      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   12214      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   12215      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   12216     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   12217     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   12218     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   12219     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   12220     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   12221     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   12222     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   12223     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   12224     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   12225     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   12226     252,253,254,255
   12227 #endif
   12228 #ifdef SQLITE_EBCDIC
   12229       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   12230      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   12231      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   12232      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   12233      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   12234      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   12235      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
   12236     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
   12237     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   12238     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
   12239     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   12240     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   12241     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   12242     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   12243     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
   12244     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
   12245 #endif
   12246 };
   12247 
   12248 /*
   12249 ** The following 256 byte lookup table is used to support SQLites built-in
   12250 ** equivalents to the following standard library functions:
   12251 **
   12252 **   isspace()                        0x01
   12253 **   isalpha()                        0x02
   12254 **   isdigit()                        0x04
   12255 **   isalnum()                        0x06
   12256 **   isxdigit()                       0x08
   12257 **   toupper()                        0x20
   12258 **   SQLite identifier character      0x40
   12259 **
   12260 ** Bit 0x20 is set if the mapped character requires translation to upper
   12261 ** case. i.e. if the character is a lower-case ASCII character.
   12262 ** If x is a lower-case ASCII character, then its upper-case equivalent
   12263 ** is (x - 0x20). Therefore toupper() can be implemented as:
   12264 **
   12265 **   (x & ~(map[x]&0x20))
   12266 **
   12267 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
   12268 ** array. tolower() is used more often than toupper() by SQLite.
   12269 **
   12270 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
   12271 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   12272 ** non-ASCII UTF character. Hence the test for whether or not a character is
   12273 ** part of an identifier is 0x46.
   12274 **
   12275 ** SQLite's versions are identical to the standard versions assuming a
   12276 ** locale of "C". They are implemented as macros in sqliteInt.h.
   12277 */
   12278 #ifdef SQLITE_ASCII
   12279 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   12280   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   12281   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   12282   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   12283   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   12284   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
   12285   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   12286   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   12287   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   12288 
   12289   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   12290   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   12291   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   12292   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   12293   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   12294   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   12295   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   12296   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   12297 
   12298   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   12299   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   12300   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   12301   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   12302   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   12303   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   12304   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   12305   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   12306 
   12307   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   12308   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   12309   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   12310   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   12311   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   12312   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   12313   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   12314   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   12315 };
   12316 #endif
   12317 
   12318 #ifndef SQLITE_USE_URI
   12319 # define  SQLITE_USE_URI 0
   12320 #endif
   12321 
   12322 /*
   12323 ** The following singleton contains the global configuration for
   12324 ** the SQLite library.
   12325 */
   12326 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   12327    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   12328    1,                         /* bCoreMutex */
   12329    SQLITE_THREADSAFE==1,      /* bFullMutex */
   12330    SQLITE_USE_URI,            /* bOpenUri */
   12331    0x7ffffffe,                /* mxStrlen */
   12332    128,                       /* szLookaside */
   12333    500,                       /* nLookaside */
   12334    {0,0,0,0,0,0,0,0},         /* m */
   12335    {0,0,0,0,0,0,0,0,0},       /* mutex */
   12336    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
   12337    (void*)0,                  /* pHeap */
   12338    0,                         /* nHeap */
   12339    0, 0,                      /* mnHeap, mxHeap */
   12340    (void*)0,                  /* pScratch */
   12341    0,                         /* szScratch */
   12342    0,                         /* nScratch */
   12343    (void*)0,                  /* pPage */
   12344    0,                         /* szPage */
   12345    0,                         /* nPage */
   12346    0,                         /* mxParserStack */
   12347    0,                         /* sharedCacheEnabled */
   12348    /* All the rest should always be initialized to zero */
   12349    0,                         /* isInit */
   12350    0,                         /* inProgress */
   12351    0,                         /* isMutexInit */
   12352    0,                         /* isMallocInit */
   12353    0,                         /* isPCacheInit */
   12354    0,                         /* pInitMutex */
   12355    0,                         /* nRefInitMutex */
   12356    0,                         /* xLog */
   12357    0,                         /* pLogArg */
   12358    0,                         /* bLocaltimeFault */
   12359 };
   12360 
   12361 
   12362 /*
   12363 ** Hash table for global functions - functions common to all
   12364 ** database connections.  After initialization, this table is
   12365 ** read-only.
   12366 */
   12367 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   12368 
   12369 /*
   12370 ** Constant tokens for values 0 and 1.
   12371 */
   12372 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
   12373    { "0", 1 },
   12374    { "1", 1 }
   12375 };
   12376 
   12377 
   12378 /*
   12379 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   12380 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   12381 ** the database page that contains the pending byte.  It never attempts
   12382 ** to read or write that page.  The pending byte page is set assign
   12383 ** for use by the VFS layers as space for managing file locks.
   12384 **
   12385 ** During testing, it is often desirable to move the pending byte to
   12386 ** a different position in the file.  This allows code that has to
   12387 ** deal with the pending byte to run on files that are much smaller
   12388 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   12389 ** move the pending byte.
   12390 **
   12391 ** IMPORTANT:  Changing the pending byte to any value other than
   12392 ** 0x40000000 results in an incompatible database file format!
   12393 ** Changing the pending byte during operating results in undefined
   12394 ** and dileterious behavior.
   12395 */
   12396 #ifndef SQLITE_OMIT_WSD
   12397 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   12398 #endif
   12399 
   12400 /*
   12401 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   12402 ** created by mkopcodeh.awk during compilation.  Data is obtained
   12403 ** from the comments following the "case OP_xxxx:" statements in
   12404 ** the vdbe.c file.
   12405 */
   12406 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   12407 
   12408 /************** End of global.c **********************************************/
   12409 /************** Begin file ctime.c *******************************************/
   12410 /*
   12411 ** 2010 February 23
   12412 **
   12413 ** The author disclaims copyright to this source code.  In place of
   12414 ** a legal notice, here is a blessing:
   12415 **
   12416 **    May you do good and not evil.
   12417 **    May you find forgiveness for yourself and forgive others.
   12418 **    May you share freely, never taking more than you give.
   12419 **
   12420 *************************************************************************
   12421 **
   12422 ** This file implements routines used to report what compile-time options
   12423 ** SQLite was built with.
   12424 */
   12425 
   12426 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   12427 
   12428 
   12429 /*
   12430 ** An array of names of all compile-time options.  This array should
   12431 ** be sorted A-Z.
   12432 **
   12433 ** This array looks large, but in a typical installation actually uses
   12434 ** only a handful of compile-time options, so most times this array is usually
   12435 ** rather short and uses little memory space.
   12436 */
   12437 static const char * const azCompileOpt[] = {
   12438 
   12439 /* These macros are provided to "stringify" the value of the define
   12440 ** for those options in which the value is meaningful. */
   12441 #define CTIMEOPT_VAL_(opt) #opt
   12442 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
   12443 
   12444 #ifdef SQLITE_32BIT_ROWID
   12445   "32BIT_ROWID",
   12446 #endif
   12447 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   12448   "4_BYTE_ALIGNED_MALLOC",
   12449 #endif
   12450 #ifdef SQLITE_CASE_SENSITIVE_LIKE
   12451   "CASE_SENSITIVE_LIKE",
   12452 #endif
   12453 #ifdef SQLITE_CHECK_PAGES
   12454   "CHECK_PAGES",
   12455 #endif
   12456 #ifdef SQLITE_COVERAGE_TEST
   12457   "COVERAGE_TEST",
   12458 #endif
   12459 #ifdef SQLITE_DEBUG
   12460   "DEBUG",
   12461 #endif
   12462 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   12463   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
   12464 #endif
   12465 #ifdef SQLITE_DISABLE_DIRSYNC
   12466   "DISABLE_DIRSYNC",
   12467 #endif
   12468 #ifdef SQLITE_DISABLE_LFS
   12469   "DISABLE_LFS",
   12470 #endif
   12471 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   12472   "ENABLE_ATOMIC_WRITE",
   12473 #endif
   12474 #ifdef SQLITE_ENABLE_CEROD
   12475   "ENABLE_CEROD",
   12476 #endif
   12477 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   12478   "ENABLE_COLUMN_METADATA",
   12479 #endif
   12480 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   12481   "ENABLE_EXPENSIVE_ASSERT",
   12482 #endif
   12483 #ifdef SQLITE_ENABLE_FTS1
   12484   "ENABLE_FTS1",
   12485 #endif
   12486 #ifdef SQLITE_ENABLE_FTS2
   12487   "ENABLE_FTS2",
   12488 #endif
   12489 #ifdef SQLITE_ENABLE_FTS3
   12490   "ENABLE_FTS3",
   12491 #endif
   12492 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   12493   "ENABLE_FTS3_PARENTHESIS",
   12494 #endif
   12495 #ifdef SQLITE_ENABLE_FTS4
   12496   "ENABLE_FTS4",
   12497 #endif
   12498 #ifdef SQLITE_ENABLE_ICU
   12499   "ENABLE_ICU",
   12500 #endif
   12501 #ifdef SQLITE_ENABLE_IOTRACE
   12502   "ENABLE_IOTRACE",
   12503 #endif
   12504 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   12505   "ENABLE_LOAD_EXTENSION",
   12506 #endif
   12507 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   12508   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
   12509 #endif
   12510 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   12511   "ENABLE_MEMORY_MANAGEMENT",
   12512 #endif
   12513 #ifdef SQLITE_ENABLE_MEMSYS3
   12514   "ENABLE_MEMSYS3",
   12515 #endif
   12516 #ifdef SQLITE_ENABLE_MEMSYS5
   12517   "ENABLE_MEMSYS5",
   12518 #endif
   12519 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   12520   "ENABLE_OVERSIZE_CELL_CHECK",
   12521 #endif
   12522 #ifdef SQLITE_ENABLE_RTREE
   12523   "ENABLE_RTREE",
   12524 #endif
   12525 #ifdef SQLITE_ENABLE_STAT3
   12526   "ENABLE_STAT3",
   12527 #endif
   12528 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   12529   "ENABLE_UNLOCK_NOTIFY",
   12530 #endif
   12531 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   12532   "ENABLE_UPDATE_DELETE_LIMIT",
   12533 #endif
   12534 #ifdef SQLITE_HAS_CODEC
   12535   "HAS_CODEC",
   12536 #endif
   12537 #ifdef SQLITE_HAVE_ISNAN
   12538   "HAVE_ISNAN",
   12539 #endif
   12540 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   12541   "HOMEGROWN_RECURSIVE_MUTEX",
   12542 #endif
   12543 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   12544   "IGNORE_AFP_LOCK_ERRORS",
   12545 #endif
   12546 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   12547   "IGNORE_FLOCK_LOCK_ERRORS",
   12548 #endif
   12549 #ifdef SQLITE_INT64_TYPE
   12550   "INT64_TYPE",
   12551 #endif
   12552 #ifdef SQLITE_LOCK_TRACE
   12553   "LOCK_TRACE",
   12554 #endif
   12555 #ifdef SQLITE_MAX_SCHEMA_RETRY
   12556   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
   12557 #endif
   12558 #ifdef SQLITE_MEMDEBUG
   12559   "MEMDEBUG",
   12560 #endif
   12561 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   12562   "MIXED_ENDIAN_64BIT_FLOAT",
   12563 #endif
   12564 #ifdef SQLITE_NO_SYNC
   12565   "NO_SYNC",
   12566 #endif
   12567 #ifdef SQLITE_OMIT_ALTERTABLE
   12568   "OMIT_ALTERTABLE",
   12569 #endif
   12570 #ifdef SQLITE_OMIT_ANALYZE
   12571   "OMIT_ANALYZE",
   12572 #endif
   12573 #ifdef SQLITE_OMIT_ATTACH
   12574   "OMIT_ATTACH",
   12575 #endif
   12576 #ifdef SQLITE_OMIT_AUTHORIZATION
   12577   "OMIT_AUTHORIZATION",
   12578 #endif
   12579 #ifdef SQLITE_OMIT_AUTOINCREMENT
   12580   "OMIT_AUTOINCREMENT",
   12581 #endif
   12582 #ifdef SQLITE_OMIT_AUTOINIT
   12583   "OMIT_AUTOINIT",
   12584 #endif
   12585 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
   12586   "OMIT_AUTOMATIC_INDEX",
   12587 #endif
   12588 #ifdef SQLITE_OMIT_AUTORESET
   12589   "OMIT_AUTORESET",
   12590 #endif
   12591 #ifdef SQLITE_OMIT_AUTOVACUUM
   12592   "OMIT_AUTOVACUUM",
   12593 #endif
   12594 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   12595   "OMIT_BETWEEN_OPTIMIZATION",
   12596 #endif
   12597 #ifdef SQLITE_OMIT_BLOB_LITERAL
   12598   "OMIT_BLOB_LITERAL",
   12599 #endif
   12600 #ifdef SQLITE_OMIT_BTREECOUNT
   12601   "OMIT_BTREECOUNT",
   12602 #endif
   12603 #ifdef SQLITE_OMIT_BUILTIN_TEST
   12604   "OMIT_BUILTIN_TEST",
   12605 #endif
   12606 #ifdef SQLITE_OMIT_CAST
   12607   "OMIT_CAST",
   12608 #endif
   12609 #ifdef SQLITE_OMIT_CHECK
   12610   "OMIT_CHECK",
   12611 #endif
   12612 /* // redundant
   12613 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
   12614 **   "OMIT_COMPILEOPTION_DIAGS",
   12615 ** #endif
   12616 */
   12617 #ifdef SQLITE_OMIT_COMPLETE
   12618   "OMIT_COMPLETE",
   12619 #endif
   12620 #ifdef SQLITE_OMIT_COMPOUND_SELECT
   12621   "OMIT_COMPOUND_SELECT",
   12622 #endif
   12623 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   12624   "OMIT_DATETIME_FUNCS",
   12625 #endif
   12626 #ifdef SQLITE_OMIT_DECLTYPE
   12627   "OMIT_DECLTYPE",
   12628 #endif
   12629 #ifdef SQLITE_OMIT_DEPRECATED
   12630   "OMIT_DEPRECATED",
   12631 #endif
   12632 #ifdef SQLITE_OMIT_DISKIO
   12633   "OMIT_DISKIO",
   12634 #endif
   12635 #ifdef SQLITE_OMIT_EXPLAIN
   12636   "OMIT_EXPLAIN",
   12637 #endif
   12638 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
   12639   "OMIT_FLAG_PRAGMAS",
   12640 #endif
   12641 #ifdef SQLITE_OMIT_FLOATING_POINT
   12642   "OMIT_FLOATING_POINT",
   12643 #endif
   12644 #ifdef SQLITE_OMIT_FOREIGN_KEY
   12645   "OMIT_FOREIGN_KEY",
   12646 #endif
   12647 #ifdef SQLITE_OMIT_GET_TABLE
   12648   "OMIT_GET_TABLE",
   12649 #endif
   12650 #ifdef SQLITE_OMIT_INCRBLOB
   12651   "OMIT_INCRBLOB",
   12652 #endif
   12653 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
   12654   "OMIT_INTEGRITY_CHECK",
   12655 #endif
   12656 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
   12657   "OMIT_LIKE_OPTIMIZATION",
   12658 #endif
   12659 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   12660   "OMIT_LOAD_EXTENSION",
   12661 #endif
   12662 #ifdef SQLITE_OMIT_LOCALTIME
   12663   "OMIT_LOCALTIME",
   12664 #endif
   12665 #ifdef SQLITE_OMIT_LOOKASIDE
   12666   "OMIT_LOOKASIDE",
   12667 #endif
   12668 #ifdef SQLITE_OMIT_MEMORYDB
   12669   "OMIT_MEMORYDB",
   12670 #endif
   12671 #ifdef SQLITE_OMIT_MERGE_SORT
   12672   "OMIT_MERGE_SORT",
   12673 #endif
   12674 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
   12675   "OMIT_OR_OPTIMIZATION",
   12676 #endif
   12677 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
   12678   "OMIT_PAGER_PRAGMAS",
   12679 #endif
   12680 #ifdef SQLITE_OMIT_PRAGMA
   12681   "OMIT_PRAGMA",
   12682 #endif
   12683 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   12684   "OMIT_PROGRESS_CALLBACK",
   12685 #endif
   12686 #ifdef SQLITE_OMIT_QUICKBALANCE
   12687   "OMIT_QUICKBALANCE",
   12688 #endif
   12689 #ifdef SQLITE_OMIT_REINDEX
   12690   "OMIT_REINDEX",
   12691 #endif
   12692 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
   12693   "OMIT_SCHEMA_PRAGMAS",
   12694 #endif
   12695 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   12696   "OMIT_SCHEMA_VERSION_PRAGMAS",
   12697 #endif
   12698 #ifdef SQLITE_OMIT_SHARED_CACHE
   12699   "OMIT_SHARED_CACHE",
   12700 #endif
   12701 #ifdef SQLITE_OMIT_SUBQUERY
   12702   "OMIT_SUBQUERY",
   12703 #endif
   12704 #ifdef SQLITE_OMIT_TCL_VARIABLE
   12705   "OMIT_TCL_VARIABLE",
   12706 #endif
   12707 #ifdef SQLITE_OMIT_TEMPDB
   12708   "OMIT_TEMPDB",
   12709 #endif
   12710 #ifdef SQLITE_OMIT_TRACE
   12711   "OMIT_TRACE",
   12712 #endif
   12713 #ifdef SQLITE_OMIT_TRIGGER
   12714   "OMIT_TRIGGER",
   12715 #endif
   12716 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   12717   "OMIT_TRUNCATE_OPTIMIZATION",
   12718 #endif
   12719 #ifdef SQLITE_OMIT_UTF16
   12720   "OMIT_UTF16",
   12721 #endif
   12722 #ifdef SQLITE_OMIT_VACUUM
   12723   "OMIT_VACUUM",
   12724 #endif
   12725 #ifdef SQLITE_OMIT_VIEW
   12726   "OMIT_VIEW",
   12727 #endif
   12728 #ifdef SQLITE_OMIT_VIRTUALTABLE
   12729   "OMIT_VIRTUALTABLE",
   12730 #endif
   12731 #ifdef SQLITE_OMIT_WAL
   12732   "OMIT_WAL",
   12733 #endif
   12734 #ifdef SQLITE_OMIT_WSD
   12735   "OMIT_WSD",
   12736 #endif
   12737 #ifdef SQLITE_OMIT_XFER_OPT
   12738   "OMIT_XFER_OPT",
   12739 #endif
   12740 #ifdef SQLITE_PERFORMANCE_TRACE
   12741   "PERFORMANCE_TRACE",
   12742 #endif
   12743 #ifdef SQLITE_PROXY_DEBUG
   12744   "PROXY_DEBUG",
   12745 #endif
   12746 #ifdef SQLITE_SECURE_DELETE
   12747   "SECURE_DELETE",
   12748 #endif
   12749 #ifdef SQLITE_SMALL_STACK
   12750   "SMALL_STACK",
   12751 #endif
   12752 #ifdef SQLITE_SOUNDEX
   12753   "SOUNDEX",
   12754 #endif
   12755 #ifdef SQLITE_TCL
   12756   "TCL",
   12757 #endif
   12758 #ifdef SQLITE_TEMP_STORE
   12759   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
   12760 #endif
   12761 #ifdef SQLITE_TEST
   12762   "TEST",
   12763 #endif
   12764 #ifdef SQLITE_THREADSAFE
   12765   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
   12766 #endif
   12767 #ifdef SQLITE_USE_ALLOCA
   12768   "USE_ALLOCA",
   12769 #endif
   12770 #ifdef SQLITE_ZERO_MALLOC
   12771   "ZERO_MALLOC"
   12772 #endif
   12773 };
   12774 
   12775 /*
   12776 ** Given the name of a compile-time option, return true if that option
   12777 ** was used and false if not.
   12778 **
   12779 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
   12780 ** is not required for a match.
   12781 */
   12782 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   12783   int i, n;
   12784   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   12785   n = sqlite3Strlen30(zOptName);
   12786 
   12787   /* Since ArraySize(azCompileOpt) is normally in single digits, a
   12788   ** linear search is adequate.  No need for a binary search. */
   12789   for(i=0; i<ArraySize(azCompileOpt); i++){
   12790     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
   12791        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
   12792   }
   12793   return 0;
   12794 }
   12795 
   12796 /*
   12797 ** Return the N-th compile-time option string.  If N is out of range,
   12798 ** return a NULL pointer.
   12799 */
   12800 SQLITE_API const char *sqlite3_compileoption_get(int N){
   12801   if( N>=0 && N<ArraySize(azCompileOpt) ){
   12802     return azCompileOpt[N];
   12803   }
   12804   return 0;
   12805 }
   12806 
   12807 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   12808 
   12809 /************** End of ctime.c ***********************************************/
   12810 /************** Begin file status.c ******************************************/
   12811 /*
   12812 ** 2008 June 18
   12813 **
   12814 ** The author disclaims copyright to this source code.  In place of
   12815 ** a legal notice, here is a blessing:
   12816 **
   12817 **    May you do good and not evil.
   12818 **    May you find forgiveness for yourself and forgive others.
   12819 **    May you share freely, never taking more than you give.
   12820 **
   12821 *************************************************************************
   12822 **
   12823 ** This module implements the sqlite3_status() interface and related
   12824 ** functionality.
   12825 */
   12826 /************** Include vdbeInt.h in the middle of status.c ******************/
   12827 /************** Begin file vdbeInt.h *****************************************/
   12828 /*
   12829 ** 2003 September 6
   12830 **
   12831 ** The author disclaims copyright to this source code.  In place of
   12832 ** a legal notice, here is a blessing:
   12833 **
   12834 **    May you do good and not evil.
   12835 **    May you find forgiveness for yourself and forgive others.
   12836 **    May you share freely, never taking more than you give.
   12837 **
   12838 *************************************************************************
   12839 ** This is the header file for information that is private to the
   12840 ** VDBE.  This information used to all be at the top of the single
   12841 ** source code file "vdbe.c".  When that file became too big (over
   12842 ** 6000 lines long) it was split up into several smaller files and
   12843 ** this header information was factored out.
   12844 */
   12845 #ifndef _VDBEINT_H_
   12846 #define _VDBEINT_H_
   12847 
   12848 /*
   12849 ** SQL is translated into a sequence of instructions to be
   12850 ** executed by a virtual machine.  Each instruction is an instance
   12851 ** of the following structure.
   12852 */
   12853 typedef struct VdbeOp Op;
   12854 
   12855 /*
   12856 ** Boolean values
   12857 */
   12858 typedef unsigned char Bool;
   12859 
   12860 /* Opaque type used by code in vdbesort.c */
   12861 typedef struct VdbeSorter VdbeSorter;
   12862 
   12863 /* Opaque type used by the explainer */
   12864 typedef struct Explain Explain;
   12865 
   12866 /*
   12867 ** A cursor is a pointer into a single BTree within a database file.
   12868 ** The cursor can seek to a BTree entry with a particular key, or
   12869 ** loop over all entries of the Btree.  You can also insert new BTree
   12870 ** entries or retrieve the key or data from the entry that the cursor
   12871 ** is currently pointing to.
   12872 **
   12873 ** Every cursor that the virtual machine has open is represented by an
   12874 ** instance of the following structure.
   12875 */
   12876 struct VdbeCursor {
   12877   BtCursor *pCursor;    /* The cursor structure of the backend */
   12878   Btree *pBt;           /* Separate file holding temporary table */
   12879   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
   12880   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
   12881   int pseudoTableReg;   /* Register holding pseudotable content. */
   12882   int nField;           /* Number of fields in the header */
   12883   Bool zeroed;          /* True if zeroed out and ready for reuse */
   12884   Bool rowidIsValid;    /* True if lastRowid is valid */
   12885   Bool atFirst;         /* True if pointing to first entry */
   12886   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
   12887   Bool nullRow;         /* True if pointing to a row with no data */
   12888   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
   12889   Bool isTable;         /* True if a table requiring integer keys */
   12890   Bool isIndex;         /* True if an index containing keys only - no data */
   12891   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
   12892   Bool isSorter;        /* True if a new-style sorter */
   12893   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
   12894   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
   12895   i64 seqCount;         /* Sequence counter */
   12896   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
   12897   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
   12898   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
   12899 
   12900   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
   12901   ** OP_IsUnique opcode on this cursor. */
   12902   int seekResult;
   12903 
   12904   /* Cached information about the header for the data record that the
   12905   ** cursor is currently pointing to.  Only valid if cacheStatus matches
   12906   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
   12907   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
   12908   ** the cache is out of date.
   12909   **
   12910   ** aRow might point to (ephemeral) data for the current row, or it might
   12911   ** be NULL.
   12912   */
   12913   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
   12914   int payloadSize;      /* Total number of bytes in the record */
   12915   u32 *aType;           /* Type values for all entries in the record */
   12916   u32 *aOffset;         /* Cached offsets to the start of each columns data */
   12917   u8 *aRow;             /* Data for the current row, if all on one page */
   12918 };
   12919 typedef struct VdbeCursor VdbeCursor;
   12920 
   12921 /*
   12922 ** When a sub-program is executed (OP_Program), a structure of this type
   12923 ** is allocated to store the current value of the program counter, as
   12924 ** well as the current memory cell array and various other frame specific
   12925 ** values stored in the Vdbe struct. When the sub-program is finished,
   12926 ** these values are copied back to the Vdbe from the VdbeFrame structure,
   12927 ** restoring the state of the VM to as it was before the sub-program
   12928 ** began executing.
   12929 **
   12930 ** The memory for a VdbeFrame object is allocated and managed by a memory
   12931 ** cell in the parent (calling) frame. When the memory cell is deleted or
   12932 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
   12933 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
   12934 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
   12935 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
   12936 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
   12937 ** child frame are released.
   12938 **
   12939 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
   12940 ** set to NULL if the currently executing frame is the main program.
   12941 */
   12942 typedef struct VdbeFrame VdbeFrame;
   12943 struct VdbeFrame {
   12944   Vdbe *v;                /* VM this frame belongs to */
   12945   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
   12946   Op *aOp;                /* Program instructions for parent frame */
   12947   Mem *aMem;              /* Array of memory cells for parent frame */
   12948   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
   12949   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
   12950   void *token;            /* Copy of SubProgram.token */
   12951   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
   12952   u16 nCursor;            /* Number of entries in apCsr */
   12953   int pc;                 /* Program Counter in parent (calling) frame */
   12954   int nOp;                /* Size of aOp array */
   12955   int nMem;               /* Number of entries in aMem */
   12956   int nOnceFlag;          /* Number of entries in aOnceFlag */
   12957   int nChildMem;          /* Number of memory cells for child frame */
   12958   int nChildCsr;          /* Number of cursors for child frame */
   12959   int nChange;            /* Statement changes (Vdbe.nChanges)     */
   12960 };
   12961 
   12962 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   12963 
   12964 /*
   12965 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
   12966 */
   12967 #define CACHE_STALE 0
   12968 
   12969 /*
   12970 ** Internally, the vdbe manipulates nearly all SQL values as Mem
   12971 ** structures. Each Mem struct may cache multiple representations (string,
   12972 ** integer etc.) of the same value.
   12973 */
   12974 struct Mem {
   12975   sqlite3 *db;        /* The associated database connection */
   12976   char *z;            /* String or BLOB value */
   12977   double r;           /* Real value */
   12978   union {
   12979     i64 i;              /* Integer value used when MEM_Int is set in flags */
   12980     int nZero;          /* Used when bit MEM_Zero is set in flags */
   12981     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   12982     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   12983     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   12984   } u;
   12985   int n;              /* Number of characters in string value, excluding '\0' */
   12986   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   12987   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
   12988   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
   12989 #ifdef SQLITE_DEBUG
   12990   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
   12991   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
   12992 #endif
   12993   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
   12994   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
   12995 };
   12996 
   12997 /* One or more of the following flags are set to indicate the validOK
   12998 ** representations of the value stored in the Mem struct.
   12999 **
   13000 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
   13001 ** No other flags may be set in this case.
   13002 **
   13003 ** If the MEM_Str flag is set then Mem.z points at a string representation.
   13004 ** Usually this is encoded in the same unicode encoding as the main
   13005 ** database (see below for exceptions). If the MEM_Term flag is also
   13006 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
   13007 ** flags may coexist with the MEM_Str flag.
   13008 */
   13009 #define MEM_Null      0x0001   /* Value is NULL */
   13010 #define MEM_Str       0x0002   /* Value is a string */
   13011 #define MEM_Int       0x0004   /* Value is an integer */
   13012 #define MEM_Real      0x0008   /* Value is a real number */
   13013 #define MEM_Blob      0x0010   /* Value is a BLOB */
   13014 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
   13015 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   13016 #define MEM_Invalid   0x0080   /* Value is undefined */
   13017 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
   13018 
   13019 /* Whenever Mem contains a valid string or blob representation, one of
   13020 ** the following flags must be set to determine the memory management
   13021 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   13022 ** string is \000 or \u0000 terminated
   13023 */
   13024 #define MEM_Term      0x0200   /* String rep is nul terminated */
   13025 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
   13026 #define MEM_Static    0x0800   /* Mem.z points to a static string */
   13027 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   13028 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   13029 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   13030 #ifdef SQLITE_OMIT_INCRBLOB
   13031   #undef MEM_Zero
   13032   #define MEM_Zero 0x0000
   13033 #endif
   13034 
   13035 /*
   13036 ** Clear any existing type flags from a Mem and replace them with f
   13037 */
   13038 #define MemSetTypeFlag(p, f) \
   13039    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
   13040 
   13041 /*
   13042 ** Return true if a memory cell is not marked as invalid.  This macro
   13043 ** is for use inside assert() statements only.
   13044 */
   13045 #ifdef SQLITE_DEBUG
   13046 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
   13047 #endif
   13048 
   13049 
   13050 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
   13051 ** additional information about auxiliary information bound to arguments
   13052 ** of the function.  This is used to implement the sqlite3_get_auxdata()
   13053 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
   13054 ** that can be associated with a constant argument to a function.  This
   13055 ** allows functions such as "regexp" to compile their constant regular
   13056 ** expression argument once and reused the compiled code for multiple
   13057 ** invocations.
   13058 */
   13059 struct VdbeFunc {
   13060   FuncDef *pFunc;               /* The definition of the function */
   13061   int nAux;                     /* Number of entries allocated for apAux[] */
   13062   struct AuxData {
   13063     void *pAux;                   /* Aux data for the i-th argument */
   13064     void (*xDelete)(void *);      /* Destructor for the aux data */
   13065   } apAux[1];                   /* One slot for each function argument */
   13066 };
   13067 
   13068 /*
   13069 ** The "context" argument for a installable function.  A pointer to an
   13070 ** instance of this structure is the first argument to the routines used
   13071 ** implement the SQL functions.
   13072 **
   13073 ** There is a typedef for this structure in sqlite.h.  So all routines,
   13074 ** even the public interface to SQLite, can use a pointer to this structure.
   13075 ** But this file is the only place where the internal details of this
   13076 ** structure are known.
   13077 **
   13078 ** This structure is defined inside of vdbeInt.h because it uses substructures
   13079 ** (Mem) which are only defined there.
   13080 */
   13081 struct sqlite3_context {
   13082   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
   13083   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
   13084   Mem s;                /* The return value is stored here */
   13085   Mem *pMem;            /* Memory cell used to store aggregate context */
   13086   CollSeq *pColl;       /* Collating sequence */
   13087   int isError;          /* Error code returned by the function. */
   13088   int skipFlag;         /* Skip skip accumulator loading if true */
   13089 };
   13090 
   13091 /*
   13092 ** An Explain object accumulates indented output which is helpful
   13093 ** in describing recursive data structures.
   13094 */
   13095 struct Explain {
   13096   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
   13097   StrAccum str;      /* The string being accumulated */
   13098   int nIndent;       /* Number of elements in aIndent */
   13099   u16 aIndent[100];  /* Levels of indentation */
   13100   char zBase[100];   /* Initial space */
   13101 };
   13102 
   13103 /*
   13104 ** An instance of the virtual machine.  This structure contains the complete
   13105 ** state of the virtual machine.
   13106 **
   13107 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
   13108 ** is really a pointer to an instance of this structure.
   13109 **
   13110 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
   13111 ** any virtual table method invocations made by the vdbe program. It is
   13112 ** set to 2 for xDestroy method calls and 1 for all other methods. This
   13113 ** variable is used for two purposes: to allow xDestroy methods to execute
   13114 ** "DROP TABLE" statements and to prevent some nasty side effects of
   13115 ** malloc failure when SQLite is invoked recursively by a virtual table
   13116 ** method function.
   13117 */
   13118 struct Vdbe {
   13119   sqlite3 *db;            /* The database connection that owns this statement */
   13120   Op *aOp;                /* Space to hold the virtual machine's program */
   13121   Mem *aMem;              /* The memory locations */
   13122   Mem **apArg;            /* Arguments to currently executing user function */
   13123   Mem *aColName;          /* Column names to return */
   13124   Mem *pResultSet;        /* Pointer to an array of results */
   13125   int nMem;               /* Number of memory locations currently allocated */
   13126   int nOp;                /* Number of instructions in the program */
   13127   int nOpAlloc;           /* Number of slots allocated for aOp[] */
   13128   int nLabel;             /* Number of labels used */
   13129   int *aLabel;            /* Space to hold the labels */
   13130   u16 nResColumn;         /* Number of columns in one row of the result set */
   13131   u16 nCursor;            /* Number of slots in apCsr[] */
   13132   u32 magic;              /* Magic number for sanity checking */
   13133   char *zErrMsg;          /* Error message written here */
   13134   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   13135   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
   13136   Mem *aVar;              /* Values for the OP_Variable opcode. */
   13137   char **azVar;           /* Name of variables */
   13138   ynVar nVar;             /* Number of entries in aVar[] */
   13139   ynVar nzVar;            /* Number of entries in azVar[] */
   13140   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   13141   int pc;                 /* The program counter */
   13142   int rc;                 /* Value to return */
   13143   u8 errorAction;         /* Recovery action to do in case of an error */
   13144   u8 explain;             /* True if EXPLAIN present on SQL command */
   13145   u8 changeCntOn;         /* True to update the change-counter */
   13146   u8 expired;             /* True if the VM needs to be recompiled */
   13147   u8 runOnlyOnce;         /* Automatically expire on reset */
   13148   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   13149   u8 inVtabMethod;        /* See comments above */
   13150   u8 usesStmtJournal;     /* True if uses a statement journal */
   13151   u8 readOnly;            /* True for read-only statements */
   13152   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
   13153   int nChange;            /* Number of db changes made since last reset */
   13154   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
   13155   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
   13156   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   13157   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
   13158 #ifndef SQLITE_OMIT_TRACE
   13159   i64 startTime;          /* Time when query started - used for profiling */
   13160 #endif
   13161   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
   13162   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
   13163   char *zSql;             /* Text of the SQL statement that generated this */
   13164   void *pFree;            /* Free this when deleting the vdbe */
   13165 #ifdef SQLITE_DEBUG
   13166   FILE *trace;            /* Write an execution trace here, if not NULL */
   13167 #endif
   13168 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
   13169   Explain *pExplain;      /* The explainer */
   13170   char *zExplain;         /* Explanation of data structures */
   13171 #endif
   13172   VdbeFrame *pFrame;      /* Parent frame */
   13173   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
   13174   int nFrame;             /* Number of frames in pFrame list */
   13175   u32 expmask;            /* Binding to these vars invalidates VM */
   13176   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
   13177   int nOnceFlag;          /* Size of array aOnceFlag[] */
   13178   u8 *aOnceFlag;          /* Flags for OP_Once */
   13179 };
   13180 
   13181 /*
   13182 ** The following are allowed values for Vdbe.magic
   13183 */
   13184 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   13185 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
   13186 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
   13187 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
   13188 
   13189 /*
   13190 ** Function prototypes
   13191 */
   13192 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
   13193 void sqliteVdbePopStack(Vdbe*,int);
   13194 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
   13195 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   13196 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
   13197 #endif
   13198 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
   13199 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
   13200 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
   13201 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   13202 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
   13203 
   13204 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   13205 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
   13206 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
   13207 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   13208 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
   13209 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
   13210 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
   13211 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
   13212 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
   13213 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
   13214 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
   13215 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
   13216 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
   13217 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
   13218 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
   13219 #ifdef SQLITE_OMIT_FLOATING_POINT
   13220 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
   13221 #else
   13222 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
   13223 #endif
   13224 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
   13225 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
   13226 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
   13227 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
   13228 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
   13229 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
   13230 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
   13231 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
   13232 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
   13233 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
   13234 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
   13235 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
   13236 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
   13237 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
   13238 #define VdbeMemRelease(X)  \
   13239   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
   13240     sqlite3VdbeMemReleaseExternal(X);
   13241 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   13242 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
   13243 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   13244 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
   13245 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
   13246 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
   13247 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
   13248 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
   13249 
   13250 #ifdef SQLITE_OMIT_MERGE_SORT
   13251 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
   13252 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
   13253 # define sqlite3VdbeSorterClose(Y,Z)
   13254 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
   13255 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
   13256 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
   13257 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
   13258 #else
   13259 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
   13260 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
   13261 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
   13262 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
   13263 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
   13264 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
   13265 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
   13266 #endif
   13267 
   13268 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   13269 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
   13270 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
   13271 #else
   13272 # define sqlite3VdbeEnter(X)
   13273 # define sqlite3VdbeLeave(X)
   13274 #endif
   13275 
   13276 #ifdef SQLITE_DEBUG
   13277 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
   13278 #endif
   13279 
   13280 #ifndef SQLITE_OMIT_FOREIGN_KEY
   13281 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
   13282 #else
   13283 # define sqlite3VdbeCheckFk(p,i) 0
   13284 #endif
   13285 
   13286 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
   13287 #ifdef SQLITE_DEBUG
   13288 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
   13289 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
   13290 #endif
   13291 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
   13292 
   13293 #ifndef SQLITE_OMIT_INCRBLOB
   13294 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
   13295   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   13296 #else
   13297   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
   13298   #define ExpandBlob(P) SQLITE_OK
   13299 #endif
   13300 
   13301 #endif /* !defined(_VDBEINT_H_) */
   13302 
   13303 /************** End of vdbeInt.h *********************************************/
   13304 /************** Continuing where we left off in status.c *********************/
   13305 
   13306 /*
   13307 ** Variables in which to record status information.
   13308 */
   13309 typedef struct sqlite3StatType sqlite3StatType;
   13310 static SQLITE_WSD struct sqlite3StatType {
   13311   int nowValue[10];         /* Current value */
   13312   int mxValue[10];          /* Maximum value */
   13313 } sqlite3Stat = { {0,}, {0,} };
   13314 
   13315 
   13316 /* The "wsdStat" macro will resolve to the status information
   13317 ** state vector.  If writable static data is unsupported on the target,
   13318 ** we have to locate the state vector at run-time.  In the more common
   13319 ** case where writable static data is supported, wsdStat can refer directly
   13320 ** to the "sqlite3Stat" state vector declared above.
   13321 */
   13322 #ifdef SQLITE_OMIT_WSD
   13323 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   13324 # define wsdStat x[0]
   13325 #else
   13326 # define wsdStatInit
   13327 # define wsdStat sqlite3Stat
   13328 #endif
   13329 
   13330 /*
   13331 ** Return the current value of a status parameter.
   13332 */
   13333 SQLITE_PRIVATE int sqlite3StatusValue(int op){
   13334   wsdStatInit;
   13335   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   13336   return wsdStat.nowValue[op];
   13337 }
   13338 
   13339 /*
   13340 ** Add N to the value of a status record.  It is assumed that the
   13341 ** caller holds appropriate locks.
   13342 */
   13343 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
   13344   wsdStatInit;
   13345   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   13346   wsdStat.nowValue[op] += N;
   13347   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   13348     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   13349   }
   13350 }
   13351 
   13352 /*
   13353 ** Set the value of a status to X.
   13354 */
   13355 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
   13356   wsdStatInit;
   13357   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   13358   wsdStat.nowValue[op] = X;
   13359   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   13360     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   13361   }
   13362 }
   13363 
   13364 /*
   13365 ** Query status information.
   13366 **
   13367 ** This implementation assumes that reading or writing an aligned
   13368 ** 32-bit integer is an atomic operation.  If that assumption is not true,
   13369 ** then this routine is not threadsafe.
   13370 */
   13371 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   13372   wsdStatInit;
   13373   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   13374     return SQLITE_MISUSE_BKPT;
   13375   }
   13376   *pCurrent = wsdStat.nowValue[op];
   13377   *pHighwater = wsdStat.mxValue[op];
   13378   if( resetFlag ){
   13379     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   13380   }
   13381   return SQLITE_OK;
   13382 }
   13383 
   13384 /*
   13385 ** Query status information for a single database connection
   13386 */
   13387 SQLITE_API int sqlite3_db_status(
   13388   sqlite3 *db,          /* The database connection whose status is desired */
   13389   int op,               /* Status verb */
   13390   int *pCurrent,        /* Write current value here */
   13391   int *pHighwater,      /* Write high-water mark here */
   13392   int resetFlag         /* Reset high-water mark if true */
   13393 ){
   13394   int rc = SQLITE_OK;   /* Return code */
   13395   sqlite3_mutex_enter(db->mutex);
   13396   switch( op ){
   13397     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   13398       *pCurrent = db->lookaside.nOut;
   13399       *pHighwater = db->lookaside.mxOut;
   13400       if( resetFlag ){
   13401         db->lookaside.mxOut = db->lookaside.nOut;
   13402       }
   13403       break;
   13404     }
   13405 
   13406     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
   13407     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
   13408     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
   13409       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
   13410       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
   13411       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
   13412       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
   13413       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
   13414       *pCurrent = 0;
   13415       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
   13416       if( resetFlag ){
   13417         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
   13418       }
   13419       break;
   13420     }
   13421 
   13422     /*
   13423     ** Return an approximation for the amount of memory currently used
   13424     ** by all pagers associated with the given database connection.  The
   13425     ** highwater mark is meaningless and is returned as zero.
   13426     */
   13427     case SQLITE_DBSTATUS_CACHE_USED: {
   13428       int totalUsed = 0;
   13429       int i;
   13430       sqlite3BtreeEnterAll(db);
   13431       for(i=0; i<db->nDb; i++){
   13432         Btree *pBt = db->aDb[i].pBt;
   13433         if( pBt ){
   13434           Pager *pPager = sqlite3BtreePager(pBt);
   13435           totalUsed += sqlite3PagerMemUsed(pPager);
   13436         }
   13437       }
   13438       sqlite3BtreeLeaveAll(db);
   13439       *pCurrent = totalUsed;
   13440       *pHighwater = 0;
   13441       break;
   13442     }
   13443 
   13444     /*
   13445     ** *pCurrent gets an accurate estimate of the amount of memory used
   13446     ** to store the schema for all databases (main, temp, and any ATTACHed
   13447     ** databases.  *pHighwater is set to zero.
   13448     */
   13449     case SQLITE_DBSTATUS_SCHEMA_USED: {
   13450       int i;                      /* Used to iterate through schemas */
   13451       int nByte = 0;              /* Used to accumulate return value */
   13452 
   13453       sqlite3BtreeEnterAll(db);
   13454       db->pnBytesFreed = &nByte;
   13455       for(i=0; i<db->nDb; i++){
   13456         Schema *pSchema = db->aDb[i].pSchema;
   13457         if( ALWAYS(pSchema!=0) ){
   13458           HashElem *p;
   13459 
   13460           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
   13461               pSchema->tblHash.count
   13462             + pSchema->trigHash.count
   13463             + pSchema->idxHash.count
   13464             + pSchema->fkeyHash.count
   13465           );
   13466           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
   13467           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
   13468           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
   13469           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
   13470 
   13471           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
   13472             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
   13473           }
   13474           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   13475             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
   13476           }
   13477         }
   13478       }
   13479       db->pnBytesFreed = 0;
   13480       sqlite3BtreeLeaveAll(db);
   13481 
   13482       *pHighwater = 0;
   13483       *pCurrent = nByte;
   13484       break;
   13485     }
   13486 
   13487     /*
   13488     ** *pCurrent gets an accurate estimate of the amount of memory used
   13489     ** to store all prepared statements.
   13490     ** *pHighwater is set to zero.
   13491     */
   13492     case SQLITE_DBSTATUS_STMT_USED: {
   13493       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
   13494       int nByte = 0;              /* Used to accumulate return value */
   13495 
   13496       db->pnBytesFreed = &nByte;
   13497       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
   13498         sqlite3VdbeDeleteObject(db, pVdbe);
   13499       }
   13500       db->pnBytesFreed = 0;
   13501 
   13502       *pHighwater = 0;
   13503       *pCurrent = nByte;
   13504 
   13505       break;
   13506     }
   13507 
   13508     /*
   13509     ** Set *pCurrent to the total cache hits or misses encountered by all
   13510     ** pagers the database handle is connected to. *pHighwater is always set
   13511     ** to zero.
   13512     */
   13513     case SQLITE_DBSTATUS_CACHE_HIT:
   13514     case SQLITE_DBSTATUS_CACHE_MISS: {
   13515       int i;
   13516       int nRet = 0;
   13517       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
   13518 
   13519       for(i=0; i<db->nDb; i++){
   13520         if( db->aDb[i].pBt ){
   13521           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
   13522           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
   13523         }
   13524       }
   13525       *pHighwater = 0;
   13526       *pCurrent = nRet;
   13527       break;
   13528     }
   13529 
   13530     default: {
   13531       rc = SQLITE_ERROR;
   13532     }
   13533   }
   13534   sqlite3_mutex_leave(db->mutex);
   13535   return rc;
   13536 }
   13537 
   13538 /************** End of status.c **********************************************/
   13539 /************** Begin file date.c ********************************************/
   13540 /*
   13541 ** 2003 October 31
   13542 **
   13543 ** The author disclaims copyright to this source code.  In place of
   13544 ** a legal notice, here is a blessing:
   13545 **
   13546 **    May you do good and not evil.
   13547 **    May you find forgiveness for yourself and forgive others.
   13548 **    May you share freely, never taking more than you give.
   13549 **
   13550 *************************************************************************
   13551 ** This file contains the C functions that implement date and time
   13552 ** functions for SQLite.
   13553 **
   13554 ** There is only one exported symbol in this file - the function
   13555 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   13556 ** All other code has file scope.
   13557 **
   13558 ** SQLite processes all times and dates as Julian Day numbers.  The
   13559 ** dates and times are stored as the number of days since noon
   13560 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   13561 ** calendar system.
   13562 **
   13563 ** 1970-01-01 00:00:00 is JD 2440587.5
   13564 ** 2000-01-01 00:00:00 is JD 2451544.5
   13565 **
   13566 ** This implemention requires years to be expressed as a 4-digit number
   13567 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   13568 ** be represented, even though julian day numbers allow a much wider
   13569 ** range of dates.
   13570 **
   13571 ** The Gregorian calendar system is used for all dates and times,
   13572 ** even those that predate the Gregorian calendar.  Historians usually
   13573 ** use the Julian calendar for dates prior to 1582-10-15 and for some
   13574 ** dates afterwards, depending on locale.  Beware of this difference.
   13575 **
   13576 ** The conversion algorithms are implemented based on descriptions
   13577 ** in the following text:
   13578 **
   13579 **      Jean Meeus
   13580 **      Astronomical Algorithms, 2nd Edition, 1998
   13581 **      ISBM 0-943396-61-1
   13582 **      Willmann-Bell, Inc
   13583 **      Richmond, Virginia (USA)
   13584 */
   13585 /* #include <stdlib.h> */
   13586 /* #include <assert.h> */
   13587 #include <time.h>
   13588 
   13589 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   13590 
   13591 
   13592 /*
   13593 ** A structure for holding a single date and time.
   13594 */
   13595 typedef struct DateTime DateTime;
   13596 struct DateTime {
   13597   sqlite3_int64 iJD; /* The julian day number times 86400000 */
   13598   int Y, M, D;       /* Year, month, and day */
   13599   int h, m;          /* Hour and minutes */
   13600   int tz;            /* Timezone offset in minutes */
   13601   double s;          /* Seconds */
   13602   char validYMD;     /* True (1) if Y,M,D are valid */
   13603   char validHMS;     /* True (1) if h,m,s are valid */
   13604   char validJD;      /* True (1) if iJD is valid */
   13605   char validTZ;      /* True (1) if tz is valid */
   13606 };
   13607 
   13608 
   13609 /*
   13610 ** Convert zDate into one or more integers.  Additional arguments
   13611 ** come in groups of 5 as follows:
   13612 **
   13613 **       N       number of digits in the integer
   13614 **       min     minimum allowed value of the integer
   13615 **       max     maximum allowed value of the integer
   13616 **       nextC   first character after the integer
   13617 **       pVal    where to write the integers value.
   13618 **
   13619 ** Conversions continue until one with nextC==0 is encountered.
   13620 ** The function returns the number of successful conversions.
   13621 */
   13622 static int getDigits(const char *zDate, ...){
   13623   va_list ap;
   13624   int val;
   13625   int N;
   13626   int min;
   13627   int max;
   13628   int nextC;
   13629   int *pVal;
   13630   int cnt = 0;
   13631   va_start(ap, zDate);
   13632   do{
   13633     N = va_arg(ap, int);
   13634     min = va_arg(ap, int);
   13635     max = va_arg(ap, int);
   13636     nextC = va_arg(ap, int);
   13637     pVal = va_arg(ap, int*);
   13638     val = 0;
   13639     while( N-- ){
   13640       if( !sqlite3Isdigit(*zDate) ){
   13641         goto end_getDigits;
   13642       }
   13643       val = val*10 + *zDate - '0';
   13644       zDate++;
   13645     }
   13646     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
   13647       goto end_getDigits;
   13648     }
   13649     *pVal = val;
   13650     zDate++;
   13651     cnt++;
   13652   }while( nextC );
   13653 end_getDigits:
   13654   va_end(ap);
   13655   return cnt;
   13656 }
   13657 
   13658 /*
   13659 ** Parse a timezone extension on the end of a date-time.
   13660 ** The extension is of the form:
   13661 **
   13662 **        (+/-)HH:MM
   13663 **
   13664 ** Or the "zulu" notation:
   13665 **
   13666 **        Z
   13667 **
   13668 ** If the parse is successful, write the number of minutes
   13669 ** of change in p->tz and return 0.  If a parser error occurs,
   13670 ** return non-zero.
   13671 **
   13672 ** A missing specifier is not considered an error.
   13673 */
   13674 static int parseTimezone(const char *zDate, DateTime *p){
   13675   int sgn = 0;
   13676   int nHr, nMn;
   13677   int c;
   13678   while( sqlite3Isspace(*zDate) ){ zDate++; }
   13679   p->tz = 0;
   13680   c = *zDate;
   13681   if( c=='-' ){
   13682     sgn = -1;
   13683   }else if( c=='+' ){
   13684     sgn = +1;
   13685   }else if( c=='Z' || c=='z' ){
   13686     zDate++;
   13687     goto zulu_time;
   13688   }else{
   13689     return c!=0;
   13690   }
   13691   zDate++;
   13692   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
   13693     return 1;
   13694   }
   13695   zDate += 5;
   13696   p->tz = sgn*(nMn + nHr*60);
   13697 zulu_time:
   13698   while( sqlite3Isspace(*zDate) ){ zDate++; }
   13699   return *zDate!=0;
   13700 }
   13701 
   13702 /*
   13703 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   13704 ** The HH, MM, and SS must each be exactly 2 digits.  The
   13705 ** fractional seconds FFFF can be one or more digits.
   13706 **
   13707 ** Return 1 if there is a parsing error and 0 on success.
   13708 */
   13709 static int parseHhMmSs(const char *zDate, DateTime *p){
   13710   int h, m, s;
   13711   double ms = 0.0;
   13712   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
   13713     return 1;
   13714   }
   13715   zDate += 5;
   13716   if( *zDate==':' ){
   13717     zDate++;
   13718     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
   13719       return 1;
   13720     }
   13721     zDate += 2;
   13722     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   13723       double rScale = 1.0;
   13724       zDate++;
   13725       while( sqlite3Isdigit(*zDate) ){
   13726         ms = ms*10.0 + *zDate - '0';
   13727         rScale *= 10.0;
   13728         zDate++;
   13729       }
   13730       ms /= rScale;
   13731     }
   13732   }else{
   13733     s = 0;
   13734   }
   13735   p->validJD = 0;
   13736   p->validHMS = 1;
   13737   p->h = h;
   13738   p->m = m;
   13739   p->s = s + ms;
   13740   if( parseTimezone(zDate, p) ) return 1;
   13741   p->validTZ = (p->tz!=0)?1:0;
   13742   return 0;
   13743 }
   13744 
   13745 /*
   13746 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   13747 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   13748 **
   13749 ** Reference:  Meeus page 61
   13750 */
   13751 static void computeJD(DateTime *p){
   13752   int Y, M, D, A, B, X1, X2;
   13753 
   13754   if( p->validJD ) return;
   13755   if( p->validYMD ){
   13756     Y = p->Y;
   13757     M = p->M;
   13758     D = p->D;
   13759   }else{
   13760     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   13761     M = 1;
   13762     D = 1;
   13763   }
   13764   if( M<=2 ){
   13765     Y--;
   13766     M += 12;
   13767   }
   13768   A = Y/100;
   13769   B = 2 - A + (A/4);
   13770   X1 = 36525*(Y+4716)/100;
   13771   X2 = 306001*(M+1)/10000;
   13772   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   13773   p->validJD = 1;
   13774   if( p->validHMS ){
   13775     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   13776     if( p->validTZ ){
   13777       p->iJD -= p->tz*60000;
   13778       p->validYMD = 0;
   13779       p->validHMS = 0;
   13780       p->validTZ = 0;
   13781     }
   13782   }
   13783 }
   13784 
   13785 /*
   13786 ** Parse dates of the form
   13787 **
   13788 **     YYYY-MM-DD HH:MM:SS.FFF
   13789 **     YYYY-MM-DD HH:MM:SS
   13790 **     YYYY-MM-DD HH:MM
   13791 **     YYYY-MM-DD
   13792 **
   13793 ** Write the result into the DateTime structure and return 0
   13794 ** on success and 1 if the input string is not a well-formed
   13795 ** date.
   13796 */
   13797 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   13798   int Y, M, D, neg;
   13799 
   13800   if( zDate[0]=='-' ){
   13801     zDate++;
   13802     neg = 1;
   13803   }else{
   13804     neg = 0;
   13805   }
   13806   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
   13807     return 1;
   13808   }
   13809   zDate += 10;
   13810   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   13811   if( parseHhMmSs(zDate, p)==0 ){
   13812     /* We got the time */
   13813   }else if( *zDate==0 ){
   13814     p->validHMS = 0;
   13815   }else{
   13816     return 1;
   13817   }
   13818   p->validJD = 0;
   13819   p->validYMD = 1;
   13820   p->Y = neg ? -Y : Y;
   13821   p->M = M;
   13822   p->D = D;
   13823   if( p->validTZ ){
   13824     computeJD(p);
   13825   }
   13826   return 0;
   13827 }
   13828 
   13829 /*
   13830 ** Set the time to the current time reported by the VFS.
   13831 **
   13832 ** Return the number of errors.
   13833 */
   13834 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   13835   sqlite3 *db = sqlite3_context_db_handle(context);
   13836   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
   13837     p->validJD = 1;
   13838     return 0;
   13839   }else{
   13840     return 1;
   13841   }
   13842 }
   13843 
   13844 /*
   13845 ** Attempt to parse the given string into a Julian Day Number.  Return
   13846 ** the number of errors.
   13847 **
   13848 ** The following are acceptable forms for the input string:
   13849 **
   13850 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   13851 **      DDDD.DD
   13852 **      now
   13853 **
   13854 ** In the first form, the +/-HH:MM is always optional.  The fractional
   13855 ** seconds extension (the ".FFF") is optional.  The seconds portion
   13856 ** (":SS.FFF") is option.  The year and date can be omitted as long
   13857 ** as there is a time string.  The time string can be omitted as long
   13858 ** as there is a year and date.
   13859 */
   13860 static int parseDateOrTime(
   13861   sqlite3_context *context,
   13862   const char *zDate,
   13863   DateTime *p
   13864 ){
   13865   double r;
   13866   if( parseYyyyMmDd(zDate,p)==0 ){
   13867     return 0;
   13868   }else if( parseHhMmSs(zDate, p)==0 ){
   13869     return 0;
   13870   }else if( sqlite3StrICmp(zDate,"now")==0){
   13871     return setDateTimeToCurrent(context, p);
   13872   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
   13873     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   13874     p->validJD = 1;
   13875     return 0;
   13876   }
   13877   return 1;
   13878 }
   13879 
   13880 /*
   13881 ** Compute the Year, Month, and Day from the julian day number.
   13882 */
   13883 static void computeYMD(DateTime *p){
   13884   int Z, A, B, C, D, E, X1;
   13885   if( p->validYMD ) return;
   13886   if( !p->validJD ){
   13887     p->Y = 2000;
   13888     p->M = 1;
   13889     p->D = 1;
   13890   }else{
   13891     Z = (int)((p->iJD + 43200000)/86400000);
   13892     A = (int)((Z - 1867216.25)/36524.25);
   13893     A = Z + 1 + A - (A/4);
   13894     B = A + 1524;
   13895     C = (int)((B - 122.1)/365.25);
   13896     D = (36525*C)/100;
   13897     E = (int)((B-D)/30.6001);
   13898     X1 = (int)(30.6001*E);
   13899     p->D = B - D - X1;
   13900     p->M = E<14 ? E-1 : E-13;
   13901     p->Y = p->M>2 ? C - 4716 : C - 4715;
   13902   }
   13903   p->validYMD = 1;
   13904 }
   13905 
   13906 /*
   13907 ** Compute the Hour, Minute, and Seconds from the julian day number.
   13908 */
   13909 static void computeHMS(DateTime *p){
   13910   int s;
   13911   if( p->validHMS ) return;
   13912   computeJD(p);
   13913   s = (int)((p->iJD + 43200000) % 86400000);
   13914   p->s = s/1000.0;
   13915   s = (int)p->s;
   13916   p->s -= s;
   13917   p->h = s/3600;
   13918   s -= p->h*3600;
   13919   p->m = s/60;
   13920   p->s += s - p->m*60;
   13921   p->validHMS = 1;
   13922 }
   13923 
   13924 /*
   13925 ** Compute both YMD and HMS
   13926 */
   13927 static void computeYMD_HMS(DateTime *p){
   13928   computeYMD(p);
   13929   computeHMS(p);
   13930 }
   13931 
   13932 /*
   13933 ** Clear the YMD and HMS and the TZ
   13934 */
   13935 static void clearYMD_HMS_TZ(DateTime *p){
   13936   p->validYMD = 0;
   13937   p->validHMS = 0;
   13938   p->validTZ = 0;
   13939 }
   13940 
   13941 /*
   13942 ** On recent Windows platforms, the localtime_s() function is available
   13943 ** as part of the "Secure CRT". It is essentially equivalent to
   13944 ** localtime_r() available under most POSIX platforms, except that the
   13945 ** order of the parameters is reversed.
   13946 **
   13947 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   13948 **
   13949 ** If the user has not indicated to use localtime_r() or localtime_s()
   13950 ** already, check for an MSVC build environment that provides
   13951 ** localtime_s().
   13952 */
   13953 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
   13954      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   13955 #define HAVE_LOCALTIME_S 1
   13956 #endif
   13957 
   13958 #ifndef SQLITE_OMIT_LOCALTIME
   13959 /*
   13960 ** The following routine implements the rough equivalent of localtime_r()
   13961 ** using whatever operating-system specific localtime facility that
   13962 ** is available.  This routine returns 0 on success and
   13963 ** non-zero on any kind of error.
   13964 **
   13965 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
   13966 ** routine will always fail.
   13967 */
   13968 static int osLocaltime(time_t *t, struct tm *pTm){
   13969   int rc;
   13970 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
   13971       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
   13972   struct tm *pX;
   13973 #if SQLITE_THREADSAFE>0
   13974   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   13975 #endif
   13976   sqlite3_mutex_enter(mutex);
   13977   pX = localtime(t);
   13978 #ifndef SQLITE_OMIT_BUILTIN_TEST
   13979   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
   13980 #endif
   13981   if( pX ) *pTm = *pX;
   13982   sqlite3_mutex_leave(mutex);
   13983   rc = pX==0;
   13984 #else
   13985 #ifndef SQLITE_OMIT_BUILTIN_TEST
   13986   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
   13987 #endif
   13988 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
   13989   rc = localtime_r(t, pTm)==0;
   13990 #else
   13991   rc = localtime_s(pTm, t);
   13992 #endif /* HAVE_LOCALTIME_R */
   13993 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
   13994   return rc;
   13995 }
   13996 #endif /* SQLITE_OMIT_LOCALTIME */
   13997 
   13998 
   13999 #ifndef SQLITE_OMIT_LOCALTIME
   14000 /*
   14001 ** Compute the difference (in milliseconds) between localtime and UTC
   14002 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
   14003 ** return this value and set *pRc to SQLITE_OK.
   14004 **
   14005 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
   14006 ** is undefined in this case.
   14007 */
   14008 static sqlite3_int64 localtimeOffset(
   14009   DateTime *p,                    /* Date at which to calculate offset */
   14010   sqlite3_context *pCtx,          /* Write error here if one occurs */
   14011   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
   14012 ){
   14013   DateTime x, y;
   14014   time_t t;
   14015   struct tm sLocal;
   14016 
   14017   /* Initialize the contents of sLocal to avoid a compiler warning. */
   14018   memset(&sLocal, 0, sizeof(sLocal));
   14019 
   14020   x = *p;
   14021   computeYMD_HMS(&x);
   14022   if( x.Y<1971 || x.Y>=2038 ){
   14023     x.Y = 2000;
   14024     x.M = 1;
   14025     x.D = 1;
   14026     x.h = 0;
   14027     x.m = 0;
   14028     x.s = 0.0;
   14029   } else {
   14030     int s = (int)(x.s + 0.5);
   14031     x.s = s;
   14032   }
   14033   x.tz = 0;
   14034   x.validJD = 0;
   14035   computeJD(&x);
   14036   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   14037   if( osLocaltime(&t, &sLocal) ){
   14038     sqlite3_result_error(pCtx, "local time unavailable", -1);
   14039     *pRc = SQLITE_ERROR;
   14040     return 0;
   14041   }
   14042   y.Y = sLocal.tm_year + 1900;
   14043   y.M = sLocal.tm_mon + 1;
   14044   y.D = sLocal.tm_mday;
   14045   y.h = sLocal.tm_hour;
   14046   y.m = sLocal.tm_min;
   14047   y.s = sLocal.tm_sec;
   14048   y.validYMD = 1;
   14049   y.validHMS = 1;
   14050   y.validJD = 0;
   14051   y.validTZ = 0;
   14052   computeJD(&y);
   14053   *pRc = SQLITE_OK;
   14054   return y.iJD - x.iJD;
   14055 }
   14056 #endif /* SQLITE_OMIT_LOCALTIME */
   14057 
   14058 /*
   14059 ** Process a modifier to a date-time stamp.  The modifiers are
   14060 ** as follows:
   14061 **
   14062 **     NNN days
   14063 **     NNN hours
   14064 **     NNN minutes
   14065 **     NNN.NNNN seconds
   14066 **     NNN months
   14067 **     NNN years
   14068 **     start of month
   14069 **     start of year
   14070 **     start of week
   14071 **     start of day
   14072 **     weekday N
   14073 **     unixepoch
   14074 **     localtime
   14075 **     utc
   14076 **
   14077 ** Return 0 on success and 1 if there is any kind of error. If the error
   14078 ** is in a system call (i.e. localtime()), then an error message is written
   14079 ** to context pCtx. If the error is an unrecognized modifier, no error is
   14080 ** written to pCtx.
   14081 */
   14082 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
   14083   int rc = 1;
   14084   int n;
   14085   double r;
   14086   char *z, zBuf[30];
   14087   z = zBuf;
   14088   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
   14089     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
   14090   }
   14091   z[n] = 0;
   14092   switch( z[0] ){
   14093 #ifndef SQLITE_OMIT_LOCALTIME
   14094     case 'l': {
   14095       /*    localtime
   14096       **
   14097       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   14098       ** show local time.
   14099       */
   14100       if( strcmp(z, "localtime")==0 ){
   14101         computeJD(p);
   14102         p->iJD += localtimeOffset(p, pCtx, &rc);
   14103         clearYMD_HMS_TZ(p);
   14104       }
   14105       break;
   14106     }
   14107 #endif
   14108     case 'u': {
   14109       /*
   14110       **    unixepoch
   14111       **
   14112       ** Treat the current value of p->iJD as the number of
   14113       ** seconds since 1970.  Convert to a real julian day number.
   14114       */
   14115       if( strcmp(z, "unixepoch")==0 && p->validJD ){
   14116         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
   14117         clearYMD_HMS_TZ(p);
   14118         rc = 0;
   14119       }
   14120 #ifndef SQLITE_OMIT_LOCALTIME
   14121       else if( strcmp(z, "utc")==0 ){
   14122         sqlite3_int64 c1;
   14123         computeJD(p);
   14124         c1 = localtimeOffset(p, pCtx, &rc);
   14125         if( rc==SQLITE_OK ){
   14126           p->iJD -= c1;
   14127           clearYMD_HMS_TZ(p);
   14128           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
   14129         }
   14130       }
   14131 #endif
   14132       break;
   14133     }
   14134     case 'w': {
   14135       /*
   14136       **    weekday N
   14137       **
   14138       ** Move the date to the same time on the next occurrence of
   14139       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   14140       ** date is already on the appropriate weekday, this is a no-op.
   14141       */
   14142       if( strncmp(z, "weekday ", 8)==0
   14143                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
   14144                && (n=(int)r)==r && n>=0 && r<7 ){
   14145         sqlite3_int64 Z;
   14146         computeYMD_HMS(p);
   14147         p->validTZ = 0;
   14148         p->validJD = 0;
   14149         computeJD(p);
   14150         Z = ((p->iJD + 129600000)/86400000) % 7;
   14151         if( Z>n ) Z -= 7;
   14152         p->iJD += (n - Z)*86400000;
   14153         clearYMD_HMS_TZ(p);
   14154         rc = 0;
   14155       }
   14156       break;
   14157     }
   14158     case 's': {
   14159       /*
   14160       **    start of TTTTT
   14161       **
   14162       ** Move the date backwards to the beginning of the current day,
   14163       ** or month or year.
   14164       */
   14165       if( strncmp(z, "start of ", 9)!=0 ) break;
   14166       z += 9;
   14167       computeYMD(p);
   14168       p->validHMS = 1;
   14169       p->h = p->m = 0;
   14170       p->s = 0.0;
   14171       p->validTZ = 0;
   14172       p->validJD = 0;
   14173       if( strcmp(z,"month")==0 ){
   14174         p->D = 1;
   14175         rc = 0;
   14176       }else if( strcmp(z,"year")==0 ){
   14177         computeYMD(p);
   14178         p->M = 1;
   14179         p->D = 1;
   14180         rc = 0;
   14181       }else if( strcmp(z,"day")==0 ){
   14182         rc = 0;
   14183       }
   14184       break;
   14185     }
   14186     case '+':
   14187     case '-':
   14188     case '0':
   14189     case '1':
   14190     case '2':
   14191     case '3':
   14192     case '4':
   14193     case '5':
   14194     case '6':
   14195     case '7':
   14196     case '8':
   14197     case '9': {
   14198       double rRounder;
   14199       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
   14200       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
   14201         rc = 1;
   14202         break;
   14203       }
   14204       if( z[n]==':' ){
   14205         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   14206         ** specified number of hours, minutes, seconds, and fractional seconds
   14207         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   14208         ** omitted.
   14209         */
   14210         const char *z2 = z;
   14211         DateTime tx;
   14212         sqlite3_int64 day;
   14213         if( !sqlite3Isdigit(*z2) ) z2++;
   14214         memset(&tx, 0, sizeof(tx));
   14215         if( parseHhMmSs(z2, &tx) ) break;
   14216         computeJD(&tx);
   14217         tx.iJD -= 43200000;
   14218         day = tx.iJD/86400000;
   14219         tx.iJD -= day*86400000;
   14220         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   14221         computeJD(p);
   14222         clearYMD_HMS_TZ(p);
   14223         p->iJD += tx.iJD;
   14224         rc = 0;
   14225         break;
   14226       }
   14227       z += n;
   14228       while( sqlite3Isspace(*z) ) z++;
   14229       n = sqlite3Strlen30(z);
   14230       if( n>10 || n<3 ) break;
   14231       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
   14232       computeJD(p);
   14233       rc = 0;
   14234       rRounder = r<0 ? -0.5 : +0.5;
   14235       if( n==3 && strcmp(z,"day")==0 ){
   14236         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
   14237       }else if( n==4 && strcmp(z,"hour")==0 ){
   14238         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
   14239       }else if( n==6 && strcmp(z,"minute")==0 ){
   14240         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
   14241       }else if( n==6 && strcmp(z,"second")==0 ){
   14242         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
   14243       }else if( n==5 && strcmp(z,"month")==0 ){
   14244         int x, y;
   14245         computeYMD_HMS(p);
   14246         p->M += (int)r;
   14247         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   14248         p->Y += x;
   14249         p->M -= x*12;
   14250         p->validJD = 0;
   14251         computeJD(p);
   14252         y = (int)r;
   14253         if( y!=r ){
   14254           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
   14255         }
   14256       }else if( n==4 && strcmp(z,"year")==0 ){
   14257         int y = (int)r;
   14258         computeYMD_HMS(p);
   14259         p->Y += y;
   14260         p->validJD = 0;
   14261         computeJD(p);
   14262         if( y!=r ){
   14263           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
   14264         }
   14265       }else{
   14266         rc = 1;
   14267       }
   14268       clearYMD_HMS_TZ(p);
   14269       break;
   14270     }
   14271     default: {
   14272       break;
   14273     }
   14274   }
   14275   return rc;
   14276 }
   14277 
   14278 /*
   14279 ** Process time function arguments.  argv[0] is a date-time stamp.
   14280 ** argv[1] and following are modifiers.  Parse them all and write
   14281 ** the resulting time into the DateTime structure p.  Return 0
   14282 ** on success and 1 if there are any errors.
   14283 **
   14284 ** If there are zero parameters (if even argv[0] is undefined)
   14285 ** then assume a default value of "now" for argv[0].
   14286 */
   14287 static int isDate(
   14288   sqlite3_context *context,
   14289   int argc,
   14290   sqlite3_value **argv,
   14291   DateTime *p
   14292 ){
   14293   int i;
   14294   const unsigned char *z;
   14295   int eType;
   14296   memset(p, 0, sizeof(*p));
   14297   if( argc==0 ){
   14298     return setDateTimeToCurrent(context, p);
   14299   }
   14300   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   14301                    || eType==SQLITE_INTEGER ){
   14302     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
   14303     p->validJD = 1;
   14304   }else{
   14305     z = sqlite3_value_text(argv[0]);
   14306     if( !z || parseDateOrTime(context, (char*)z, p) ){
   14307       return 1;
   14308     }
   14309   }
   14310   for(i=1; i<argc; i++){
   14311     z = sqlite3_value_text(argv[i]);
   14312     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
   14313   }
   14314   return 0;
   14315 }
   14316 
   14317 
   14318 /*
   14319 ** The following routines implement the various date and time functions
   14320 ** of SQLite.
   14321 */
   14322 
   14323 /*
   14324 **    julianday( TIMESTRING, MOD, MOD, ...)
   14325 **
   14326 ** Return the julian day number of the date specified in the arguments
   14327 */
   14328 static void juliandayFunc(
   14329   sqlite3_context *context,
   14330   int argc,
   14331   sqlite3_value **argv
   14332 ){
   14333   DateTime x;
   14334   if( isDate(context, argc, argv, &x)==0 ){
   14335     computeJD(&x);
   14336     sqlite3_result_double(context, x.iJD/86400000.0);
   14337   }
   14338 }
   14339 
   14340 /*
   14341 **    datetime( TIMESTRING, MOD, MOD, ...)
   14342 **
   14343 ** Return YYYY-MM-DD HH:MM:SS
   14344 */
   14345 static void datetimeFunc(
   14346   sqlite3_context *context,
   14347   int argc,
   14348   sqlite3_value **argv
   14349 ){
   14350   DateTime x;
   14351   if( isDate(context, argc, argv, &x)==0 ){
   14352     char zBuf[100];
   14353     computeYMD_HMS(&x);
   14354     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   14355                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   14356     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   14357   }
   14358 }
   14359 
   14360 /*
   14361 **    time( TIMESTRING, MOD, MOD, ...)
   14362 **
   14363 ** Return HH:MM:SS
   14364 */
   14365 static void timeFunc(
   14366   sqlite3_context *context,
   14367   int argc,
   14368   sqlite3_value **argv
   14369 ){
   14370   DateTime x;
   14371   if( isDate(context, argc, argv, &x)==0 ){
   14372     char zBuf[100];
   14373     computeHMS(&x);
   14374     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   14375     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   14376   }
   14377 }
   14378 
   14379 /*
   14380 **    date( TIMESTRING, MOD, MOD, ...)
   14381 **
   14382 ** Return YYYY-MM-DD
   14383 */
   14384 static void dateFunc(
   14385   sqlite3_context *context,
   14386   int argc,
   14387   sqlite3_value **argv
   14388 ){
   14389   DateTime x;
   14390   if( isDate(context, argc, argv, &x)==0 ){
   14391     char zBuf[100];
   14392     computeYMD(&x);
   14393     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   14394     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   14395   }
   14396 }
   14397 
   14398 /*
   14399 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   14400 **
   14401 ** Return a string described by FORMAT.  Conversions as follows:
   14402 **
   14403 **   %d  day of month
   14404 **   %f  ** fractional seconds  SS.SSS
   14405 **   %H  hour 00-24
   14406 **   %j  day of year 000-366
   14407 **   %J  ** Julian day number
   14408 **   %m  month 01-12
   14409 **   %M  minute 00-59
   14410 **   %s  seconds since 1970-01-01
   14411 **   %S  seconds 00-59
   14412 **   %w  day of week 0-6  sunday==0
   14413 **   %W  week of year 00-53
   14414 **   %Y  year 0000-9999
   14415 **   %%  %
   14416 */
   14417 static void strftimeFunc(
   14418   sqlite3_context *context,
   14419   int argc,
   14420   sqlite3_value **argv
   14421 ){
   14422   DateTime x;
   14423   u64 n;
   14424   size_t i,j;
   14425   char *z;
   14426   sqlite3 *db;
   14427   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   14428   char zBuf[100];
   14429   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   14430   db = sqlite3_context_db_handle(context);
   14431   for(i=0, n=1; zFmt[i]; i++, n++){
   14432     if( zFmt[i]=='%' ){
   14433       switch( zFmt[i+1] ){
   14434         case 'd':
   14435         case 'H':
   14436         case 'm':
   14437         case 'M':
   14438         case 'S':
   14439         case 'W':
   14440           n++;
   14441           /* fall thru */
   14442         case 'w':
   14443         case '%':
   14444           break;
   14445         case 'f':
   14446           n += 8;
   14447           break;
   14448         case 'j':
   14449           n += 3;
   14450           break;
   14451         case 'Y':
   14452           n += 8;
   14453           break;
   14454         case 's':
   14455         case 'J':
   14456           n += 50;
   14457           break;
   14458         default:
   14459           return;  /* ERROR.  return a NULL */
   14460       }
   14461       i++;
   14462     }
   14463   }
   14464   testcase( n==sizeof(zBuf)-1 );
   14465   testcase( n==sizeof(zBuf) );
   14466   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   14467   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   14468   if( n<sizeof(zBuf) ){
   14469     z = zBuf;
   14470   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   14471     sqlite3_result_error_toobig(context);
   14472     return;
   14473   }else{
   14474     z = sqlite3DbMallocRaw(db, (int)n);
   14475     if( z==0 ){
   14476       sqlite3_result_error_nomem(context);
   14477       return;
   14478     }
   14479   }
   14480   computeJD(&x);
   14481   computeYMD_HMS(&x);
   14482   for(i=j=0; zFmt[i]; i++){
   14483     if( zFmt[i]!='%' ){
   14484       z[j++] = zFmt[i];
   14485     }else{
   14486       i++;
   14487       switch( zFmt[i] ){
   14488         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   14489         case 'f': {
   14490           double s = x.s;
   14491           if( s>59.999 ) s = 59.999;
   14492           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   14493           j += sqlite3Strlen30(&z[j]);
   14494           break;
   14495         }
   14496         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   14497         case 'W': /* Fall thru */
   14498         case 'j': {
   14499           int nDay;             /* Number of days since 1st day of year */
   14500           DateTime y = x;
   14501           y.validJD = 0;
   14502           y.M = 1;
   14503           y.D = 1;
   14504           computeJD(&y);
   14505           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   14506           if( zFmt[i]=='W' ){
   14507             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   14508             wd = (int)(((x.iJD+43200000)/86400000)%7);
   14509             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   14510             j += 2;
   14511           }else{
   14512             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   14513             j += 3;
   14514           }
   14515           break;
   14516         }
   14517         case 'J': {
   14518           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   14519           j+=sqlite3Strlen30(&z[j]);
   14520           break;
   14521         }
   14522         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   14523         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   14524         case 's': {
   14525           sqlite3_snprintf(30,&z[j],"%lld",
   14526                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   14527           j += sqlite3Strlen30(&z[j]);
   14528           break;
   14529         }
   14530         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   14531         case 'w': {
   14532           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   14533           break;
   14534         }
   14535         case 'Y': {
   14536           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   14537           break;
   14538         }
   14539         default:   z[j++] = '%'; break;
   14540       }
   14541     }
   14542   }
   14543   z[j] = 0;
   14544   sqlite3_result_text(context, z, -1,
   14545                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   14546 }
   14547 
   14548 /*
   14549 ** current_time()
   14550 **
   14551 ** This function returns the same value as time('now').
   14552 */
   14553 static void ctimeFunc(
   14554   sqlite3_context *context,
   14555   int NotUsed,
   14556   sqlite3_value **NotUsed2
   14557 ){
   14558   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   14559   timeFunc(context, 0, 0);
   14560 }
   14561 
   14562 /*
   14563 ** current_date()
   14564 **
   14565 ** This function returns the same value as date('now').
   14566 */
   14567 static void cdateFunc(
   14568   sqlite3_context *context,
   14569   int NotUsed,
   14570   sqlite3_value **NotUsed2
   14571 ){
   14572   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   14573   dateFunc(context, 0, 0);
   14574 }
   14575 
   14576 /*
   14577 ** current_timestamp()
   14578 **
   14579 ** This function returns the same value as datetime('now').
   14580 */
   14581 static void ctimestampFunc(
   14582   sqlite3_context *context,
   14583   int NotUsed,
   14584   sqlite3_value **NotUsed2
   14585 ){
   14586   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   14587   datetimeFunc(context, 0, 0);
   14588 }
   14589 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   14590 
   14591 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   14592 /*
   14593 ** If the library is compiled to omit the full-scale date and time
   14594 ** handling (to get a smaller binary), the following minimal version
   14595 ** of the functions current_time(), current_date() and current_timestamp()
   14596 ** are included instead. This is to support column declarations that
   14597 ** include "DEFAULT CURRENT_TIME" etc.
   14598 **
   14599 ** This function uses the C-library functions time(), gmtime()
   14600 ** and strftime(). The format string to pass to strftime() is supplied
   14601 ** as the user-data for the function.
   14602 */
   14603 static void currentTimeFunc(
   14604   sqlite3_context *context,
   14605   int argc,
   14606   sqlite3_value **argv
   14607 ){
   14608   time_t t;
   14609   char *zFormat = (char *)sqlite3_user_data(context);
   14610   sqlite3 *db;
   14611   sqlite3_int64 iT;
   14612   struct tm *pTm;
   14613   struct tm sNow;
   14614   char zBuf[20];
   14615 
   14616   UNUSED_PARAMETER(argc);
   14617   UNUSED_PARAMETER(argv);
   14618 
   14619   db = sqlite3_context_db_handle(context);
   14620   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
   14621   t = iT/1000 - 10000*(sqlite3_int64)21086676;
   14622 #ifdef HAVE_GMTIME_R
   14623   pTm = gmtime_r(&t, &sNow);
   14624 #else
   14625   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   14626   pTm = gmtime(&t);
   14627   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
   14628   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   14629 #endif
   14630   if( pTm ){
   14631     strftime(zBuf, 20, zFormat, &sNow);
   14632     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   14633   }
   14634 }
   14635 #endif
   14636 
   14637 /*
   14638 ** This function registered all of the above C functions as SQL
   14639 ** functions.  This should be the only routine in this file with
   14640 ** external linkage.
   14641 */
   14642 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   14643   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
   14644 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   14645     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
   14646     FUNCTION(date,             -1, 0, 0, dateFunc      ),
   14647     FUNCTION(time,             -1, 0, 0, timeFunc      ),
   14648     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
   14649     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
   14650     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   14651     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   14652     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   14653 #else
   14654     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   14655     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
   14656     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   14657 #endif
   14658   };
   14659   int i;
   14660   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   14661   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
   14662 
   14663   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
   14664     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   14665   }
   14666 }
   14667 
   14668 /************** End of date.c ************************************************/
   14669 /************** Begin file os.c **********************************************/
   14670 /*
   14671 ** 2005 November 29
   14672 **
   14673 ** The author disclaims copyright to this source code.  In place of
   14674 ** a legal notice, here is a blessing:
   14675 **
   14676 **    May you do good and not evil.
   14677 **    May you find forgiveness for yourself and forgive others.
   14678 **    May you share freely, never taking more than you give.
   14679 **
   14680 ******************************************************************************
   14681 **
   14682 ** This file contains OS interface code that is common to all
   14683 ** architectures.
   14684 */
   14685 #define _SQLITE_OS_C_ 1
   14686 #undef _SQLITE_OS_C_
   14687 
   14688 /*
   14689 ** The default SQLite sqlite3_vfs implementations do not allocate
   14690 ** memory (actually, os_unix.c allocates a small amount of memory
   14691 ** from within OsOpen()), but some third-party implementations may.
   14692 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   14693 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   14694 **
   14695 ** The following functions are instrumented for malloc() failure
   14696 ** testing:
   14697 **
   14698 **     sqlite3OsRead()
   14699 **     sqlite3OsWrite()
   14700 **     sqlite3OsSync()
   14701 **     sqlite3OsFileSize()
   14702 **     sqlite3OsLock()
   14703 **     sqlite3OsCheckReservedLock()
   14704 **     sqlite3OsFileControl()
   14705 **     sqlite3OsShmMap()
   14706 **     sqlite3OsOpen()
   14707 **     sqlite3OsDelete()
   14708 **     sqlite3OsAccess()
   14709 **     sqlite3OsFullPathname()
   14710 **
   14711 */
   14712 #if defined(SQLITE_TEST)
   14713 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
   14714   #define DO_OS_MALLOC_TEST(x)                                       \
   14715   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
   14716     void *pTstAlloc = sqlite3Malloc(10);                             \
   14717     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
   14718     sqlite3_free(pTstAlloc);                                         \
   14719   }
   14720 #else
   14721   #define DO_OS_MALLOC_TEST(x)
   14722 #endif
   14723 
   14724 /*
   14725 ** The following routines are convenience wrappers around methods
   14726 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   14727 ** of this would be completely automatic if SQLite were coded using
   14728 ** C++ instead of plain old C.
   14729 */
   14730 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
   14731   int rc = SQLITE_OK;
   14732   if( pId->pMethods ){
   14733     rc = pId->pMethods->xClose(pId);
   14734     pId->pMethods = 0;
   14735   }
   14736   return rc;
   14737 }
   14738 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   14739   DO_OS_MALLOC_TEST(id);
   14740   return id->pMethods->xRead(id, pBuf, amt, offset);
   14741 }
   14742 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   14743   DO_OS_MALLOC_TEST(id);
   14744   return id->pMethods->xWrite(id, pBuf, amt, offset);
   14745 }
   14746 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   14747   return id->pMethods->xTruncate(id, size);
   14748 }
   14749 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   14750   DO_OS_MALLOC_TEST(id);
   14751   return id->pMethods->xSync(id, flags);
   14752 }
   14753 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   14754   DO_OS_MALLOC_TEST(id);
   14755   return id->pMethods->xFileSize(id, pSize);
   14756 }
   14757 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   14758   DO_OS_MALLOC_TEST(id);
   14759   return id->pMethods->xLock(id, lockType);
   14760 }
   14761 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   14762   return id->pMethods->xUnlock(id, lockType);
   14763 }
   14764 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   14765   DO_OS_MALLOC_TEST(id);
   14766   return id->pMethods->xCheckReservedLock(id, pResOut);
   14767 }
   14768 
   14769 /*
   14770 ** Use sqlite3OsFileControl() when we are doing something that might fail
   14771 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
   14772 ** when simply tossing information over the wall to the VFS and we do not
   14773 ** really care if the VFS receives and understands the information since it
   14774 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
   14775 ** routine has no return value since the return value would be meaningless.
   14776 */
   14777 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   14778   DO_OS_MALLOC_TEST(id);
   14779   return id->pMethods->xFileControl(id, op, pArg);
   14780 }
   14781 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
   14782   (void)id->pMethods->xFileControl(id, op, pArg);
   14783 }
   14784 
   14785 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   14786   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   14787   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   14788 }
   14789 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   14790   return id->pMethods->xDeviceCharacteristics(id);
   14791 }
   14792 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
   14793   return id->pMethods->xShmLock(id, offset, n, flags);
   14794 }
   14795 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
   14796   id->pMethods->xShmBarrier(id);
   14797 }
   14798 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
   14799   return id->pMethods->xShmUnmap(id, deleteFlag);
   14800 }
   14801 SQLITE_PRIVATE int sqlite3OsShmMap(
   14802   sqlite3_file *id,               /* Database file handle */
   14803   int iPage,
   14804   int pgsz,
   14805   int bExtend,                    /* True to extend file if necessary */
   14806   void volatile **pp              /* OUT: Pointer to mapping */
   14807 ){
   14808   DO_OS_MALLOC_TEST(id);
   14809   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
   14810 }
   14811 
   14812 /*
   14813 ** The next group of routines are convenience wrappers around the
   14814 ** VFS methods.
   14815 */
   14816 SQLITE_PRIVATE int sqlite3OsOpen(
   14817   sqlite3_vfs *pVfs,
   14818   const char *zPath,
   14819   sqlite3_file *pFile,
   14820   int flags,
   14821   int *pFlagsOut
   14822 ){
   14823   int rc;
   14824   DO_OS_MALLOC_TEST(0);
   14825   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   14826   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   14827   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   14828   ** reaching the VFS. */
   14829   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
   14830   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   14831   return rc;
   14832 }
   14833 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   14834   DO_OS_MALLOC_TEST(0);
   14835   assert( dirSync==0 || dirSync==1 );
   14836   return pVfs->xDelete(pVfs, zPath, dirSync);
   14837 }
   14838 SQLITE_PRIVATE int sqlite3OsAccess(
   14839   sqlite3_vfs *pVfs,
   14840   const char *zPath,
   14841   int flags,
   14842   int *pResOut
   14843 ){
   14844   DO_OS_MALLOC_TEST(0);
   14845   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   14846 }
   14847 SQLITE_PRIVATE int sqlite3OsFullPathname(
   14848   sqlite3_vfs *pVfs,
   14849   const char *zPath,
   14850   int nPathOut,
   14851   char *zPathOut
   14852 ){
   14853   DO_OS_MALLOC_TEST(0);
   14854   zPathOut[0] = 0;
   14855   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   14856 }
   14857 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   14858 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   14859   return pVfs->xDlOpen(pVfs, zPath);
   14860 }
   14861 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   14862   pVfs->xDlError(pVfs, nByte, zBufOut);
   14863 }
   14864 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   14865   return pVfs->xDlSym(pVfs, pHdle, zSym);
   14866 }
   14867 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   14868   pVfs->xDlClose(pVfs, pHandle);
   14869 }
   14870 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   14871 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   14872   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   14873 }
   14874 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   14875   return pVfs->xSleep(pVfs, nMicro);
   14876 }
   14877 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
   14878   int rc;
   14879   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
   14880   ** method to get the current date and time if that method is available
   14881   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
   14882   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
   14883   ** unavailable.
   14884   */
   14885   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
   14886     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
   14887   }else{
   14888     double r;
   14889     rc = pVfs->xCurrentTime(pVfs, &r);
   14890     *pTimeOut = (sqlite3_int64)(r*86400000.0);
   14891   }
   14892   return rc;
   14893 }
   14894 
   14895 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   14896   sqlite3_vfs *pVfs,
   14897   const char *zFile,
   14898   sqlite3_file **ppFile,
   14899   int flags,
   14900   int *pOutFlags
   14901 ){
   14902   int rc = SQLITE_NOMEM;
   14903   sqlite3_file *pFile;
   14904   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
   14905   if( pFile ){
   14906     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   14907     if( rc!=SQLITE_OK ){
   14908       sqlite3_free(pFile);
   14909     }else{
   14910       *ppFile = pFile;
   14911     }
   14912   }
   14913   return rc;
   14914 }
   14915 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
   14916   int rc = SQLITE_OK;
   14917   assert( pFile );
   14918   rc = sqlite3OsClose(pFile);
   14919   sqlite3_free(pFile);
   14920   return rc;
   14921 }
   14922 
   14923 /*
   14924 ** This function is a wrapper around the OS specific implementation of
   14925 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   14926 ** ability to simulate a malloc failure, so that the handling of an
   14927 ** error in sqlite3_os_init() by the upper layers can be tested.
   14928 */
   14929 SQLITE_PRIVATE int sqlite3OsInit(void){
   14930   void *p = sqlite3_malloc(10);
   14931   if( p==0 ) return SQLITE_NOMEM;
   14932   sqlite3_free(p);
   14933   return sqlite3_os_init();
   14934 }
   14935 
   14936 /*
   14937 ** The list of all registered VFS implementations.
   14938 */
   14939 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   14940 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   14941 
   14942 /*
   14943 ** Locate a VFS by name.  If no name is given, simply return the
   14944 ** first VFS on the list.
   14945 */
   14946 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   14947   sqlite3_vfs *pVfs = 0;
   14948 #if SQLITE_THREADSAFE
   14949   sqlite3_mutex *mutex;
   14950 #endif
   14951 #ifndef SQLITE_OMIT_AUTOINIT
   14952   int rc = sqlite3_initialize();
   14953   if( rc ) return 0;
   14954 #endif
   14955 #if SQLITE_THREADSAFE
   14956   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   14957 #endif
   14958   sqlite3_mutex_enter(mutex);
   14959   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   14960     if( zVfs==0 ) break;
   14961     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   14962   }
   14963   sqlite3_mutex_leave(mutex);
   14964   return pVfs;
   14965 }
   14966 
   14967 /*
   14968 ** Unlink a VFS from the linked list
   14969 */
   14970 static void vfsUnlink(sqlite3_vfs *pVfs){
   14971   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   14972   if( pVfs==0 ){
   14973     /* No-op */
   14974   }else if( vfsList==pVfs ){
   14975     vfsList = pVfs->pNext;
   14976   }else if( vfsList ){
   14977     sqlite3_vfs *p = vfsList;
   14978     while( p->pNext && p->pNext!=pVfs ){
   14979       p = p->pNext;
   14980     }
   14981     if( p->pNext==pVfs ){
   14982       p->pNext = pVfs->pNext;
   14983     }
   14984   }
   14985 }
   14986 
   14987 /*
   14988 ** Register a VFS with the system.  It is harmless to register the same
   14989 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   14990 ** true.
   14991 */
   14992 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   14993   MUTEX_LOGIC(sqlite3_mutex *mutex;)
   14994 #ifndef SQLITE_OMIT_AUTOINIT
   14995   int rc = sqlite3_initialize();
   14996   if( rc ) return rc;
   14997 #endif
   14998   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   14999   sqlite3_mutex_enter(mutex);
   15000   vfsUnlink(pVfs);
   15001   if( makeDflt || vfsList==0 ){
   15002     pVfs->pNext = vfsList;
   15003     vfsList = pVfs;
   15004   }else{
   15005     pVfs->pNext = vfsList->pNext;
   15006     vfsList->pNext = pVfs;
   15007   }
   15008   assert(vfsList);
   15009   sqlite3_mutex_leave(mutex);
   15010   return SQLITE_OK;
   15011 }
   15012 
   15013 /*
   15014 ** Unregister a VFS so that it is no longer accessible.
   15015 */
   15016 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   15017 #if SQLITE_THREADSAFE
   15018   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   15019 #endif
   15020   sqlite3_mutex_enter(mutex);
   15021   vfsUnlink(pVfs);
   15022   sqlite3_mutex_leave(mutex);
   15023   return SQLITE_OK;
   15024 }
   15025 
   15026 /************** End of os.c **************************************************/
   15027 /************** Begin file fault.c *******************************************/
   15028 /*
   15029 ** 2008 Jan 22
   15030 **
   15031 ** The author disclaims copyright to this source code.  In place of
   15032 ** a legal notice, here is a blessing:
   15033 **
   15034 **    May you do good and not evil.
   15035 **    May you find forgiveness for yourself and forgive others.
   15036 **    May you share freely, never taking more than you give.
   15037 **
   15038 *************************************************************************
   15039 **
   15040 ** This file contains code to support the concept of "benign"
   15041 ** malloc failures (when the xMalloc() or xRealloc() method of the
   15042 ** sqlite3_mem_methods structure fails to allocate a block of memory
   15043 ** and returns 0).
   15044 **
   15045 ** Most malloc failures are non-benign. After they occur, SQLite
   15046 ** abandons the current operation and returns an error code (usually
   15047 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   15048 ** fatal. For example, if a malloc fails while resizing a hash table, this
   15049 ** is completely recoverable simply by not carrying out the resize. The
   15050 ** hash table will continue to function normally.  So a malloc failure
   15051 ** during a hash table resize is a benign fault.
   15052 */
   15053 
   15054 
   15055 #ifndef SQLITE_OMIT_BUILTIN_TEST
   15056 
   15057 /*
   15058 ** Global variables.
   15059 */
   15060 typedef struct BenignMallocHooks BenignMallocHooks;
   15061 static SQLITE_WSD struct BenignMallocHooks {
   15062   void (*xBenignBegin)(void);
   15063   void (*xBenignEnd)(void);
   15064 } sqlite3Hooks = { 0, 0 };
   15065 
   15066 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   15067 ** structure.  If writable static data is unsupported on the target,
   15068 ** we have to locate the state vector at run-time.  In the more common
   15069 ** case where writable static data is supported, wsdHooks can refer directly
   15070 ** to the "sqlite3Hooks" state vector declared above.
   15071 */
   15072 #ifdef SQLITE_OMIT_WSD
   15073 # define wsdHooksInit \
   15074   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   15075 # define wsdHooks x[0]
   15076 #else
   15077 # define wsdHooksInit
   15078 # define wsdHooks sqlite3Hooks
   15079 #endif
   15080 
   15081 
   15082 /*
   15083 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   15084 ** sqlite3EndBenignMalloc() are called, respectively.
   15085 */
   15086 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   15087   void (*xBenignBegin)(void),
   15088   void (*xBenignEnd)(void)
   15089 ){
   15090   wsdHooksInit;
   15091   wsdHooks.xBenignBegin = xBenignBegin;
   15092   wsdHooks.xBenignEnd = xBenignEnd;
   15093 }
   15094 
   15095 /*
   15096 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   15097 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   15098 ** indicates that subsequent malloc failures are non-benign.
   15099 */
   15100 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   15101   wsdHooksInit;
   15102   if( wsdHooks.xBenignBegin ){
   15103     wsdHooks.xBenignBegin();
   15104   }
   15105 }
   15106 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   15107   wsdHooksInit;
   15108   if( wsdHooks.xBenignEnd ){
   15109     wsdHooks.xBenignEnd();
   15110   }
   15111 }
   15112 
   15113 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
   15114 
   15115 /************** End of fault.c ***********************************************/
   15116 /************** Begin file mem0.c ********************************************/
   15117 /*
   15118 ** 2008 October 28
   15119 **
   15120 ** The author disclaims copyright to this source code.  In place of
   15121 ** a legal notice, here is a blessing:
   15122 **
   15123 **    May you do good and not evil.
   15124 **    May you find forgiveness for yourself and forgive others.
   15125 **    May you share freely, never taking more than you give.
   15126 **
   15127 *************************************************************************
   15128 **
   15129 ** This file contains a no-op memory allocation drivers for use when
   15130 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   15131 ** here always fail.  SQLite will not operate with these drivers.  These
   15132 ** are merely placeholders.  Real drivers must be substituted using
   15133 ** sqlite3_config() before SQLite will operate.
   15134 */
   15135 
   15136 /*
   15137 ** This version of the memory allocator is the default.  It is
   15138 ** used when no other memory allocator is specified using compile-time
   15139 ** macros.
   15140 */
   15141 #ifdef SQLITE_ZERO_MALLOC
   15142 
   15143 /*
   15144 ** No-op versions of all memory allocation routines
   15145 */
   15146 static void *sqlite3MemMalloc(int nByte){ return 0; }
   15147 static void sqlite3MemFree(void *pPrior){ return; }
   15148 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   15149 static int sqlite3MemSize(void *pPrior){ return 0; }
   15150 static int sqlite3MemRoundup(int n){ return n; }
   15151 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   15152 static void sqlite3MemShutdown(void *NotUsed){ return; }
   15153 
   15154 /*
   15155 ** This routine is the only routine in this file with external linkage.
   15156 **
   15157 ** Populate the low-level memory allocation function pointers in
   15158 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   15159 */
   15160 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   15161   static const sqlite3_mem_methods defaultMethods = {
   15162      sqlite3MemMalloc,
   15163      sqlite3MemFree,
   15164      sqlite3MemRealloc,
   15165      sqlite3MemSize,
   15166      sqlite3MemRoundup,
   15167      sqlite3MemInit,
   15168      sqlite3MemShutdown,
   15169      0
   15170   };
   15171   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   15172 }
   15173 
   15174 #endif /* SQLITE_ZERO_MALLOC */
   15175 
   15176 /************** End of mem0.c ************************************************/
   15177 /************** Begin file mem1.c ********************************************/
   15178 /*
   15179 ** 2007 August 14
   15180 **
   15181 ** The author disclaims copyright to this source code.  In place of
   15182 ** a legal notice, here is a blessing:
   15183 **
   15184 **    May you do good and not evil.
   15185 **    May you find forgiveness for yourself and forgive others.
   15186 **    May you share freely, never taking more than you give.
   15187 **
   15188 *************************************************************************
   15189 **
   15190 ** This file contains low-level memory allocation drivers for when
   15191 ** SQLite will use the standard C-library malloc/realloc/free interface
   15192 ** to obtain the memory it needs.
   15193 **
   15194 ** This file contains implementations of the low-level memory allocation
   15195 ** routines specified in the sqlite3_mem_methods object.  The content of
   15196 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
   15197 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
   15198 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
   15199 ** default configuration is to use memory allocation routines in this
   15200 ** file.
   15201 **
   15202 ** C-preprocessor macro summary:
   15203 **
   15204 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
   15205 **                                the malloc_usable_size() interface exists
   15206 **                                on the target platform.  Or, this symbol
   15207 **                                can be set manually, if desired.
   15208 **                                If an equivalent interface exists by
   15209 **                                a different name, using a separate -D
   15210 **                                option to rename it.
   15211 **
   15212 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
   15213 **                                memory allocator.  Set this symbol to enable
   15214 **                                building on older macs.
   15215 **
   15216 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
   15217 **                                _msize() on windows systems.  This might
   15218 **                                be necessary when compiling for Delphi,
   15219 **                                for example.
   15220 */
   15221 
   15222 /*
   15223 ** This version of the memory allocator is the default.  It is
   15224 ** used when no other memory allocator is specified using compile-time
   15225 ** macros.
   15226 */
   15227 #ifdef SQLITE_SYSTEM_MALLOC
   15228 
   15229 /*
   15230 ** The MSVCRT has malloc_usable_size() but it is called _msize().
   15231 ** The use of _msize() is automatic, but can be disabled by compiling
   15232 ** with -DSQLITE_WITHOUT_MSIZE
   15233 */
   15234 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
   15235 # define SQLITE_MALLOCSIZE _msize
   15236 #endif
   15237 
   15238 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   15239 
   15240 /*
   15241 ** Use the zone allocator available on apple products unless the
   15242 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
   15243 */
   15244 #include <sys/sysctl.h>
   15245 #include <malloc/malloc.h>
   15246 #include <libkern/OSAtomic.h>
   15247 static malloc_zone_t* _sqliteZone_;
   15248 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
   15249 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
   15250 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
   15251 #define SQLITE_MALLOCSIZE(x) \
   15252         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
   15253 
   15254 #else /* if not __APPLE__ */
   15255 
   15256 /*
   15257 ** Use standard C library malloc and free on non-Apple systems.
   15258 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
   15259 */
   15260 #define SQLITE_MALLOC(x)    malloc(x)
   15261 #define SQLITE_FREE(x)      free(x)
   15262 #define SQLITE_REALLOC(x,y) realloc((x),(y))
   15263 
   15264 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
   15265       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
   15266 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
   15267 #endif
   15268 #ifdef HAVE_MALLOC_USABLE_SIZE
   15269 # ifndef SQLITE_MALLOCSIZE
   15270 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
   15271 # endif
   15272 #else
   15273 # undef SQLITE_MALLOCSIZE
   15274 #endif
   15275 
   15276 #endif /* __APPLE__ or not __APPLE__ */
   15277 
   15278 /*
   15279 ** Like malloc(), but remember the size of the allocation
   15280 ** so that we can find it later using sqlite3MemSize().
   15281 **
   15282 ** For this low-level routine, we are guaranteed that nByte>0 because
   15283 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   15284 ** routines.
   15285 */
   15286 static void *sqlite3MemMalloc(int nByte){
   15287 #ifdef SQLITE_MALLOCSIZE
   15288   void *p = SQLITE_MALLOC( nByte );
   15289   if( p==0 ){
   15290     testcase( sqlite3GlobalConfig.xLog!=0 );
   15291     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   15292   }
   15293   return p;
   15294 #else
   15295   sqlite3_int64 *p;
   15296   assert( nByte>0 );
   15297   nByte = ROUND8(nByte);
   15298   p = SQLITE_MALLOC( nByte+8 );
   15299   if( p ){
   15300     p[0] = nByte;
   15301     p++;
   15302   }else{
   15303     testcase( sqlite3GlobalConfig.xLog!=0 );
   15304     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   15305   }
   15306   return (void *)p;
   15307 #endif
   15308 }
   15309 
   15310 /*
   15311 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   15312 ** or sqlite3MemRealloc().
   15313 **
   15314 ** For this low-level routine, we already know that pPrior!=0 since
   15315 ** cases where pPrior==0 will have been intecepted and dealt with
   15316 ** by higher-level routines.
   15317 */
   15318 static void sqlite3MemFree(void *pPrior){
   15319 #ifdef SQLITE_MALLOCSIZE
   15320   SQLITE_FREE(pPrior);
   15321 #else
   15322   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   15323   assert( pPrior!=0 );
   15324   p--;
   15325   SQLITE_FREE(p);
   15326 #endif
   15327 }
   15328 
   15329 /*
   15330 ** Report the allocated size of a prior return from xMalloc()
   15331 ** or xRealloc().
   15332 */
   15333 static int sqlite3MemSize(void *pPrior){
   15334 #ifdef SQLITE_MALLOCSIZE
   15335   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
   15336 #else
   15337   sqlite3_int64 *p;
   15338   if( pPrior==0 ) return 0;
   15339   p = (sqlite3_int64*)pPrior;
   15340   p--;
   15341   return (int)p[0];
   15342 #endif
   15343 }
   15344 
   15345 /*
   15346 ** Like realloc().  Resize an allocation previously obtained from
   15347 ** sqlite3MemMalloc().
   15348 **
   15349 ** For this low-level interface, we know that pPrior!=0.  Cases where
   15350 ** pPrior==0 while have been intercepted by higher-level routine and
   15351 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
   15352 ** cases where nByte<=0 will have been intercepted by higher-level
   15353 ** routines and redirected to xFree.
   15354 */
   15355 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   15356 #ifdef SQLITE_MALLOCSIZE
   15357   void *p = SQLITE_REALLOC(pPrior, nByte);
   15358   if( p==0 ){
   15359     testcase( sqlite3GlobalConfig.xLog!=0 );
   15360     sqlite3_log(SQLITE_NOMEM,
   15361       "failed memory resize %u to %u bytes",
   15362       SQLITE_MALLOCSIZE(pPrior), nByte);
   15363   }
   15364   return p;
   15365 #else
   15366   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   15367   assert( pPrior!=0 && nByte>0 );
   15368   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
   15369   p--;
   15370   p = SQLITE_REALLOC(p, nByte+8 );
   15371   if( p ){
   15372     p[0] = nByte;
   15373     p++;
   15374   }else{
   15375     testcase( sqlite3GlobalConfig.xLog!=0 );
   15376     sqlite3_log(SQLITE_NOMEM,
   15377       "failed memory resize %u to %u bytes",
   15378       sqlite3MemSize(pPrior), nByte);
   15379   }
   15380   return (void*)p;
   15381 #endif
   15382 }
   15383 
   15384 /*
   15385 ** Round up a request size to the next valid allocation size.
   15386 */
   15387 static int sqlite3MemRoundup(int n){
   15388   return ROUND8(n);
   15389 }
   15390 
   15391 /*
   15392 ** Initialize this module.
   15393 */
   15394 static int sqlite3MemInit(void *NotUsed){
   15395 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
   15396   int cpuCount;
   15397   size_t len;
   15398   if( _sqliteZone_ ){
   15399     return SQLITE_OK;
   15400   }
   15401   len = sizeof(cpuCount);
   15402   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
   15403   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
   15404   if( cpuCount>1 ){
   15405     /* defer MT decisions to system malloc */
   15406     _sqliteZone_ = malloc_default_zone();
   15407   }else{
   15408     /* only 1 core, use our own zone to contention over global locks,
   15409     ** e.g. we have our own dedicated locks */
   15410     bool success;
   15411     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
   15412     malloc_set_zone_name(newzone, "Sqlite_Heap");
   15413     do{
   15414       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
   15415                                  (void * volatile *)&_sqliteZone_);
   15416     }while(!_sqliteZone_);
   15417     if( !success ){
   15418       /* somebody registered a zone first */
   15419       malloc_destroy_zone(newzone);
   15420     }
   15421   }
   15422 #endif
   15423   UNUSED_PARAMETER(NotUsed);
   15424   return SQLITE_OK;
   15425 }
   15426 
   15427 /*
   15428 ** Deinitialize this module.
   15429 */
   15430 static void sqlite3MemShutdown(void *NotUsed){
   15431   UNUSED_PARAMETER(NotUsed);
   15432   return;
   15433 }
   15434 
   15435 /*
   15436 ** This routine is the only routine in this file with external linkage.
   15437 **
   15438 ** Populate the low-level memory allocation function pointers in
   15439 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   15440 */
   15441 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   15442   static const sqlite3_mem_methods defaultMethods = {
   15443      sqlite3MemMalloc,
   15444      sqlite3MemFree,
   15445      sqlite3MemRealloc,
   15446      sqlite3MemSize,
   15447      sqlite3MemRoundup,
   15448      sqlite3MemInit,
   15449      sqlite3MemShutdown,
   15450      0
   15451   };
   15452   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   15453 }
   15454 
   15455 #endif /* SQLITE_SYSTEM_MALLOC */
   15456 
   15457 /************** End of mem1.c ************************************************/
   15458 /************** Begin file mem2.c ********************************************/
   15459 /*
   15460 ** 2007 August 15
   15461 **
   15462 ** The author disclaims copyright to this source code.  In place of
   15463 ** a legal notice, here is a blessing:
   15464 **
   15465 **    May you do good and not evil.
   15466 **    May you find forgiveness for yourself and forgive others.
   15467 **    May you share freely, never taking more than you give.
   15468 **
   15469 *************************************************************************
   15470 **
   15471 ** This file contains low-level memory allocation drivers for when
   15472 ** SQLite will use the standard C-library malloc/realloc/free interface
   15473 ** to obtain the memory it needs while adding lots of additional debugging
   15474 ** information to each allocation in order to help detect and fix memory
   15475 ** leaks and memory usage errors.
   15476 **
   15477 ** This file contains implementations of the low-level memory allocation
   15478 ** routines specified in the sqlite3_mem_methods object.
   15479 */
   15480 
   15481 /*
   15482 ** This version of the memory allocator is used only if the
   15483 ** SQLITE_MEMDEBUG macro is defined
   15484 */
   15485 #ifdef SQLITE_MEMDEBUG
   15486 
   15487 /*
   15488 ** The backtrace functionality is only available with GLIBC
   15489 */
   15490 #ifdef __GLIBC__
   15491   extern int backtrace(void**,int);
   15492   extern void backtrace_symbols_fd(void*const*,int,int);
   15493 #else
   15494 # define backtrace(A,B) 1
   15495 # define backtrace_symbols_fd(A,B,C)
   15496 #endif
   15497 /* #include <stdio.h> */
   15498 
   15499 /*
   15500 ** Each memory allocation looks like this:
   15501 **
   15502 **  ------------------------------------------------------------------------
   15503 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   15504 **  ------------------------------------------------------------------------
   15505 **
   15506 ** The application code sees only a pointer to the allocation.  We have
   15507 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   15508 ** MemBlockHdr tells us the size of the allocation and the number of
   15509 ** backtrace pointers.  There is also a guard word at the end of the
   15510 ** MemBlockHdr.
   15511 */
   15512 struct MemBlockHdr {
   15513   i64 iSize;                          /* Size of this allocation */
   15514   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   15515   char nBacktrace;                    /* Number of backtraces on this alloc */
   15516   char nBacktraceSlots;               /* Available backtrace slots */
   15517   u8 nTitle;                          /* Bytes of title; includes '\0' */
   15518   u8 eType;                           /* Allocation type code */
   15519   int iForeGuard;                     /* Guard word for sanity */
   15520 };
   15521 
   15522 /*
   15523 ** Guard words
   15524 */
   15525 #define FOREGUARD 0x80F5E153
   15526 #define REARGUARD 0xE4676B53
   15527 
   15528 /*
   15529 ** Number of malloc size increments to track.
   15530 */
   15531 #define NCSIZE  1000
   15532 
   15533 /*
   15534 ** All of the static variables used by this module are collected
   15535 ** into a single structure named "mem".  This is to keep the
   15536 ** static variables organized and to reduce namespace pollution
   15537 ** when this module is combined with other in the amalgamation.
   15538 */
   15539 static struct {
   15540 
   15541   /*
   15542   ** Mutex to control access to the memory allocation subsystem.
   15543   */
   15544   sqlite3_mutex *mutex;
   15545 
   15546   /*
   15547   ** Head and tail of a linked list of all outstanding allocations
   15548   */
   15549   struct MemBlockHdr *pFirst;
   15550   struct MemBlockHdr *pLast;
   15551 
   15552   /*
   15553   ** The number of levels of backtrace to save in new allocations.
   15554   */
   15555   int nBacktrace;
   15556   void (*xBacktrace)(int, int, void **);
   15557 
   15558   /*
   15559   ** Title text to insert in front of each block
   15560   */
   15561   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   15562   char zTitle[100];  /* The title text */
   15563 
   15564   /*
   15565   ** sqlite3MallocDisallow() increments the following counter.
   15566   ** sqlite3MallocAllow() decrements it.
   15567   */
   15568   int disallow; /* Do not allow memory allocation */
   15569 
   15570   /*
   15571   ** Gather statistics on the sizes of memory allocations.
   15572   ** nAlloc[i] is the number of allocation attempts of i*8
   15573   ** bytes.  i==NCSIZE is the number of allocation attempts for
   15574   ** sizes more than NCSIZE*8 bytes.
   15575   */
   15576   int nAlloc[NCSIZE];      /* Total number of allocations */
   15577   int nCurrent[NCSIZE];    /* Current number of allocations */
   15578   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   15579 
   15580 } mem;
   15581 
   15582 
   15583 /*
   15584 ** Adjust memory usage statistics
   15585 */
   15586 static void adjustStats(int iSize, int increment){
   15587   int i = ROUND8(iSize)/8;
   15588   if( i>NCSIZE-1 ){
   15589     i = NCSIZE - 1;
   15590   }
   15591   if( increment>0 ){
   15592     mem.nAlloc[i]++;
   15593     mem.nCurrent[i]++;
   15594     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   15595       mem.mxCurrent[i] = mem.nCurrent[i];
   15596     }
   15597   }else{
   15598     mem.nCurrent[i]--;
   15599     assert( mem.nCurrent[i]>=0 );
   15600   }
   15601 }
   15602 
   15603 /*
   15604 ** Given an allocation, find the MemBlockHdr for that allocation.
   15605 **
   15606 ** This routine checks the guards at either end of the allocation and
   15607 ** if they are incorrect it asserts.
   15608 */
   15609 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   15610   struct MemBlockHdr *p;
   15611   int *pInt;
   15612   u8 *pU8;
   15613   int nReserve;
   15614 
   15615   p = (struct MemBlockHdr*)pAllocation;
   15616   p--;
   15617   assert( p->iForeGuard==(int)FOREGUARD );
   15618   nReserve = ROUND8(p->iSize);
   15619   pInt = (int*)pAllocation;
   15620   pU8 = (u8*)pAllocation;
   15621   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   15622   /* This checks any of the "extra" bytes allocated due
   15623   ** to rounding up to an 8 byte boundary to ensure
   15624   ** they haven't been overwritten.
   15625   */
   15626   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   15627   return p;
   15628 }
   15629 
   15630 /*
   15631 ** Return the number of bytes currently allocated at address p.
   15632 */
   15633 static int sqlite3MemSize(void *p){
   15634   struct MemBlockHdr *pHdr;
   15635   if( !p ){
   15636     return 0;
   15637   }
   15638   pHdr = sqlite3MemsysGetHeader(p);
   15639   return pHdr->iSize;
   15640 }
   15641 
   15642 /*
   15643 ** Initialize the memory allocation subsystem.
   15644 */
   15645 static int sqlite3MemInit(void *NotUsed){
   15646   UNUSED_PARAMETER(NotUsed);
   15647   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   15648   if( !sqlite3GlobalConfig.bMemstat ){
   15649     /* If memory status is enabled, then the malloc.c wrapper will already
   15650     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   15651     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   15652   }
   15653   return SQLITE_OK;
   15654 }
   15655 
   15656 /*
   15657 ** Deinitialize the memory allocation subsystem.
   15658 */
   15659 static void sqlite3MemShutdown(void *NotUsed){
   15660   UNUSED_PARAMETER(NotUsed);
   15661   mem.mutex = 0;
   15662 }
   15663 
   15664 /*
   15665 ** Round up a request size to the next valid allocation size.
   15666 */
   15667 static int sqlite3MemRoundup(int n){
   15668   return ROUND8(n);
   15669 }
   15670 
   15671 /*
   15672 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   15673 ** the content of a new memory allocation to unpredictable values and
   15674 ** to clear the content of a freed allocation to unpredictable values.
   15675 */
   15676 static void randomFill(char *pBuf, int nByte){
   15677   unsigned int x, y, r;
   15678   x = SQLITE_PTR_TO_INT(pBuf);
   15679   y = nByte | 1;
   15680   while( nByte >= 4 ){
   15681     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   15682     y = y*1103515245 + 12345;
   15683     r = x ^ y;
   15684     *(int*)pBuf = r;
   15685     pBuf += 4;
   15686     nByte -= 4;
   15687   }
   15688   while( nByte-- > 0 ){
   15689     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   15690     y = y*1103515245 + 12345;
   15691     r = x ^ y;
   15692     *(pBuf++) = r & 0xff;
   15693   }
   15694 }
   15695 
   15696 /*
   15697 ** Allocate nByte bytes of memory.
   15698 */
   15699 static void *sqlite3MemMalloc(int nByte){
   15700   struct MemBlockHdr *pHdr;
   15701   void **pBt;
   15702   char *z;
   15703   int *pInt;
   15704   void *p = 0;
   15705   int totalSize;
   15706   int nReserve;
   15707   sqlite3_mutex_enter(mem.mutex);
   15708   assert( mem.disallow==0 );
   15709   nReserve = ROUND8(nByte);
   15710   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   15711                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   15712   p = malloc(totalSize);
   15713   if( p ){
   15714     z = p;
   15715     pBt = (void**)&z[mem.nTitle];
   15716     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   15717     pHdr->pNext = 0;
   15718     pHdr->pPrev = mem.pLast;
   15719     if( mem.pLast ){
   15720       mem.pLast->pNext = pHdr;
   15721     }else{
   15722       mem.pFirst = pHdr;
   15723     }
   15724     mem.pLast = pHdr;
   15725     pHdr->iForeGuard = FOREGUARD;
   15726     pHdr->eType = MEMTYPE_HEAP;
   15727     pHdr->nBacktraceSlots = mem.nBacktrace;
   15728     pHdr->nTitle = mem.nTitle;
   15729     if( mem.nBacktrace ){
   15730       void *aAddr[40];
   15731       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   15732       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   15733       assert(pBt[0]);
   15734       if( mem.xBacktrace ){
   15735         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   15736       }
   15737     }else{
   15738       pHdr->nBacktrace = 0;
   15739     }
   15740     if( mem.nTitle ){
   15741       memcpy(z, mem.zTitle, mem.nTitle);
   15742     }
   15743     pHdr->iSize = nByte;
   15744     adjustStats(nByte, +1);
   15745     pInt = (int*)&pHdr[1];
   15746     pInt[nReserve/sizeof(int)] = REARGUARD;
   15747     randomFill((char*)pInt, nByte);
   15748     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   15749     p = (void*)pInt;
   15750   }
   15751   sqlite3_mutex_leave(mem.mutex);
   15752   return p;
   15753 }
   15754 
   15755 /*
   15756 ** Free memory.
   15757 */
   15758 static void sqlite3MemFree(void *pPrior){
   15759   struct MemBlockHdr *pHdr;
   15760   void **pBt;
   15761   char *z;
   15762   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
   15763        || mem.mutex!=0 );
   15764   pHdr = sqlite3MemsysGetHeader(pPrior);
   15765   pBt = (void**)pHdr;
   15766   pBt -= pHdr->nBacktraceSlots;
   15767   sqlite3_mutex_enter(mem.mutex);
   15768   if( pHdr->pPrev ){
   15769     assert( pHdr->pPrev->pNext==pHdr );
   15770     pHdr->pPrev->pNext = pHdr->pNext;
   15771   }else{
   15772     assert( mem.pFirst==pHdr );
   15773     mem.pFirst = pHdr->pNext;
   15774   }
   15775   if( pHdr->pNext ){
   15776     assert( pHdr->pNext->pPrev==pHdr );
   15777     pHdr->pNext->pPrev = pHdr->pPrev;
   15778   }else{
   15779     assert( mem.pLast==pHdr );
   15780     mem.pLast = pHdr->pPrev;
   15781   }
   15782   z = (char*)pBt;
   15783   z -= pHdr->nTitle;
   15784   adjustStats(pHdr->iSize, -1);
   15785   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   15786                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
   15787   free(z);
   15788   sqlite3_mutex_leave(mem.mutex);
   15789 }
   15790 
   15791 /*
   15792 ** Change the size of an existing memory allocation.
   15793 **
   15794 ** For this debugging implementation, we *always* make a copy of the
   15795 ** allocation into a new place in memory.  In this way, if the
   15796 ** higher level code is using pointer to the old allocation, it is
   15797 ** much more likely to break and we are much more liking to find
   15798 ** the error.
   15799 */
   15800 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   15801   struct MemBlockHdr *pOldHdr;
   15802   void *pNew;
   15803   assert( mem.disallow==0 );
   15804   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
   15805   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   15806   pNew = sqlite3MemMalloc(nByte);
   15807   if( pNew ){
   15808     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
   15809     if( nByte>pOldHdr->iSize ){
   15810       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
   15811     }
   15812     sqlite3MemFree(pPrior);
   15813   }
   15814   return pNew;
   15815 }
   15816 
   15817 /*
   15818 ** Populate the low-level memory allocation function pointers in
   15819 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   15820 */
   15821 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   15822   static const sqlite3_mem_methods defaultMethods = {
   15823      sqlite3MemMalloc,
   15824      sqlite3MemFree,
   15825      sqlite3MemRealloc,
   15826      sqlite3MemSize,
   15827      sqlite3MemRoundup,
   15828      sqlite3MemInit,
   15829      sqlite3MemShutdown,
   15830      0
   15831   };
   15832   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   15833 }
   15834 
   15835 /*
   15836 ** Set the "type" of an allocation.
   15837 */
   15838 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
   15839   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   15840     struct MemBlockHdr *pHdr;
   15841     pHdr = sqlite3MemsysGetHeader(p);
   15842     assert( pHdr->iForeGuard==FOREGUARD );
   15843     pHdr->eType = eType;
   15844   }
   15845 }
   15846 
   15847 /*
   15848 ** Return TRUE if the mask of type in eType matches the type of the
   15849 ** allocation p.  Also return true if p==NULL.
   15850 **
   15851 ** This routine is designed for use within an assert() statement, to
   15852 ** verify the type of an allocation.  For example:
   15853 **
   15854 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   15855 */
   15856 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
   15857   int rc = 1;
   15858   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   15859     struct MemBlockHdr *pHdr;
   15860     pHdr = sqlite3MemsysGetHeader(p);
   15861     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   15862     if( (pHdr->eType&eType)==0 ){
   15863       rc = 0;
   15864     }
   15865   }
   15866   return rc;
   15867 }
   15868 
   15869 /*
   15870 ** Return TRUE if the mask of type in eType matches no bits of the type of the
   15871 ** allocation p.  Also return true if p==NULL.
   15872 **
   15873 ** This routine is designed for use within an assert() statement, to
   15874 ** verify the type of an allocation.  For example:
   15875 **
   15876 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   15877 */
   15878 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
   15879   int rc = 1;
   15880   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   15881     struct MemBlockHdr *pHdr;
   15882     pHdr = sqlite3MemsysGetHeader(p);
   15883     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   15884     if( (pHdr->eType&eType)!=0 ){
   15885       rc = 0;
   15886     }
   15887   }
   15888   return rc;
   15889 }
   15890 
   15891 /*
   15892 ** Set the number of backtrace levels kept for each allocation.
   15893 ** A value of zero turns off backtracing.  The number is always rounded
   15894 ** up to a multiple of 2.
   15895 */
   15896 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   15897   if( depth<0 ){ depth = 0; }
   15898   if( depth>20 ){ depth = 20; }
   15899   depth = (depth+1)&0xfe;
   15900   mem.nBacktrace = depth;
   15901 }
   15902 
   15903 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   15904   mem.xBacktrace = xBacktrace;
   15905 }
   15906 
   15907 /*
   15908 ** Set the title string for subsequent allocations.
   15909 */
   15910 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   15911   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   15912   sqlite3_mutex_enter(mem.mutex);
   15913   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   15914   memcpy(mem.zTitle, zTitle, n);
   15915   mem.zTitle[n] = 0;
   15916   mem.nTitle = ROUND8(n);
   15917   sqlite3_mutex_leave(mem.mutex);
   15918 }
   15919 
   15920 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   15921   struct MemBlockHdr *pHdr;
   15922   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   15923     void **pBt = (void**)pHdr;
   15924     pBt -= pHdr->nBacktraceSlots;
   15925     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   15926   }
   15927 }
   15928 
   15929 /*
   15930 ** Open the file indicated and write a log of all unfreed memory
   15931 ** allocations into that log.
   15932 */
   15933 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   15934   FILE *out;
   15935   struct MemBlockHdr *pHdr;
   15936   void **pBt;
   15937   int i;
   15938   out = fopen(zFilename, "w");
   15939   if( out==0 ){
   15940     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   15941                     zFilename);
   15942     return;
   15943   }
   15944   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   15945     char *z = (char*)pHdr;
   15946     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   15947     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   15948             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   15949     if( pHdr->nBacktrace ){
   15950       fflush(out);
   15951       pBt = (void**)pHdr;
   15952       pBt -= pHdr->nBacktraceSlots;
   15953       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   15954       fprintf(out, "\n");
   15955     }
   15956   }
   15957   fprintf(out, "COUNTS:\n");
   15958   for(i=0; i<NCSIZE-1; i++){
   15959     if( mem.nAlloc[i] ){
   15960       fprintf(out, "   %5d: %10d %10d %10d\n",
   15961             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   15962     }
   15963   }
   15964   if( mem.nAlloc[NCSIZE-1] ){
   15965     fprintf(out, "   %5d: %10d %10d %10d\n",
   15966              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   15967              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   15968   }
   15969   fclose(out);
   15970 }
   15971 
   15972 /*
   15973 ** Return the number of times sqlite3MemMalloc() has been called.
   15974 */
   15975 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   15976   int i;
   15977   int nTotal = 0;
   15978   for(i=0; i<NCSIZE; i++){
   15979     nTotal += mem.nAlloc[i];
   15980   }
   15981   return nTotal;
   15982 }
   15983 
   15984 
   15985 #endif /* SQLITE_MEMDEBUG */
   15986 
   15987 /************** End of mem2.c ************************************************/
   15988 /************** Begin file mem3.c ********************************************/
   15989 /*
   15990 ** 2007 October 14
   15991 **
   15992 ** The author disclaims copyright to this source code.  In place of
   15993 ** a legal notice, here is a blessing:
   15994 **
   15995 **    May you do good and not evil.
   15996 **    May you find forgiveness for yourself and forgive others.
   15997 **    May you share freely, never taking more than you give.
   15998 **
   15999 *************************************************************************
   16000 ** This file contains the C functions that implement a memory
   16001 ** allocation subsystem for use by SQLite.
   16002 **
   16003 ** This version of the memory allocation subsystem omits all
   16004 ** use of malloc(). The SQLite user supplies a block of memory
   16005 ** before calling sqlite3_initialize() from which allocations
   16006 ** are made and returned by the xMalloc() and xRealloc()
   16007 ** implementations. Once sqlite3_initialize() has been called,
   16008 ** the amount of memory available to SQLite is fixed and cannot
   16009 ** be changed.
   16010 **
   16011 ** This version of the memory allocation subsystem is included
   16012 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   16013 */
   16014 
   16015 /*
   16016 ** This version of the memory allocator is only built into the library
   16017 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   16018 ** mean that the library will use a memory-pool by default, just that
   16019 ** it is available. The mempool allocator is activated by calling
   16020 ** sqlite3_config().
   16021 */
   16022 #ifdef SQLITE_ENABLE_MEMSYS3
   16023 
   16024 /*
   16025 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   16026 */
   16027 #define MX_SMALL 10
   16028 
   16029 
   16030 /*
   16031 ** Number of freelist hash slots
   16032 */
   16033 #define N_HASH  61
   16034 
   16035 /*
   16036 ** A memory allocation (also called a "chunk") consists of two or
   16037 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   16038 ** a header that is not returned to the user.
   16039 **
   16040 ** A chunk is two or more blocks that is either checked out or
   16041 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   16042 ** size of the allocation in blocks if the allocation is free.
   16043 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   16044 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   16045 ** is true if the previous chunk is checked out and false if the
   16046 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   16047 ** the previous chunk in blocks if the previous chunk is on the
   16048 ** freelist. If the previous chunk is checked out, then
   16049 ** u.hdr.prevSize can be part of the data for that chunk and should
   16050 ** not be read or written.
   16051 **
   16052 ** We often identify a chunk by its index in mem3.aPool[].  When
   16053 ** this is done, the chunk index refers to the second block of
   16054 ** the chunk.  In this way, the first chunk has an index of 1.
   16055 ** A chunk index of 0 means "no such chunk" and is the equivalent
   16056 ** of a NULL pointer.
   16057 **
   16058 ** The second block of free chunks is of the form u.list.  The
   16059 ** two fields form a double-linked list of chunks of related sizes.
   16060 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   16061 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   16062 **
   16063 ** The second block of a chunk is user data if the chunk is checked
   16064 ** out.  If a chunk is checked out, the user data may extend into
   16065 ** the u.hdr.prevSize value of the following chunk.
   16066 */
   16067 typedef struct Mem3Block Mem3Block;
   16068 struct Mem3Block {
   16069   union {
   16070     struct {
   16071       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   16072       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   16073     } hdr;
   16074     struct {
   16075       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   16076       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   16077     } list;
   16078   } u;
   16079 };
   16080 
   16081 /*
   16082 ** All of the static variables used by this module are collected
   16083 ** into a single structure named "mem3".  This is to keep the
   16084 ** static variables organized and to reduce namespace pollution
   16085 ** when this module is combined with other in the amalgamation.
   16086 */
   16087 static SQLITE_WSD struct Mem3Global {
   16088   /*
   16089   ** Memory available for allocation. nPool is the size of the array
   16090   ** (in Mem3Blocks) pointed to by aPool less 2.
   16091   */
   16092   u32 nPool;
   16093   Mem3Block *aPool;
   16094 
   16095   /*
   16096   ** True if we are evaluating an out-of-memory callback.
   16097   */
   16098   int alarmBusy;
   16099 
   16100   /*
   16101   ** Mutex to control access to the memory allocation subsystem.
   16102   */
   16103   sqlite3_mutex *mutex;
   16104 
   16105   /*
   16106   ** The minimum amount of free space that we have seen.
   16107   */
   16108   u32 mnMaster;
   16109 
   16110   /*
   16111   ** iMaster is the index of the master chunk.  Most new allocations
   16112   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   16113   ** of the current master.  iMaster is 0 if there is not master chunk.
   16114   ** The master chunk is not in either the aiHash[] or aiSmall[].
   16115   */
   16116   u32 iMaster;
   16117   u32 szMaster;
   16118 
   16119   /*
   16120   ** Array of lists of free blocks according to the block size
   16121   ** for smaller chunks, or a hash on the block size for larger
   16122   ** chunks.
   16123   */
   16124   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   16125   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   16126 } mem3 = { 97535575 };
   16127 
   16128 #define mem3 GLOBAL(struct Mem3Global, mem3)
   16129 
   16130 /*
   16131 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   16132 ** on.  *pRoot is the list that i is a member of.
   16133 */
   16134 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   16135   u32 next = mem3.aPool[i].u.list.next;
   16136   u32 prev = mem3.aPool[i].u.list.prev;
   16137   assert( sqlite3_mutex_held(mem3.mutex) );
   16138   if( prev==0 ){
   16139     *pRoot = next;
   16140   }else{
   16141     mem3.aPool[prev].u.list.next = next;
   16142   }
   16143   if( next ){
   16144     mem3.aPool[next].u.list.prev = prev;
   16145   }
   16146   mem3.aPool[i].u.list.next = 0;
   16147   mem3.aPool[i].u.list.prev = 0;
   16148 }
   16149 
   16150 /*
   16151 ** Unlink the chunk at index i from
   16152 ** whatever list is currently a member of.
   16153 */
   16154 static void memsys3Unlink(u32 i){
   16155   u32 size, hash;
   16156   assert( sqlite3_mutex_held(mem3.mutex) );
   16157   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   16158   assert( i>=1 );
   16159   size = mem3.aPool[i-1].u.hdr.size4x/4;
   16160   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   16161   assert( size>=2 );
   16162   if( size <= MX_SMALL ){
   16163     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   16164   }else{
   16165     hash = size % N_HASH;
   16166     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   16167   }
   16168 }
   16169 
   16170 /*
   16171 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   16172 ** at *pRoot.
   16173 */
   16174 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   16175   assert( sqlite3_mutex_held(mem3.mutex) );
   16176   mem3.aPool[i].u.list.next = *pRoot;
   16177   mem3.aPool[i].u.list.prev = 0;
   16178   if( *pRoot ){
   16179     mem3.aPool[*pRoot].u.list.prev = i;
   16180   }
   16181   *pRoot = i;
   16182 }
   16183 
   16184 /*
   16185 ** Link the chunk at index i into either the appropriate
   16186 ** small chunk list, or into the large chunk hash table.
   16187 */
   16188 static void memsys3Link(u32 i){
   16189   u32 size, hash;
   16190   assert( sqlite3_mutex_held(mem3.mutex) );
   16191   assert( i>=1 );
   16192   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   16193   size = mem3.aPool[i-1].u.hdr.size4x/4;
   16194   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   16195   assert( size>=2 );
   16196   if( size <= MX_SMALL ){
   16197     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   16198   }else{
   16199     hash = size % N_HASH;
   16200     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   16201   }
   16202 }
   16203 
   16204 /*
   16205 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   16206 ** will already be held (obtained by code in malloc.c) if
   16207 ** sqlite3GlobalConfig.bMemStat is true.
   16208 */
   16209 static void memsys3Enter(void){
   16210   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   16211     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   16212   }
   16213   sqlite3_mutex_enter(mem3.mutex);
   16214 }
   16215 static void memsys3Leave(void){
   16216   sqlite3_mutex_leave(mem3.mutex);
   16217 }
   16218 
   16219 /*
   16220 ** Called when we are unable to satisfy an allocation of nBytes.
   16221 */
   16222 static void memsys3OutOfMemory(int nByte){
   16223   if( !mem3.alarmBusy ){
   16224     mem3.alarmBusy = 1;
   16225     assert( sqlite3_mutex_held(mem3.mutex) );
   16226     sqlite3_mutex_leave(mem3.mutex);
   16227     sqlite3_release_memory(nByte);
   16228     sqlite3_mutex_enter(mem3.mutex);
   16229     mem3.alarmBusy = 0;
   16230   }
   16231 }
   16232 
   16233 
   16234 /*
   16235 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   16236 ** size parameters for check-out and return a pointer to the
   16237 ** user portion of the chunk.
   16238 */
   16239 static void *memsys3Checkout(u32 i, u32 nBlock){
   16240   u32 x;
   16241   assert( sqlite3_mutex_held(mem3.mutex) );
   16242   assert( i>=1 );
   16243   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   16244   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   16245   x = mem3.aPool[i-1].u.hdr.size4x;
   16246   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   16247   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   16248   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   16249   return &mem3.aPool[i];
   16250 }
   16251 
   16252 /*
   16253 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   16254 ** Return a pointer to the new allocation.  Or, if the master chunk
   16255 ** is not large enough, return 0.
   16256 */
   16257 static void *memsys3FromMaster(u32 nBlock){
   16258   assert( sqlite3_mutex_held(mem3.mutex) );
   16259   assert( mem3.szMaster>=nBlock );
   16260   if( nBlock>=mem3.szMaster-1 ){
   16261     /* Use the entire master */
   16262     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   16263     mem3.iMaster = 0;
   16264     mem3.szMaster = 0;
   16265     mem3.mnMaster = 0;
   16266     return p;
   16267   }else{
   16268     /* Split the master block.  Return the tail. */
   16269     u32 newi, x;
   16270     newi = mem3.iMaster + mem3.szMaster - nBlock;
   16271     assert( newi > mem3.iMaster+1 );
   16272     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   16273     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   16274     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   16275     mem3.szMaster -= nBlock;
   16276     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   16277     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   16278     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   16279     if( mem3.szMaster < mem3.mnMaster ){
   16280       mem3.mnMaster = mem3.szMaster;
   16281     }
   16282     return (void*)&mem3.aPool[newi];
   16283   }
   16284 }
   16285 
   16286 /*
   16287 ** *pRoot is the head of a list of free chunks of the same size
   16288 ** or same size hash.  In other words, *pRoot is an entry in either
   16289 ** mem3.aiSmall[] or mem3.aiHash[].
   16290 **
   16291 ** This routine examines all entries on the given list and tries
   16292 ** to coalesce each entries with adjacent free chunks.
   16293 **
   16294 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   16295 ** the current mem3.iMaster with the new larger chunk.  In order for
   16296 ** this mem3.iMaster replacement to work, the master chunk must be
   16297 ** linked into the hash tables.  That is not the normal state of
   16298 ** affairs, of course.  The calling routine must link the master
   16299 ** chunk before invoking this routine, then must unlink the (possibly
   16300 ** changed) master chunk once this routine has finished.
   16301 */
   16302 static void memsys3Merge(u32 *pRoot){
   16303   u32 iNext, prev, size, i, x;
   16304 
   16305   assert( sqlite3_mutex_held(mem3.mutex) );
   16306   for(i=*pRoot; i>0; i=iNext){
   16307     iNext = mem3.aPool[i].u.list.next;
   16308     size = mem3.aPool[i-1].u.hdr.size4x;
   16309     assert( (size&1)==0 );
   16310     if( (size&2)==0 ){
   16311       memsys3UnlinkFromList(i, pRoot);
   16312       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   16313       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   16314       if( prev==iNext ){
   16315         iNext = mem3.aPool[prev].u.list.next;
   16316       }
   16317       memsys3Unlink(prev);
   16318       size = i + size/4 - prev;
   16319       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   16320       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   16321       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   16322       memsys3Link(prev);
   16323       i = prev;
   16324     }else{
   16325       size /= 4;
   16326     }
   16327     if( size>mem3.szMaster ){
   16328       mem3.iMaster = i;
   16329       mem3.szMaster = size;
   16330     }
   16331   }
   16332 }
   16333 
   16334 /*
   16335 ** Return a block of memory of at least nBytes in size.
   16336 ** Return NULL if unable.
   16337 **
   16338 ** This function assumes that the necessary mutexes, if any, are
   16339 ** already held by the caller. Hence "Unsafe".
   16340 */
   16341 static void *memsys3MallocUnsafe(int nByte){
   16342   u32 i;
   16343   u32 nBlock;
   16344   u32 toFree;
   16345 
   16346   assert( sqlite3_mutex_held(mem3.mutex) );
   16347   assert( sizeof(Mem3Block)==8 );
   16348   if( nByte<=12 ){
   16349     nBlock = 2;
   16350   }else{
   16351     nBlock = (nByte + 11)/8;
   16352   }
   16353   assert( nBlock>=2 );
   16354 
   16355   /* STEP 1:
   16356   ** Look for an entry of the correct size in either the small
   16357   ** chunk table or in the large chunk hash table.  This is
   16358   ** successful most of the time (about 9 times out of 10).
   16359   */
   16360   if( nBlock <= MX_SMALL ){
   16361     i = mem3.aiSmall[nBlock-2];
   16362     if( i>0 ){
   16363       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   16364       return memsys3Checkout(i, nBlock);
   16365     }
   16366   }else{
   16367     int hash = nBlock % N_HASH;
   16368     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   16369       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   16370         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   16371         return memsys3Checkout(i, nBlock);
   16372       }
   16373     }
   16374   }
   16375 
   16376   /* STEP 2:
   16377   ** Try to satisfy the allocation by carving a piece off of the end
   16378   ** of the master chunk.  This step usually works if step 1 fails.
   16379   */
   16380   if( mem3.szMaster>=nBlock ){
   16381     return memsys3FromMaster(nBlock);
   16382   }
   16383 
   16384 
   16385   /* STEP 3:
   16386   ** Loop through the entire memory pool.  Coalesce adjacent free
   16387   ** chunks.  Recompute the master chunk as the largest free chunk.
   16388   ** Then try again to satisfy the allocation by carving a piece off
   16389   ** of the end of the master chunk.  This step happens very
   16390   ** rarely (we hope!)
   16391   */
   16392   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   16393     memsys3OutOfMemory(toFree);
   16394     if( mem3.iMaster ){
   16395       memsys3Link(mem3.iMaster);
   16396       mem3.iMaster = 0;
   16397       mem3.szMaster = 0;
   16398     }
   16399     for(i=0; i<N_HASH; i++){
   16400       memsys3Merge(&mem3.aiHash[i]);
   16401     }
   16402     for(i=0; i<MX_SMALL-1; i++){
   16403       memsys3Merge(&mem3.aiSmall[i]);
   16404     }
   16405     if( mem3.szMaster ){
   16406       memsys3Unlink(mem3.iMaster);
   16407       if( mem3.szMaster>=nBlock ){
   16408         return memsys3FromMaster(nBlock);
   16409       }
   16410     }
   16411   }
   16412 
   16413   /* If none of the above worked, then we fail. */
   16414   return 0;
   16415 }
   16416 
   16417 /*
   16418 ** Free an outstanding memory allocation.
   16419 **
   16420 ** This function assumes that the necessary mutexes, if any, are
   16421 ** already held by the caller. Hence "Unsafe".
   16422 */
   16423 static void memsys3FreeUnsafe(void *pOld){
   16424   Mem3Block *p = (Mem3Block*)pOld;
   16425   int i;
   16426   u32 size, x;
   16427   assert( sqlite3_mutex_held(mem3.mutex) );
   16428   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   16429   i = p - mem3.aPool;
   16430   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   16431   size = mem3.aPool[i-1].u.hdr.size4x/4;
   16432   assert( i+size<=mem3.nPool+1 );
   16433   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   16434   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   16435   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   16436   memsys3Link(i);
   16437 
   16438   /* Try to expand the master using the newly freed chunk */
   16439   if( mem3.iMaster ){
   16440     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   16441       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   16442       mem3.iMaster -= size;
   16443       mem3.szMaster += size;
   16444       memsys3Unlink(mem3.iMaster);
   16445       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   16446       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   16447       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   16448     }
   16449     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   16450     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   16451       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   16452       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   16453       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   16454       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   16455     }
   16456   }
   16457 }
   16458 
   16459 /*
   16460 ** Return the size of an outstanding allocation, in bytes.  The
   16461 ** size returned omits the 8-byte header overhead.  This only
   16462 ** works for chunks that are currently checked out.
   16463 */
   16464 static int memsys3Size(void *p){
   16465   Mem3Block *pBlock;
   16466   if( p==0 ) return 0;
   16467   pBlock = (Mem3Block*)p;
   16468   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   16469   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   16470 }
   16471 
   16472 /*
   16473 ** Round up a request size to the next valid allocation size.
   16474 */
   16475 static int memsys3Roundup(int n){
   16476   if( n<=12 ){
   16477     return 12;
   16478   }else{
   16479     return ((n+11)&~7) - 4;
   16480   }
   16481 }
   16482 
   16483 /*
   16484 ** Allocate nBytes of memory.
   16485 */
   16486 static void *memsys3Malloc(int nBytes){
   16487   sqlite3_int64 *p;
   16488   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   16489   memsys3Enter();
   16490   p = memsys3MallocUnsafe(nBytes);
   16491   memsys3Leave();
   16492   return (void*)p;
   16493 }
   16494 
   16495 /*
   16496 ** Free memory.
   16497 */
   16498 static void memsys3Free(void *pPrior){
   16499   assert( pPrior );
   16500   memsys3Enter();
   16501   memsys3FreeUnsafe(pPrior);
   16502   memsys3Leave();
   16503 }
   16504 
   16505 /*
   16506 ** Change the size of an existing memory allocation
   16507 */
   16508 static void *memsys3Realloc(void *pPrior, int nBytes){
   16509   int nOld;
   16510   void *p;
   16511   if( pPrior==0 ){
   16512     return sqlite3_malloc(nBytes);
   16513   }
   16514   if( nBytes<=0 ){
   16515     sqlite3_free(pPrior);
   16516     return 0;
   16517   }
   16518   nOld = memsys3Size(pPrior);
   16519   if( nBytes<=nOld && nBytes>=nOld-128 ){
   16520     return pPrior;
   16521   }
   16522   memsys3Enter();
   16523   p = memsys3MallocUnsafe(nBytes);
   16524   if( p ){
   16525     if( nOld<nBytes ){
   16526       memcpy(p, pPrior, nOld);
   16527     }else{
   16528       memcpy(p, pPrior, nBytes);
   16529     }
   16530     memsys3FreeUnsafe(pPrior);
   16531   }
   16532   memsys3Leave();
   16533   return p;
   16534 }
   16535 
   16536 /*
   16537 ** Initialize this module.
   16538 */
   16539 static int memsys3Init(void *NotUsed){
   16540   UNUSED_PARAMETER(NotUsed);
   16541   if( !sqlite3GlobalConfig.pHeap ){
   16542     return SQLITE_ERROR;
   16543   }
   16544 
   16545   /* Store a pointer to the memory block in global structure mem3. */
   16546   assert( sizeof(Mem3Block)==8 );
   16547   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   16548   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   16549 
   16550   /* Initialize the master block. */
   16551   mem3.szMaster = mem3.nPool;
   16552   mem3.mnMaster = mem3.szMaster;
   16553   mem3.iMaster = 1;
   16554   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   16555   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   16556   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   16557 
   16558   return SQLITE_OK;
   16559 }
   16560 
   16561 /*
   16562 ** Deinitialize this module.
   16563 */
   16564 static void memsys3Shutdown(void *NotUsed){
   16565   UNUSED_PARAMETER(NotUsed);
   16566   mem3.mutex = 0;
   16567   return;
   16568 }
   16569 
   16570 
   16571 
   16572 /*
   16573 ** Open the file indicated and write a log of all unfreed memory
   16574 ** allocations into that log.
   16575 */
   16576 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   16577 #ifdef SQLITE_DEBUG
   16578   FILE *out;
   16579   u32 i, j;
   16580   u32 size;
   16581   if( zFilename==0 || zFilename[0]==0 ){
   16582     out = stdout;
   16583   }else{
   16584     out = fopen(zFilename, "w");
   16585     if( out==0 ){
   16586       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   16587                       zFilename);
   16588       return;
   16589     }
   16590   }
   16591   memsys3Enter();
   16592   fprintf(out, "CHUNKS:\n");
   16593   for(i=1; i<=mem3.nPool; i+=size/4){
   16594     size = mem3.aPool[i-1].u.hdr.size4x;
   16595     if( size/4<=1 ){
   16596       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   16597       assert( 0 );
   16598       break;
   16599     }
   16600     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   16601       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   16602       assert( 0 );
   16603       break;
   16604     }
   16605     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   16606       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   16607       assert( 0 );
   16608       break;
   16609     }
   16610     if( size&1 ){
   16611       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   16612     }else{
   16613       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   16614                   i==mem3.iMaster ? " **master**" : "");
   16615     }
   16616   }
   16617   for(i=0; i<MX_SMALL-1; i++){
   16618     if( mem3.aiSmall[i]==0 ) continue;
   16619     fprintf(out, "small(%2d):", i);
   16620     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   16621       fprintf(out, " %p(%d)", &mem3.aPool[j],
   16622               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   16623     }
   16624     fprintf(out, "\n");
   16625   }
   16626   for(i=0; i<N_HASH; i++){
   16627     if( mem3.aiHash[i]==0 ) continue;
   16628     fprintf(out, "hash(%2d):", i);
   16629     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   16630       fprintf(out, " %p(%d)", &mem3.aPool[j],
   16631               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   16632     }
   16633     fprintf(out, "\n");
   16634   }
   16635   fprintf(out, "master=%d\n", mem3.iMaster);
   16636   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   16637   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   16638   sqlite3_mutex_leave(mem3.mutex);
   16639   if( out==stdout ){
   16640     fflush(stdout);
   16641   }else{
   16642     fclose(out);
   16643   }
   16644 #else
   16645   UNUSED_PARAMETER(zFilename);
   16646 #endif
   16647 }
   16648 
   16649 /*
   16650 ** This routine is the only routine in this file with external
   16651 ** linkage.
   16652 **
   16653 ** Populate the low-level memory allocation function pointers in
   16654 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   16655 ** arguments specify the block of memory to manage.
   16656 **
   16657 ** This routine is only called by sqlite3_config(), and therefore
   16658 ** is not required to be threadsafe (it is not).
   16659 */
   16660 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   16661   static const sqlite3_mem_methods mempoolMethods = {
   16662      memsys3Malloc,
   16663      memsys3Free,
   16664      memsys3Realloc,
   16665      memsys3Size,
   16666      memsys3Roundup,
   16667      memsys3Init,
   16668      memsys3Shutdown,
   16669      0
   16670   };
   16671   return &mempoolMethods;
   16672 }
   16673 
   16674 #endif /* SQLITE_ENABLE_MEMSYS3 */
   16675 
   16676 /************** End of mem3.c ************************************************/
   16677 /************** Begin file mem5.c ********************************************/
   16678 /*
   16679 ** 2007 October 14
   16680 **
   16681 ** The author disclaims copyright to this source code.  In place of
   16682 ** a legal notice, here is a blessing:
   16683 **
   16684 **    May you do good and not evil.
   16685 **    May you find forgiveness for yourself and forgive others.
   16686 **    May you share freely, never taking more than you give.
   16687 **
   16688 *************************************************************************
   16689 ** This file contains the C functions that implement a memory
   16690 ** allocation subsystem for use by SQLite.
   16691 **
   16692 ** This version of the memory allocation subsystem omits all
   16693 ** use of malloc(). The application gives SQLite a block of memory
   16694 ** before calling sqlite3_initialize() from which allocations
   16695 ** are made and returned by the xMalloc() and xRealloc()
   16696 ** implementations. Once sqlite3_initialize() has been called,
   16697 ** the amount of memory available to SQLite is fixed and cannot
   16698 ** be changed.
   16699 **
   16700 ** This version of the memory allocation subsystem is included
   16701 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   16702 **
   16703 ** This memory allocator uses the following algorithm:
   16704 **
   16705 **   1.  All memory allocations sizes are rounded up to a power of 2.
   16706 **
   16707 **   2.  If two adjacent free blocks are the halves of a larger block,
   16708 **       then the two blocks are coalesed into the single larger block.
   16709 **
   16710 **   3.  New memory is allocated from the first available free block.
   16711 **
   16712 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   16713 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   16714 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   16715 **
   16716 ** Let n be the size of the largest allocation divided by the minimum
   16717 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   16718 ** be the maximum amount of memory ever outstanding at one time.  Let
   16719 ** N be the total amount of memory available for allocation.  Robson
   16720 ** proved that this memory allocator will never breakdown due to
   16721 ** fragmentation as long as the following constraint holds:
   16722 **
   16723 **      N >=  M*(1 + log2(n)/2) - n + 1
   16724 **
   16725 ** The sqlite3_status() logic tracks the maximum values of n and M so
   16726 ** that an application can, at any time, verify this constraint.
   16727 */
   16728 
   16729 /*
   16730 ** This version of the memory allocator is used only when
   16731 ** SQLITE_ENABLE_MEMSYS5 is defined.
   16732 */
   16733 #ifdef SQLITE_ENABLE_MEMSYS5
   16734 
   16735 /*
   16736 ** A minimum allocation is an instance of the following structure.
   16737 ** Larger allocations are an array of these structures where the
   16738 ** size of the array is a power of 2.
   16739 **
   16740 ** The size of this object must be a power of two.  That fact is
   16741 ** verified in memsys5Init().
   16742 */
   16743 typedef struct Mem5Link Mem5Link;
   16744 struct Mem5Link {
   16745   int next;       /* Index of next free chunk */
   16746   int prev;       /* Index of previous free chunk */
   16747 };
   16748 
   16749 /*
   16750 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   16751 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   16752 ** it is not actually possible to reach this limit.
   16753 */
   16754 #define LOGMAX 30
   16755 
   16756 /*
   16757 ** Masks used for mem5.aCtrl[] elements.
   16758 */
   16759 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   16760 #define CTRL_FREE     0x20    /* True if not checked out */
   16761 
   16762 /*
   16763 ** All of the static variables used by this module are collected
   16764 ** into a single structure named "mem5".  This is to keep the
   16765 ** static variables organized and to reduce namespace pollution
   16766 ** when this module is combined with other in the amalgamation.
   16767 */
   16768 static SQLITE_WSD struct Mem5Global {
   16769   /*
   16770   ** Memory available for allocation
   16771   */
   16772   int szAtom;      /* Smallest possible allocation in bytes */
   16773   int nBlock;      /* Number of szAtom sized blocks in zPool */
   16774   u8 *zPool;       /* Memory available to be allocated */
   16775 
   16776   /*
   16777   ** Mutex to control access to the memory allocation subsystem.
   16778   */
   16779   sqlite3_mutex *mutex;
   16780 
   16781   /*
   16782   ** Performance statistics
   16783   */
   16784   u64 nAlloc;         /* Total number of calls to malloc */
   16785   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   16786   u64 totalExcess;    /* Total internal fragmentation */
   16787   u32 currentOut;     /* Current checkout, including internal fragmentation */
   16788   u32 currentCount;   /* Current number of distinct checkouts */
   16789   u32 maxOut;         /* Maximum instantaneous currentOut */
   16790   u32 maxCount;       /* Maximum instantaneous currentCount */
   16791   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   16792 
   16793   /*
   16794   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   16795   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   16796   ** and so forth.
   16797   */
   16798   int aiFreelist[LOGMAX+1];
   16799 
   16800   /*
   16801   ** Space for tracking which blocks are checked out and the size
   16802   ** of each block.  One byte per block.
   16803   */
   16804   u8 *aCtrl;
   16805 
   16806 } mem5;
   16807 
   16808 /*
   16809 ** Access the static variable through a macro for SQLITE_OMIT_WSD
   16810 */
   16811 #define mem5 GLOBAL(struct Mem5Global, mem5)
   16812 
   16813 /*
   16814 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   16815 ** structures, return a pointer to the idx-th such lik.
   16816 */
   16817 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   16818 
   16819 /*
   16820 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   16821 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   16822 */
   16823 static void memsys5Unlink(int i, int iLogsize){
   16824   int next, prev;
   16825   assert( i>=0 && i<mem5.nBlock );
   16826   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   16827   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   16828 
   16829   next = MEM5LINK(i)->next;
   16830   prev = MEM5LINK(i)->prev;
   16831   if( prev<0 ){
   16832     mem5.aiFreelist[iLogsize] = next;
   16833   }else{
   16834     MEM5LINK(prev)->next = next;
   16835   }
   16836   if( next>=0 ){
   16837     MEM5LINK(next)->prev = prev;
   16838   }
   16839 }
   16840 
   16841 /*
   16842 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   16843 ** free list.
   16844 */
   16845 static void memsys5Link(int i, int iLogsize){
   16846   int x;
   16847   assert( sqlite3_mutex_held(mem5.mutex) );
   16848   assert( i>=0 && i<mem5.nBlock );
   16849   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   16850   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   16851 
   16852   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   16853   MEM5LINK(i)->prev = -1;
   16854   if( x>=0 ){
   16855     assert( x<mem5.nBlock );
   16856     MEM5LINK(x)->prev = i;
   16857   }
   16858   mem5.aiFreelist[iLogsize] = i;
   16859 }
   16860 
   16861 /*
   16862 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   16863 ** will already be held (obtained by code in malloc.c) if
   16864 ** sqlite3GlobalConfig.bMemStat is true.
   16865 */
   16866 static void memsys5Enter(void){
   16867   sqlite3_mutex_enter(mem5.mutex);
   16868 }
   16869 static void memsys5Leave(void){
   16870   sqlite3_mutex_leave(mem5.mutex);
   16871 }
   16872 
   16873 /*
   16874 ** Return the size of an outstanding allocation, in bytes.  The
   16875 ** size returned omits the 8-byte header overhead.  This only
   16876 ** works for chunks that are currently checked out.
   16877 */
   16878 static int memsys5Size(void *p){
   16879   int iSize = 0;
   16880   if( p ){
   16881     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
   16882     assert( i>=0 && i<mem5.nBlock );
   16883     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   16884   }
   16885   return iSize;
   16886 }
   16887 
   16888 /*
   16889 ** Find the first entry on the freelist iLogsize.  Unlink that
   16890 ** entry and return its index.
   16891 */
   16892 static int memsys5UnlinkFirst(int iLogsize){
   16893   int i;
   16894   int iFirst;
   16895 
   16896   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   16897   i = iFirst = mem5.aiFreelist[iLogsize];
   16898   assert( iFirst>=0 );
   16899   while( i>0 ){
   16900     if( i<iFirst ) iFirst = i;
   16901     i = MEM5LINK(i)->next;
   16902   }
   16903   memsys5Unlink(iFirst, iLogsize);
   16904   return iFirst;
   16905 }
   16906 
   16907 /*
   16908 ** Return a block of memory of at least nBytes in size.
   16909 ** Return NULL if unable.  Return NULL if nBytes==0.
   16910 **
   16911 ** The caller guarantees that nByte positive.
   16912 **
   16913 ** The caller has obtained a mutex prior to invoking this
   16914 ** routine so there is never any chance that two or more
   16915 ** threads can be in this routine at the same time.
   16916 */
   16917 static void *memsys5MallocUnsafe(int nByte){
   16918   int i;           /* Index of a mem5.aPool[] slot */
   16919   int iBin;        /* Index into mem5.aiFreelist[] */
   16920   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   16921   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   16922 
   16923   /* nByte must be a positive */
   16924   assert( nByte>0 );
   16925 
   16926   /* Keep track of the maximum allocation request.  Even unfulfilled
   16927   ** requests are counted */
   16928   if( (u32)nByte>mem5.maxRequest ){
   16929     mem5.maxRequest = nByte;
   16930   }
   16931 
   16932   /* Abort if the requested allocation size is larger than the largest
   16933   ** power of two that we can represent using 32-bit signed integers.
   16934   */
   16935   if( nByte > 0x40000000 ){
   16936     return 0;
   16937   }
   16938 
   16939   /* Round nByte up to the next valid power of two */
   16940   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
   16941 
   16942   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   16943   ** block.  If not, then split a block of the next larger power of
   16944   ** two in order to create a new free block of size iLogsize.
   16945   */
   16946   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
   16947   if( iBin>LOGMAX ){
   16948     testcase( sqlite3GlobalConfig.xLog!=0 );
   16949     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   16950     return 0;
   16951   }
   16952   i = memsys5UnlinkFirst(iBin);
   16953   while( iBin>iLogsize ){
   16954     int newSize;
   16955 
   16956     iBin--;
   16957     newSize = 1 << iBin;
   16958     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   16959     memsys5Link(i+newSize, iBin);
   16960   }
   16961   mem5.aCtrl[i] = iLogsize;
   16962 
   16963   /* Update allocator performance statistics. */
   16964   mem5.nAlloc++;
   16965   mem5.totalAlloc += iFullSz;
   16966   mem5.totalExcess += iFullSz - nByte;
   16967   mem5.currentCount++;
   16968   mem5.currentOut += iFullSz;
   16969   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   16970   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   16971 
   16972   /* Return a pointer to the allocated memory. */
   16973   return (void*)&mem5.zPool[i*mem5.szAtom];
   16974 }
   16975 
   16976 /*
   16977 ** Free an outstanding memory allocation.
   16978 */
   16979 static void memsys5FreeUnsafe(void *pOld){
   16980   u32 size, iLogsize;
   16981   int iBlock;
   16982 
   16983   /* Set iBlock to the index of the block pointed to by pOld in
   16984   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   16985   */
   16986   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
   16987 
   16988   /* Check that the pointer pOld points to a valid, non-free block. */
   16989   assert( iBlock>=0 && iBlock<mem5.nBlock );
   16990   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   16991   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   16992 
   16993   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   16994   size = 1<<iLogsize;
   16995   assert( iBlock+size-1<(u32)mem5.nBlock );
   16996 
   16997   mem5.aCtrl[iBlock] |= CTRL_FREE;
   16998   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   16999   assert( mem5.currentCount>0 );
   17000   assert( mem5.currentOut>=(size*mem5.szAtom) );
   17001   mem5.currentCount--;
   17002   mem5.currentOut -= size*mem5.szAtom;
   17003   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   17004   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   17005 
   17006   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   17007   while( ALWAYS(iLogsize<LOGMAX) ){
   17008     int iBuddy;
   17009     if( (iBlock>>iLogsize) & 1 ){
   17010       iBuddy = iBlock - size;
   17011     }else{
   17012       iBuddy = iBlock + size;
   17013     }
   17014     assert( iBuddy>=0 );
   17015     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
   17016     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   17017     memsys5Unlink(iBuddy, iLogsize);
   17018     iLogsize++;
   17019     if( iBuddy<iBlock ){
   17020       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   17021       mem5.aCtrl[iBlock] = 0;
   17022       iBlock = iBuddy;
   17023     }else{
   17024       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   17025       mem5.aCtrl[iBuddy] = 0;
   17026     }
   17027     size *= 2;
   17028   }
   17029   memsys5Link(iBlock, iLogsize);
   17030 }
   17031 
   17032 /*
   17033 ** Allocate nBytes of memory
   17034 */
   17035 static void *memsys5Malloc(int nBytes){
   17036   sqlite3_int64 *p = 0;
   17037   if( nBytes>0 ){
   17038     memsys5Enter();
   17039     p = memsys5MallocUnsafe(nBytes);
   17040     memsys5Leave();
   17041   }
   17042   return (void*)p;
   17043 }
   17044 
   17045 /*
   17046 ** Free memory.
   17047 **
   17048 ** The outer layer memory allocator prevents this routine from
   17049 ** being called with pPrior==0.
   17050 */
   17051 static void memsys5Free(void *pPrior){
   17052   assert( pPrior!=0 );
   17053   memsys5Enter();
   17054   memsys5FreeUnsafe(pPrior);
   17055   memsys5Leave();
   17056 }
   17057 
   17058 /*
   17059 ** Change the size of an existing memory allocation.
   17060 **
   17061 ** The outer layer memory allocator prevents this routine from
   17062 ** being called with pPrior==0.
   17063 **
   17064 ** nBytes is always a value obtained from a prior call to
   17065 ** memsys5Round().  Hence nBytes is always a non-negative power
   17066 ** of two.  If nBytes==0 that means that an oversize allocation
   17067 ** (an allocation larger than 0x40000000) was requested and this
   17068 ** routine should return 0 without freeing pPrior.
   17069 */
   17070 static void *memsys5Realloc(void *pPrior, int nBytes){
   17071   int nOld;
   17072   void *p;
   17073   assert( pPrior!=0 );
   17074   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
   17075   assert( nBytes>=0 );
   17076   if( nBytes==0 ){
   17077     return 0;
   17078   }
   17079   nOld = memsys5Size(pPrior);
   17080   if( nBytes<=nOld ){
   17081     return pPrior;
   17082   }
   17083   memsys5Enter();
   17084   p = memsys5MallocUnsafe(nBytes);
   17085   if( p ){
   17086     memcpy(p, pPrior, nOld);
   17087     memsys5FreeUnsafe(pPrior);
   17088   }
   17089   memsys5Leave();
   17090   return p;
   17091 }
   17092 
   17093 /*
   17094 ** Round up a request size to the next valid allocation size.  If
   17095 ** the allocation is too large to be handled by this allocation system,
   17096 ** return 0.
   17097 **
   17098 ** All allocations must be a power of two and must be expressed by a
   17099 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   17100 ** or 1073741824 bytes.
   17101 */
   17102 static int memsys5Roundup(int n){
   17103   int iFullSz;
   17104   if( n > 0x40000000 ) return 0;
   17105   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   17106   return iFullSz;
   17107 }
   17108 
   17109 /*
   17110 ** Return the ceiling of the logarithm base 2 of iValue.
   17111 **
   17112 ** Examples:   memsys5Log(1) -> 0
   17113 **             memsys5Log(2) -> 1
   17114 **             memsys5Log(4) -> 2
   17115 **             memsys5Log(5) -> 3
   17116 **             memsys5Log(8) -> 3
   17117 **             memsys5Log(9) -> 4
   17118 */
   17119 static int memsys5Log(int iValue){
   17120   int iLog;
   17121   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
   17122   return iLog;
   17123 }
   17124 
   17125 /*
   17126 ** Initialize the memory allocator.
   17127 **
   17128 ** This routine is not threadsafe.  The caller must be holding a mutex
   17129 ** to prevent multiple threads from entering at the same time.
   17130 */
   17131 static int memsys5Init(void *NotUsed){
   17132   int ii;            /* Loop counter */
   17133   int nByte;         /* Number of bytes of memory available to this allocator */
   17134   u8 *zByte;         /* Memory usable by this allocator */
   17135   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   17136   int iOffset;       /* An offset into mem5.aCtrl[] */
   17137 
   17138   UNUSED_PARAMETER(NotUsed);
   17139 
   17140   /* For the purposes of this routine, disable the mutex */
   17141   mem5.mutex = 0;
   17142 
   17143   /* The size of a Mem5Link object must be a power of two.  Verify that
   17144   ** this is case.
   17145   */
   17146   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   17147 
   17148   nByte = sqlite3GlobalConfig.nHeap;
   17149   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   17150   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   17151 
   17152   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
   17153   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   17154   mem5.szAtom = (1<<nMinLog);
   17155   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   17156     mem5.szAtom = mem5.szAtom << 1;
   17157   }
   17158 
   17159   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   17160   mem5.zPool = zByte;
   17161   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   17162 
   17163   for(ii=0; ii<=LOGMAX; ii++){
   17164     mem5.aiFreelist[ii] = -1;
   17165   }
   17166 
   17167   iOffset = 0;
   17168   for(ii=LOGMAX; ii>=0; ii--){
   17169     int nAlloc = (1<<ii);
   17170     if( (iOffset+nAlloc)<=mem5.nBlock ){
   17171       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   17172       memsys5Link(iOffset, ii);
   17173       iOffset += nAlloc;
   17174     }
   17175     assert((iOffset+nAlloc)>mem5.nBlock);
   17176   }
   17177 
   17178   /* If a mutex is required for normal operation, allocate one */
   17179   if( sqlite3GlobalConfig.bMemstat==0 ){
   17180     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   17181   }
   17182 
   17183   return SQLITE_OK;
   17184 }
   17185 
   17186 /*
   17187 ** Deinitialize this module.
   17188 */
   17189 static void memsys5Shutdown(void *NotUsed){
   17190   UNUSED_PARAMETER(NotUsed);
   17191   mem5.mutex = 0;
   17192   return;
   17193 }
   17194 
   17195 #ifdef SQLITE_TEST
   17196 /*
   17197 ** Open the file indicated and write a log of all unfreed memory
   17198 ** allocations into that log.
   17199 */
   17200 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   17201   FILE *out;
   17202   int i, j, n;
   17203   int nMinLog;
   17204 
   17205   if( zFilename==0 || zFilename[0]==0 ){
   17206     out = stdout;
   17207   }else{
   17208     out = fopen(zFilename, "w");
   17209     if( out==0 ){
   17210       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   17211                       zFilename);
   17212       return;
   17213     }
   17214   }
   17215   memsys5Enter();
   17216   nMinLog = memsys5Log(mem5.szAtom);
   17217   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   17218     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   17219     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   17220   }
   17221   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   17222   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   17223   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   17224   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   17225   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   17226   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   17227   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   17228   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   17229   memsys5Leave();
   17230   if( out==stdout ){
   17231     fflush(stdout);
   17232   }else{
   17233     fclose(out);
   17234   }
   17235 }
   17236 #endif
   17237 
   17238 /*
   17239 ** This routine is the only routine in this file with external
   17240 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   17241 ** struct populated with the memsys5 methods.
   17242 */
   17243 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   17244   static const sqlite3_mem_methods memsys5Methods = {
   17245      memsys5Malloc,
   17246      memsys5Free,
   17247      memsys5Realloc,
   17248      memsys5Size,
   17249      memsys5Roundup,
   17250      memsys5Init,
   17251      memsys5Shutdown,
   17252      0
   17253   };
   17254   return &memsys5Methods;
   17255 }
   17256 
   17257 #endif /* SQLITE_ENABLE_MEMSYS5 */
   17258 
   17259 /************** End of mem5.c ************************************************/
   17260 /************** Begin file mutex.c *******************************************/
   17261 /*
   17262 ** 2007 August 14
   17263 **
   17264 ** The author disclaims copyright to this source code.  In place of
   17265 ** a legal notice, here is a blessing:
   17266 **
   17267 **    May you do good and not evil.
   17268 **    May you find forgiveness for yourself and forgive others.
   17269 **    May you share freely, never taking more than you give.
   17270 **
   17271 *************************************************************************
   17272 ** This file contains the C functions that implement mutexes.
   17273 **
   17274 ** This file contains code that is common across all mutex implementations.
   17275 */
   17276 
   17277 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   17278 /*
   17279 ** For debugging purposes, record when the mutex subsystem is initialized
   17280 ** and uninitialized so that we can assert() if there is an attempt to
   17281 ** allocate a mutex while the system is uninitialized.
   17282 */
   17283 static SQLITE_WSD int mutexIsInit = 0;
   17284 #endif /* SQLITE_DEBUG */
   17285 
   17286 
   17287 #ifndef SQLITE_MUTEX_OMIT
   17288 /*
   17289 ** Initialize the mutex system.
   17290 */
   17291 SQLITE_PRIVATE int sqlite3MutexInit(void){
   17292   int rc = SQLITE_OK;
   17293   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   17294     /* If the xMutexAlloc method has not been set, then the user did not
   17295     ** install a mutex implementation via sqlite3_config() prior to
   17296     ** sqlite3_initialize() being called. This block copies pointers to
   17297     ** the default implementation into the sqlite3GlobalConfig structure.
   17298     */
   17299     sqlite3_mutex_methods const *pFrom;
   17300     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   17301 
   17302     if( sqlite3GlobalConfig.bCoreMutex ){
   17303       pFrom = sqlite3DefaultMutex();
   17304     }else{
   17305       pFrom = sqlite3NoopMutex();
   17306     }
   17307     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
   17308     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
   17309            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
   17310     pTo->xMutexAlloc = pFrom->xMutexAlloc;
   17311   }
   17312   rc = sqlite3GlobalConfig.mutex.xMutexInit();
   17313 
   17314 #ifdef SQLITE_DEBUG
   17315   GLOBAL(int, mutexIsInit) = 1;
   17316 #endif
   17317 
   17318   return rc;
   17319 }
   17320 
   17321 /*
   17322 ** Shutdown the mutex system. This call frees resources allocated by
   17323 ** sqlite3MutexInit().
   17324 */
   17325 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   17326   int rc = SQLITE_OK;
   17327   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   17328     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   17329   }
   17330 
   17331 #ifdef SQLITE_DEBUG
   17332   GLOBAL(int, mutexIsInit) = 0;
   17333 #endif
   17334 
   17335   return rc;
   17336 }
   17337 
   17338 /*
   17339 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   17340 */
   17341 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   17342 #ifndef SQLITE_OMIT_AUTOINIT
   17343   if( sqlite3_initialize() ) return 0;
   17344 #endif
   17345   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   17346 }
   17347 
   17348 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   17349   if( !sqlite3GlobalConfig.bCoreMutex ){
   17350     return 0;
   17351   }
   17352   assert( GLOBAL(int, mutexIsInit) );
   17353   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   17354 }
   17355 
   17356 /*
   17357 ** Free a dynamic mutex.
   17358 */
   17359 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   17360   if( p ){
   17361     sqlite3GlobalConfig.mutex.xMutexFree(p);
   17362   }
   17363 }
   17364 
   17365 /*
   17366 ** Obtain the mutex p. If some other thread already has the mutex, block
   17367 ** until it can be obtained.
   17368 */
   17369 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   17370   if( p ){
   17371     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   17372   }
   17373 }
   17374 
   17375 /*
   17376 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   17377 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   17378 */
   17379 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   17380   int rc = SQLITE_OK;
   17381   if( p ){
   17382     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   17383   }
   17384   return rc;
   17385 }
   17386 
   17387 /*
   17388 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   17389 ** entered by the same thread.  The behavior is undefined if the mutex
   17390 ** is not currently entered. If a NULL pointer is passed as an argument
   17391 ** this function is a no-op.
   17392 */
   17393 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   17394   if( p ){
   17395     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   17396   }
   17397 }
   17398 
   17399 #ifndef NDEBUG
   17400 /*
   17401 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   17402 ** intended for use inside assert() statements.
   17403 */
   17404 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   17405   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   17406 }
   17407 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   17408   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   17409 }
   17410 #endif
   17411 
   17412 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   17413 
   17414 /************** End of mutex.c ***********************************************/
   17415 /************** Begin file mutex_noop.c **************************************/
   17416 /*
   17417 ** 2008 October 07
   17418 **
   17419 ** The author disclaims copyright to this source code.  In place of
   17420 ** a legal notice, here is a blessing:
   17421 **
   17422 **    May you do good and not evil.
   17423 **    May you find forgiveness for yourself and forgive others.
   17424 **    May you share freely, never taking more than you give.
   17425 **
   17426 *************************************************************************
   17427 ** This file contains the C functions that implement mutexes.
   17428 **
   17429 ** This implementation in this file does not provide any mutual
   17430 ** exclusion and is thus suitable for use only in applications
   17431 ** that use SQLite in a single thread.  The routines defined
   17432 ** here are place-holders.  Applications can substitute working
   17433 ** mutex routines at start-time using the
   17434 **
   17435 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   17436 **
   17437 ** interface.
   17438 **
   17439 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   17440 ** that does error checking on mutexes to make sure they are being
   17441 ** called correctly.
   17442 */
   17443 
   17444 #ifndef SQLITE_MUTEX_OMIT
   17445 
   17446 #ifndef SQLITE_DEBUG
   17447 /*
   17448 ** Stub routines for all mutex methods.
   17449 **
   17450 ** This routines provide no mutual exclusion or error checking.
   17451 */
   17452 static int noopMutexInit(void){ return SQLITE_OK; }
   17453 static int noopMutexEnd(void){ return SQLITE_OK; }
   17454 static sqlite3_mutex *noopMutexAlloc(int id){
   17455   UNUSED_PARAMETER(id);
   17456   return (sqlite3_mutex*)8;
   17457 }
   17458 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   17459 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   17460 static int noopMutexTry(sqlite3_mutex *p){
   17461   UNUSED_PARAMETER(p);
   17462   return SQLITE_OK;
   17463 }
   17464 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   17465 
   17466 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   17467   static const sqlite3_mutex_methods sMutex = {
   17468     noopMutexInit,
   17469     noopMutexEnd,
   17470     noopMutexAlloc,
   17471     noopMutexFree,
   17472     noopMutexEnter,
   17473     noopMutexTry,
   17474     noopMutexLeave,
   17475 
   17476     0,
   17477     0,
   17478   };
   17479 
   17480   return &sMutex;
   17481 }
   17482 #endif /* !SQLITE_DEBUG */
   17483 
   17484 #ifdef SQLITE_DEBUG
   17485 /*
   17486 ** In this implementation, error checking is provided for testing
   17487 ** and debugging purposes.  The mutexes still do not provide any
   17488 ** mutual exclusion.
   17489 */
   17490 
   17491 /*
   17492 ** The mutex object
   17493 */
   17494 typedef struct sqlite3_debug_mutex {
   17495   int id;     /* The mutex type */
   17496   int cnt;    /* Number of entries without a matching leave */
   17497 } sqlite3_debug_mutex;
   17498 
   17499 /*
   17500 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   17501 ** intended for use inside assert() statements.
   17502 */
   17503 static int debugMutexHeld(sqlite3_mutex *pX){
   17504   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17505   return p==0 || p->cnt>0;
   17506 }
   17507 static int debugMutexNotheld(sqlite3_mutex *pX){
   17508   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17509   return p==0 || p->cnt==0;
   17510 }
   17511 
   17512 /*
   17513 ** Initialize and deinitialize the mutex subsystem.
   17514 */
   17515 static int debugMutexInit(void){ return SQLITE_OK; }
   17516 static int debugMutexEnd(void){ return SQLITE_OK; }
   17517 
   17518 /*
   17519 ** The sqlite3_mutex_alloc() routine allocates a new
   17520 ** mutex and returns a pointer to it.  If it returns NULL
   17521 ** that means that a mutex could not be allocated.
   17522 */
   17523 static sqlite3_mutex *debugMutexAlloc(int id){
   17524   static sqlite3_debug_mutex aStatic[6];
   17525   sqlite3_debug_mutex *pNew = 0;
   17526   switch( id ){
   17527     case SQLITE_MUTEX_FAST:
   17528     case SQLITE_MUTEX_RECURSIVE: {
   17529       pNew = sqlite3Malloc(sizeof(*pNew));
   17530       if( pNew ){
   17531         pNew->id = id;
   17532         pNew->cnt = 0;
   17533       }
   17534       break;
   17535     }
   17536     default: {
   17537       assert( id-2 >= 0 );
   17538       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
   17539       pNew = &aStatic[id-2];
   17540       pNew->id = id;
   17541       break;
   17542     }
   17543   }
   17544   return (sqlite3_mutex*)pNew;
   17545 }
   17546 
   17547 /*
   17548 ** This routine deallocates a previously allocated mutex.
   17549 */
   17550 static void debugMutexFree(sqlite3_mutex *pX){
   17551   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17552   assert( p->cnt==0 );
   17553   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   17554   sqlite3_free(p);
   17555 }
   17556 
   17557 /*
   17558 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   17559 ** to enter a mutex.  If another thread is already within the mutex,
   17560 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   17561 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   17562 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   17563 ** be entered multiple times by the same thread.  In such cases the,
   17564 ** mutex must be exited an equal number of times before another thread
   17565 ** can enter.  If the same thread tries to enter any other kind of mutex
   17566 ** more than once, the behavior is undefined.
   17567 */
   17568 static void debugMutexEnter(sqlite3_mutex *pX){
   17569   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17570   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   17571   p->cnt++;
   17572 }
   17573 static int debugMutexTry(sqlite3_mutex *pX){
   17574   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17575   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   17576   p->cnt++;
   17577   return SQLITE_OK;
   17578 }
   17579 
   17580 /*
   17581 ** The sqlite3_mutex_leave() routine exits a mutex that was
   17582 ** previously entered by the same thread.  The behavior
   17583 ** is undefined if the mutex is not currently entered or
   17584 ** is not currently allocated.  SQLite will never do either.
   17585 */
   17586 static void debugMutexLeave(sqlite3_mutex *pX){
   17587   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   17588   assert( debugMutexHeld(pX) );
   17589   p->cnt--;
   17590   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   17591 }
   17592 
   17593 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   17594   static const sqlite3_mutex_methods sMutex = {
   17595     debugMutexInit,
   17596     debugMutexEnd,
   17597     debugMutexAlloc,
   17598     debugMutexFree,
   17599     debugMutexEnter,
   17600     debugMutexTry,
   17601     debugMutexLeave,
   17602 
   17603     debugMutexHeld,
   17604     debugMutexNotheld
   17605   };
   17606 
   17607   return &sMutex;
   17608 }
   17609 #endif /* SQLITE_DEBUG */
   17610 
   17611 /*
   17612 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
   17613 ** is used regardless of the run-time threadsafety setting.
   17614 */
   17615 #ifdef SQLITE_MUTEX_NOOP
   17616 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   17617   return sqlite3NoopMutex();
   17618 }
   17619 #endif /* defined(SQLITE_MUTEX_NOOP) */
   17620 #endif /* !defined(SQLITE_MUTEX_OMIT) */
   17621 
   17622 /************** End of mutex_noop.c ******************************************/
   17623 /************** Begin file mutex_os2.c ***************************************/
   17624 /*
   17625 ** 2007 August 28
   17626 **
   17627 ** The author disclaims copyright to this source code.  In place of
   17628 ** a legal notice, here is a blessing:
   17629 **
   17630 **    May you do good and not evil.
   17631 **    May you find forgiveness for yourself and forgive others.
   17632 **    May you share freely, never taking more than you give.
   17633 **
   17634 *************************************************************************
   17635 ** This file contains the C functions that implement mutexes for OS/2
   17636 */
   17637 
   17638 /*
   17639 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
   17640 ** See the mutex.h file for details.
   17641 */
   17642 #ifdef SQLITE_MUTEX_OS2
   17643 
   17644 /********************** OS/2 Mutex Implementation **********************
   17645 **
   17646 ** This implementation of mutexes is built using the OS/2 API.
   17647 */
   17648 
   17649 /*
   17650 ** The mutex object
   17651 ** Each recursive mutex is an instance of the following structure.
   17652 */
   17653 struct sqlite3_mutex {
   17654   HMTX mutex;       /* Mutex controlling the lock */
   17655   int  id;          /* Mutex type */
   17656 #ifdef SQLITE_DEBUG
   17657  int   trace;       /* True to trace changes */
   17658 #endif
   17659 };
   17660 
   17661 #ifdef SQLITE_DEBUG
   17662 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
   17663 #else
   17664 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
   17665 #endif
   17666 
   17667 /*
   17668 ** Initialize and deinitialize the mutex subsystem.
   17669 */
   17670 static int os2MutexInit(void){ return SQLITE_OK; }
   17671 static int os2MutexEnd(void){ return SQLITE_OK; }
   17672 
   17673 /*
   17674 ** The sqlite3_mutex_alloc() routine allocates a new
   17675 ** mutex and returns a pointer to it.  If it returns NULL
   17676 ** that means that a mutex could not be allocated.
   17677 ** SQLite will unwind its stack and return an error.  The argument
   17678 ** to sqlite3_mutex_alloc() is one of these integer constants:
   17679 **
   17680 ** <ul>
   17681 ** <li>  SQLITE_MUTEX_FAST
   17682 ** <li>  SQLITE_MUTEX_RECURSIVE
   17683 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   17684 ** <li>  SQLITE_MUTEX_STATIC_MEM
   17685 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   17686 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   17687 ** <li>  SQLITE_MUTEX_STATIC_LRU
   17688 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   17689 ** </ul>
   17690 **
   17691 ** The first two constants cause sqlite3_mutex_alloc() to create
   17692 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   17693 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   17694 ** The mutex implementation does not need to make a distinction
   17695 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   17696 ** not want to.  But SQLite will only request a recursive mutex in
   17697 ** cases where it really needs one.  If a faster non-recursive mutex
   17698 ** implementation is available on the host platform, the mutex subsystem
   17699 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   17700 **
   17701 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   17702 ** a pointer to a static preexisting mutex.  Six static mutexes are
   17703 ** used by the current version of SQLite.  Future versions of SQLite
   17704 ** may add additional static mutexes.  Static mutexes are for internal
   17705 ** use by SQLite only.  Applications that use SQLite mutexes should
   17706 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   17707 ** SQLITE_MUTEX_RECURSIVE.
   17708 **
   17709 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   17710 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   17711 ** returns a different mutex on every call.  But for the static
   17712 ** mutex types, the same mutex is returned on every call that has
   17713 ** the same type number.
   17714 */
   17715 static sqlite3_mutex *os2MutexAlloc(int iType){
   17716   sqlite3_mutex *p = NULL;
   17717   switch( iType ){
   17718     case SQLITE_MUTEX_FAST:
   17719     case SQLITE_MUTEX_RECURSIVE: {
   17720       p = sqlite3MallocZero( sizeof(*p) );
   17721       if( p ){
   17722         p->id = iType;
   17723         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
   17724           sqlite3_free( p );
   17725           p = NULL;
   17726         }
   17727       }
   17728       break;
   17729     }
   17730     default: {
   17731       static volatile int isInit = 0;
   17732       static sqlite3_mutex staticMutexes[6] = {
   17733         SQLITE3_MUTEX_INITIALIZER,
   17734         SQLITE3_MUTEX_INITIALIZER,
   17735         SQLITE3_MUTEX_INITIALIZER,
   17736         SQLITE3_MUTEX_INITIALIZER,
   17737         SQLITE3_MUTEX_INITIALIZER,
   17738         SQLITE3_MUTEX_INITIALIZER,
   17739       };
   17740       if ( !isInit ){
   17741         APIRET rc;
   17742         PTIB ptib;
   17743         PPIB ppib;
   17744         HMTX mutex;
   17745         char name[32];
   17746         DosGetInfoBlocks( &ptib, &ppib );
   17747         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
   17748                           ppib->pib_ulpid );
   17749         while( !isInit ){
   17750           mutex = 0;
   17751           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
   17752           if( rc == NO_ERROR ){
   17753             unsigned int i;
   17754             if( !isInit ){
   17755               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
   17756                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
   17757               }
   17758               isInit = 1;
   17759             }
   17760             DosCloseMutexSem( mutex );
   17761           }else if( rc == ERROR_DUPLICATE_NAME ){
   17762             DosSleep( 1 );
   17763           }else{
   17764             return p;
   17765           }
   17766         }
   17767       }
   17768       assert( iType-2 >= 0 );
   17769       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
   17770       p = &staticMutexes[iType-2];
   17771       p->id = iType;
   17772       break;
   17773     }
   17774   }
   17775   return p;
   17776 }
   17777 
   17778 
   17779 /*
   17780 ** This routine deallocates a previously allocated mutex.
   17781 ** SQLite is careful to deallocate every mutex that it allocates.
   17782 */
   17783 static void os2MutexFree(sqlite3_mutex *p){
   17784 #ifdef SQLITE_DEBUG
   17785   TID tid;
   17786   PID pid;
   17787   ULONG ulCount;
   17788   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   17789   assert( ulCount==0 );
   17790   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   17791 #endif
   17792   DosCloseMutexSem( p->mutex );
   17793   sqlite3_free( p );
   17794 }
   17795 
   17796 #ifdef SQLITE_DEBUG
   17797 /*
   17798 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   17799 ** intended for use inside assert() statements.
   17800 */
   17801 static int os2MutexHeld(sqlite3_mutex *p){
   17802   TID tid;
   17803   PID pid;
   17804   ULONG ulCount;
   17805   PTIB ptib;
   17806   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   17807   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
   17808     return 0;
   17809   DosGetInfoBlocks(&ptib, NULL);
   17810   return tid==ptib->tib_ptib2->tib2_ultid;
   17811 }
   17812 static int os2MutexNotheld(sqlite3_mutex *p){
   17813   TID tid;
   17814   PID pid;
   17815   ULONG ulCount;
   17816   PTIB ptib;
   17817   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   17818   if( ulCount==0 )
   17819     return 1;
   17820   DosGetInfoBlocks(&ptib, NULL);
   17821   return tid!=ptib->tib_ptib2->tib2_ultid;
   17822 }
   17823 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
   17824   TID   tid;
   17825   PID   pid;
   17826   ULONG ulCount;
   17827   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   17828   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
   17829 }
   17830 #endif
   17831 
   17832 /*
   17833 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   17834 ** to enter a mutex.  If another thread is already within the mutex,
   17835 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   17836 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   17837 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   17838 ** be entered multiple times by the same thread.  In such cases the,
   17839 ** mutex must be exited an equal number of times before another thread
   17840 ** can enter.  If the same thread tries to enter any other kind of mutex
   17841 ** more than once, the behavior is undefined.
   17842 */
   17843 static void os2MutexEnter(sqlite3_mutex *p){
   17844   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   17845   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
   17846 #ifdef SQLITE_DEBUG
   17847   if( p->trace ) os2MutexTrace(p, "enter");
   17848 #endif
   17849 }
   17850 static int os2MutexTry(sqlite3_mutex *p){
   17851   int rc = SQLITE_BUSY;
   17852   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   17853   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
   17854     rc = SQLITE_OK;
   17855 #ifdef SQLITE_DEBUG
   17856     if( p->trace ) os2MutexTrace(p, "try");
   17857 #endif
   17858   }
   17859   return rc;
   17860 }
   17861 
   17862 /*
   17863 ** The sqlite3_mutex_leave() routine exits a mutex that was
   17864 ** previously entered by the same thread.  The behavior
   17865 ** is undefined if the mutex is not currently entered or
   17866 ** is not currently allocated.  SQLite will never do either.
   17867 */
   17868 static void os2MutexLeave(sqlite3_mutex *p){
   17869   assert( os2MutexHeld(p) );
   17870   DosReleaseMutexSem(p->mutex);
   17871 #ifdef SQLITE_DEBUG
   17872   if( p->trace ) os2MutexTrace(p, "leave");
   17873 #endif
   17874 }
   17875 
   17876 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   17877   static const sqlite3_mutex_methods sMutex = {
   17878     os2MutexInit,
   17879     os2MutexEnd,
   17880     os2MutexAlloc,
   17881     os2MutexFree,
   17882     os2MutexEnter,
   17883     os2MutexTry,
   17884     os2MutexLeave,
   17885 #ifdef SQLITE_DEBUG
   17886     os2MutexHeld,
   17887     os2MutexNotheld
   17888 #else
   17889     0,
   17890     0
   17891 #endif
   17892   };
   17893 
   17894   return &sMutex;
   17895 }
   17896 #endif /* SQLITE_MUTEX_OS2 */
   17897 
   17898 /************** End of mutex_os2.c *******************************************/
   17899 /************** Begin file mutex_unix.c **************************************/
   17900 /*
   17901 ** 2007 August 28
   17902 **
   17903 ** The author disclaims copyright to this source code.  In place of
   17904 ** a legal notice, here is a blessing:
   17905 **
   17906 **    May you do good and not evil.
   17907 **    May you find forgiveness for yourself and forgive others.
   17908 **    May you share freely, never taking more than you give.
   17909 **
   17910 *************************************************************************
   17911 ** This file contains the C functions that implement mutexes for pthreads
   17912 */
   17913 
   17914 /*
   17915 ** The code in this file is only used if we are compiling threadsafe
   17916 ** under unix with pthreads.
   17917 **
   17918 ** Note that this implementation requires a version of pthreads that
   17919 ** supports recursive mutexes.
   17920 */
   17921 #ifdef SQLITE_MUTEX_PTHREADS
   17922 
   17923 #include <pthread.h>
   17924 
   17925 /*
   17926 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
   17927 ** are necessary under two condidtions:  (1) Debug builds and (2) using
   17928 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
   17929 */
   17930 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
   17931 # define SQLITE_MUTEX_NREF 1
   17932 #else
   17933 # define SQLITE_MUTEX_NREF 0
   17934 #endif
   17935 
   17936 /*
   17937 ** Each recursive mutex is an instance of the following structure.
   17938 */
   17939 struct sqlite3_mutex {
   17940   pthread_mutex_t mutex;     /* Mutex controlling the lock */
   17941 #if SQLITE_MUTEX_NREF
   17942   int id;                    /* Mutex type */
   17943   volatile int nRef;         /* Number of entrances */
   17944   volatile pthread_t owner;  /* Thread that is within this mutex */
   17945   int trace;                 /* True to trace changes */
   17946 #endif
   17947 };
   17948 #if SQLITE_MUTEX_NREF
   17949 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
   17950 #else
   17951 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
   17952 #endif
   17953 
   17954 /*
   17955 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   17956 ** intended for use only inside assert() statements.  On some platforms,
   17957 ** there might be race conditions that can cause these routines to
   17958 ** deliver incorrect results.  In particular, if pthread_equal() is
   17959 ** not an atomic operation, then these routines might delivery
   17960 ** incorrect results.  On most platforms, pthread_equal() is a
   17961 ** comparison of two integers and is therefore atomic.  But we are
   17962 ** told that HPUX is not such a platform.  If so, then these routines
   17963 ** will not always work correctly on HPUX.
   17964 **
   17965 ** On those platforms where pthread_equal() is not atomic, SQLite
   17966 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
   17967 ** make sure no assert() statements are evaluated and hence these
   17968 ** routines are never called.
   17969 */
   17970 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
   17971 static int pthreadMutexHeld(sqlite3_mutex *p){
   17972   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
   17973 }
   17974 static int pthreadMutexNotheld(sqlite3_mutex *p){
   17975   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
   17976 }
   17977 #endif
   17978 
   17979 /*
   17980 ** Initialize and deinitialize the mutex subsystem.
   17981 */
   17982 static int pthreadMutexInit(void){ return SQLITE_OK; }
   17983 static int pthreadMutexEnd(void){ return SQLITE_OK; }
   17984 
   17985 /*
   17986 ** The sqlite3_mutex_alloc() routine allocates a new
   17987 ** mutex and returns a pointer to it.  If it returns NULL
   17988 ** that means that a mutex could not be allocated.  SQLite
   17989 ** will unwind its stack and return an error.  The argument
   17990 ** to sqlite3_mutex_alloc() is one of these integer constants:
   17991 **
   17992 ** <ul>
   17993 ** <li>  SQLITE_MUTEX_FAST
   17994 ** <li>  SQLITE_MUTEX_RECURSIVE
   17995 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   17996 ** <li>  SQLITE_MUTEX_STATIC_MEM
   17997 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   17998 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   17999 ** <li>  SQLITE_MUTEX_STATIC_LRU
   18000 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   18001 ** </ul>
   18002 **
   18003 ** The first two constants cause sqlite3_mutex_alloc() to create
   18004 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   18005 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   18006 ** The mutex implementation does not need to make a distinction
   18007 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   18008 ** not want to.  But SQLite will only request a recursive mutex in
   18009 ** cases where it really needs one.  If a faster non-recursive mutex
   18010 ** implementation is available on the host platform, the mutex subsystem
   18011 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   18012 **
   18013 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   18014 ** a pointer to a static preexisting mutex.  Six static mutexes are
   18015 ** used by the current version of SQLite.  Future versions of SQLite
   18016 ** may add additional static mutexes.  Static mutexes are for internal
   18017 ** use by SQLite only.  Applications that use SQLite mutexes should
   18018 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   18019 ** SQLITE_MUTEX_RECURSIVE.
   18020 **
   18021 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   18022 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   18023 ** returns a different mutex on every call.  But for the static
   18024 ** mutex types, the same mutex is returned on every call that has
   18025 ** the same type number.
   18026 */
   18027 static sqlite3_mutex *pthreadMutexAlloc(int iType){
   18028   static sqlite3_mutex staticMutexes[] = {
   18029     SQLITE3_MUTEX_INITIALIZER,
   18030     SQLITE3_MUTEX_INITIALIZER,
   18031     SQLITE3_MUTEX_INITIALIZER,
   18032     SQLITE3_MUTEX_INITIALIZER,
   18033     SQLITE3_MUTEX_INITIALIZER,
   18034     SQLITE3_MUTEX_INITIALIZER
   18035   };
   18036   sqlite3_mutex *p;
   18037   switch( iType ){
   18038     case SQLITE_MUTEX_RECURSIVE: {
   18039       p = sqlite3MallocZero( sizeof(*p) );
   18040       if( p ){
   18041 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18042         /* If recursive mutexes are not available, we will have to
   18043         ** build our own.  See below. */
   18044         pthread_mutex_init(&p->mutex, 0);
   18045 #else
   18046         /* Use a recursive mutex if it is available */
   18047         pthread_mutexattr_t recursiveAttr;
   18048         pthread_mutexattr_init(&recursiveAttr);
   18049         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
   18050         pthread_mutex_init(&p->mutex, &recursiveAttr);
   18051         pthread_mutexattr_destroy(&recursiveAttr);
   18052 #endif
   18053 #if SQLITE_MUTEX_NREF
   18054         p->id = iType;
   18055 #endif
   18056       }
   18057       break;
   18058     }
   18059     case SQLITE_MUTEX_FAST: {
   18060       p = sqlite3MallocZero( sizeof(*p) );
   18061       if( p ){
   18062 #if SQLITE_MUTEX_NREF
   18063         p->id = iType;
   18064 #endif
   18065         pthread_mutex_init(&p->mutex, 0);
   18066       }
   18067       break;
   18068     }
   18069     default: {
   18070       assert( iType-2 >= 0 );
   18071       assert( iType-2 < ArraySize(staticMutexes) );
   18072       p = &staticMutexes[iType-2];
   18073 #if SQLITE_MUTEX_NREF
   18074       p->id = iType;
   18075 #endif
   18076       break;
   18077     }
   18078   }
   18079   return p;
   18080 }
   18081 
   18082 
   18083 /*
   18084 ** This routine deallocates a previously
   18085 ** allocated mutex.  SQLite is careful to deallocate every
   18086 ** mutex that it allocates.
   18087 */
   18088 static void pthreadMutexFree(sqlite3_mutex *p){
   18089   assert( p->nRef==0 );
   18090   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   18091   pthread_mutex_destroy(&p->mutex);
   18092   sqlite3_free(p);
   18093 }
   18094 
   18095 /*
   18096 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   18097 ** to enter a mutex.  If another thread is already within the mutex,
   18098 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   18099 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   18100 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   18101 ** be entered multiple times by the same thread.  In such cases the,
   18102 ** mutex must be exited an equal number of times before another thread
   18103 ** can enter.  If the same thread tries to enter any other kind of mutex
   18104 ** more than once, the behavior is undefined.
   18105 */
   18106 static void pthreadMutexEnter(sqlite3_mutex *p){
   18107   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   18108 
   18109 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18110   /* If recursive mutexes are not available, then we have to grow
   18111   ** our own.  This implementation assumes that pthread_equal()
   18112   ** is atomic - that it cannot be deceived into thinking self
   18113   ** and p->owner are equal if p->owner changes between two values
   18114   ** that are not equal to self while the comparison is taking place.
   18115   ** This implementation also assumes a coherent cache - that
   18116   ** separate processes cannot read different values from the same
   18117   ** address at the same time.  If either of these two conditions
   18118   ** are not met, then the mutexes will fail and problems will result.
   18119   */
   18120   {
   18121     pthread_t self = pthread_self();
   18122     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   18123       p->nRef++;
   18124     }else{
   18125       pthread_mutex_lock(&p->mutex);
   18126       assert( p->nRef==0 );
   18127       p->owner = self;
   18128       p->nRef = 1;
   18129     }
   18130   }
   18131 #else
   18132   /* Use the built-in recursive mutexes if they are available.
   18133   */
   18134   pthread_mutex_lock(&p->mutex);
   18135 #if SQLITE_MUTEX_NREF
   18136   assert( p->nRef>0 || p->owner==0 );
   18137   p->owner = pthread_self();
   18138   p->nRef++;
   18139 #endif
   18140 #endif
   18141 
   18142 #ifdef SQLITE_DEBUG
   18143   if( p->trace ){
   18144     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18145   }
   18146 #endif
   18147 }
   18148 static int pthreadMutexTry(sqlite3_mutex *p){
   18149   int rc;
   18150   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   18151 
   18152 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18153   /* If recursive mutexes are not available, then we have to grow
   18154   ** our own.  This implementation assumes that pthread_equal()
   18155   ** is atomic - that it cannot be deceived into thinking self
   18156   ** and p->owner are equal if p->owner changes between two values
   18157   ** that are not equal to self while the comparison is taking place.
   18158   ** This implementation also assumes a coherent cache - that
   18159   ** separate processes cannot read different values from the same
   18160   ** address at the same time.  If either of these two conditions
   18161   ** are not met, then the mutexes will fail and problems will result.
   18162   */
   18163   {
   18164     pthread_t self = pthread_self();
   18165     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   18166       p->nRef++;
   18167       rc = SQLITE_OK;
   18168     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
   18169       assert( p->nRef==0 );
   18170       p->owner = self;
   18171       p->nRef = 1;
   18172       rc = SQLITE_OK;
   18173     }else{
   18174       rc = SQLITE_BUSY;
   18175     }
   18176   }
   18177 #else
   18178   /* Use the built-in recursive mutexes if they are available.
   18179   */
   18180   if( pthread_mutex_trylock(&p->mutex)==0 ){
   18181 #if SQLITE_MUTEX_NREF
   18182     p->owner = pthread_self();
   18183     p->nRef++;
   18184 #endif
   18185     rc = SQLITE_OK;
   18186   }else{
   18187     rc = SQLITE_BUSY;
   18188   }
   18189 #endif
   18190 
   18191 #ifdef SQLITE_DEBUG
   18192   if( rc==SQLITE_OK && p->trace ){
   18193     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18194   }
   18195 #endif
   18196   return rc;
   18197 }
   18198 
   18199 /*
   18200 ** The sqlite3_mutex_leave() routine exits a mutex that was
   18201 ** previously entered by the same thread.  The behavior
   18202 ** is undefined if the mutex is not currently entered or
   18203 ** is not currently allocated.  SQLite will never do either.
   18204 */
   18205 static void pthreadMutexLeave(sqlite3_mutex *p){
   18206   assert( pthreadMutexHeld(p) );
   18207 #if SQLITE_MUTEX_NREF
   18208   p->nRef--;
   18209   if( p->nRef==0 ) p->owner = 0;
   18210 #endif
   18211   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   18212 
   18213 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   18214   if( p->nRef==0 ){
   18215     pthread_mutex_unlock(&p->mutex);
   18216   }
   18217 #else
   18218   pthread_mutex_unlock(&p->mutex);
   18219 #endif
   18220 
   18221 #ifdef SQLITE_DEBUG
   18222   if( p->trace ){
   18223     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18224   }
   18225 #endif
   18226 }
   18227 
   18228 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   18229   static const sqlite3_mutex_methods sMutex = {
   18230     pthreadMutexInit,
   18231     pthreadMutexEnd,
   18232     pthreadMutexAlloc,
   18233     pthreadMutexFree,
   18234     pthreadMutexEnter,
   18235     pthreadMutexTry,
   18236     pthreadMutexLeave,
   18237 #ifdef SQLITE_DEBUG
   18238     pthreadMutexHeld,
   18239     pthreadMutexNotheld
   18240 #else
   18241     0,
   18242     0
   18243 #endif
   18244   };
   18245 
   18246   return &sMutex;
   18247 }
   18248 
   18249 #endif /* SQLITE_MUTEX_PTHREADS */
   18250 
   18251 /************** End of mutex_unix.c ******************************************/
   18252 /************** Begin file mutex_w32.c ***************************************/
   18253 /*
   18254 ** 2007 August 14
   18255 **
   18256 ** The author disclaims copyright to this source code.  In place of
   18257 ** a legal notice, here is a blessing:
   18258 **
   18259 **    May you do good and not evil.
   18260 **    May you find forgiveness for yourself and forgive others.
   18261 **    May you share freely, never taking more than you give.
   18262 **
   18263 *************************************************************************
   18264 ** This file contains the C functions that implement mutexes for win32
   18265 */
   18266 
   18267 /*
   18268 ** The code in this file is only used if we are compiling multithreaded
   18269 ** on a win32 system.
   18270 */
   18271 #ifdef SQLITE_MUTEX_W32
   18272 
   18273 /*
   18274 ** Each recursive mutex is an instance of the following structure.
   18275 */
   18276 struct sqlite3_mutex {
   18277   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
   18278   int id;                    /* Mutex type */
   18279 #ifdef SQLITE_DEBUG
   18280   volatile int nRef;         /* Number of enterances */
   18281   volatile DWORD owner;      /* Thread holding this mutex */
   18282   int trace;                 /* True to trace changes */
   18283 #endif
   18284 };
   18285 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
   18286 #ifdef SQLITE_DEBUG
   18287 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
   18288 #else
   18289 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
   18290 #endif
   18291 
   18292 /*
   18293 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   18294 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   18295 **
   18296 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   18297 ** the LockFileEx() API.  But we can still statically link against that
   18298 ** API as long as we don't call it win running Win95/98/ME.  A call to
   18299 ** this routine is used to determine if the host is Win95/98/ME or
   18300 ** WinNT/2K/XP so that we will know whether or not we can safely call
   18301 ** the LockFileEx() API.
   18302 **
   18303 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
   18304 ** which is only available if your application was compiled with
   18305 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
   18306 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
   18307 ** this out as well.
   18308 */
   18309 #if 0
   18310 #if SQLITE_OS_WINCE
   18311 # define mutexIsNT()  (1)
   18312 #else
   18313   static int mutexIsNT(void){
   18314     static int osType = 0;
   18315     if( osType==0 ){
   18316       OSVERSIONINFO sInfo;
   18317       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   18318       GetVersionEx(&sInfo);
   18319       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   18320     }
   18321     return osType==2;
   18322   }
   18323 #endif /* SQLITE_OS_WINCE */
   18324 #endif
   18325 
   18326 #ifdef SQLITE_DEBUG
   18327 /*
   18328 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   18329 ** intended for use only inside assert() statements.
   18330 */
   18331 static int winMutexHeld(sqlite3_mutex *p){
   18332   return p->nRef!=0 && p->owner==GetCurrentThreadId();
   18333 }
   18334 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
   18335   return p->nRef==0 || p->owner!=tid;
   18336 }
   18337 static int winMutexNotheld(sqlite3_mutex *p){
   18338   DWORD tid = GetCurrentThreadId();
   18339   return winMutexNotheld2(p, tid);
   18340 }
   18341 #endif
   18342 
   18343 
   18344 /*
   18345 ** Initialize and deinitialize the mutex subsystem.
   18346 */
   18347 static sqlite3_mutex winMutex_staticMutexes[6] = {
   18348   SQLITE3_MUTEX_INITIALIZER,
   18349   SQLITE3_MUTEX_INITIALIZER,
   18350   SQLITE3_MUTEX_INITIALIZER,
   18351   SQLITE3_MUTEX_INITIALIZER,
   18352   SQLITE3_MUTEX_INITIALIZER,
   18353   SQLITE3_MUTEX_INITIALIZER
   18354 };
   18355 static int winMutex_isInit = 0;
   18356 /* As winMutexInit() and winMutexEnd() are called as part
   18357 ** of the sqlite3_initialize and sqlite3_shutdown()
   18358 ** processing, the "interlocked" magic is probably not
   18359 ** strictly necessary.
   18360 */
   18361 static long winMutex_lock = 0;
   18362 
   18363 static int winMutexInit(void){
   18364   /* The first to increment to 1 does actual initialization */
   18365   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
   18366     int i;
   18367     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   18368       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
   18369     }
   18370     winMutex_isInit = 1;
   18371   }else{
   18372     /* Someone else is in the process of initing the static mutexes */
   18373     while( !winMutex_isInit ){
   18374       Sleep(1);
   18375     }
   18376   }
   18377   return SQLITE_OK;
   18378 }
   18379 
   18380 static int winMutexEnd(void){
   18381   /* The first to decrement to 0 does actual shutdown
   18382   ** (which should be the last to shutdown.) */
   18383   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
   18384     if( winMutex_isInit==1 ){
   18385       int i;
   18386       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   18387         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
   18388       }
   18389       winMutex_isInit = 0;
   18390     }
   18391   }
   18392   return SQLITE_OK;
   18393 }
   18394 
   18395 /*
   18396 ** The sqlite3_mutex_alloc() routine allocates a new
   18397 ** mutex and returns a pointer to it.  If it returns NULL
   18398 ** that means that a mutex could not be allocated.  SQLite
   18399 ** will unwind its stack and return an error.  The argument
   18400 ** to sqlite3_mutex_alloc() is one of these integer constants:
   18401 **
   18402 ** <ul>
   18403 ** <li>  SQLITE_MUTEX_FAST
   18404 ** <li>  SQLITE_MUTEX_RECURSIVE
   18405 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   18406 ** <li>  SQLITE_MUTEX_STATIC_MEM
   18407 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   18408 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   18409 ** <li>  SQLITE_MUTEX_STATIC_LRU
   18410 ** <li>  SQLITE_MUTEX_STATIC_PMEM
   18411 ** </ul>
   18412 **
   18413 ** The first two constants cause sqlite3_mutex_alloc() to create
   18414 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   18415 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   18416 ** The mutex implementation does not need to make a distinction
   18417 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   18418 ** not want to.  But SQLite will only request a recursive mutex in
   18419 ** cases where it really needs one.  If a faster non-recursive mutex
   18420 ** implementation is available on the host platform, the mutex subsystem
   18421 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   18422 **
   18423 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   18424 ** a pointer to a static preexisting mutex.  Six static mutexes are
   18425 ** used by the current version of SQLite.  Future versions of SQLite
   18426 ** may add additional static mutexes.  Static mutexes are for internal
   18427 ** use by SQLite only.  Applications that use SQLite mutexes should
   18428 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   18429 ** SQLITE_MUTEX_RECURSIVE.
   18430 **
   18431 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   18432 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   18433 ** returns a different mutex on every call.  But for the static
   18434 ** mutex types, the same mutex is returned on every call that has
   18435 ** the same type number.
   18436 */
   18437 static sqlite3_mutex *winMutexAlloc(int iType){
   18438   sqlite3_mutex *p;
   18439 
   18440   switch( iType ){
   18441     case SQLITE_MUTEX_FAST:
   18442     case SQLITE_MUTEX_RECURSIVE: {
   18443       p = sqlite3MallocZero( sizeof(*p) );
   18444       if( p ){
   18445 #ifdef SQLITE_DEBUG
   18446         p->id = iType;
   18447 #endif
   18448         InitializeCriticalSection(&p->mutex);
   18449       }
   18450       break;
   18451     }
   18452     default: {
   18453       assert( winMutex_isInit==1 );
   18454       assert( iType-2 >= 0 );
   18455       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
   18456       p = &winMutex_staticMutexes[iType-2];
   18457 #ifdef SQLITE_DEBUG
   18458       p->id = iType;
   18459 #endif
   18460       break;
   18461     }
   18462   }
   18463   return p;
   18464 }
   18465 
   18466 
   18467 /*
   18468 ** This routine deallocates a previously
   18469 ** allocated mutex.  SQLite is careful to deallocate every
   18470 ** mutex that it allocates.
   18471 */
   18472 static void winMutexFree(sqlite3_mutex *p){
   18473   assert( p );
   18474   assert( p->nRef==0 && p->owner==0 );
   18475   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   18476   DeleteCriticalSection(&p->mutex);
   18477   sqlite3_free(p);
   18478 }
   18479 
   18480 /*
   18481 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   18482 ** to enter a mutex.  If another thread is already within the mutex,
   18483 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   18484 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   18485 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   18486 ** be entered multiple times by the same thread.  In such cases the,
   18487 ** mutex must be exited an equal number of times before another thread
   18488 ** can enter.  If the same thread tries to enter any other kind of mutex
   18489 ** more than once, the behavior is undefined.
   18490 */
   18491 static void winMutexEnter(sqlite3_mutex *p){
   18492 #ifdef SQLITE_DEBUG
   18493   DWORD tid = GetCurrentThreadId();
   18494   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   18495 #endif
   18496   EnterCriticalSection(&p->mutex);
   18497 #ifdef SQLITE_DEBUG
   18498   assert( p->nRef>0 || p->owner==0 );
   18499   p->owner = tid;
   18500   p->nRef++;
   18501   if( p->trace ){
   18502     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18503   }
   18504 #endif
   18505 }
   18506 static int winMutexTry(sqlite3_mutex *p){
   18507 #ifndef NDEBUG
   18508   DWORD tid = GetCurrentThreadId();
   18509 #endif
   18510   int rc = SQLITE_BUSY;
   18511   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   18512   /*
   18513   ** The sqlite3_mutex_try() routine is very rarely used, and when it
   18514   ** is used it is merely an optimization.  So it is OK for it to always
   18515   ** fail.
   18516   **
   18517   ** The TryEnterCriticalSection() interface is only available on WinNT.
   18518   ** And some windows compilers complain if you try to use it without
   18519   ** first doing some #defines that prevent SQLite from building on Win98.
   18520   ** For that reason, we will omit this optimization for now.  See
   18521   ** ticket #2685.
   18522   */
   18523 #if 0
   18524   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
   18525     p->owner = tid;
   18526     p->nRef++;
   18527     rc = SQLITE_OK;
   18528   }
   18529 #else
   18530   UNUSED_PARAMETER(p);
   18531 #endif
   18532 #ifdef SQLITE_DEBUG
   18533   if( rc==SQLITE_OK && p->trace ){
   18534     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18535   }
   18536 #endif
   18537   return rc;
   18538 }
   18539 
   18540 /*
   18541 ** The sqlite3_mutex_leave() routine exits a mutex that was
   18542 ** previously entered by the same thread.  The behavior
   18543 ** is undefined if the mutex is not currently entered or
   18544 ** is not currently allocated.  SQLite will never do either.
   18545 */
   18546 static void winMutexLeave(sqlite3_mutex *p){
   18547 #ifndef NDEBUG
   18548   DWORD tid = GetCurrentThreadId();
   18549   assert( p->nRef>0 );
   18550   assert( p->owner==tid );
   18551   p->nRef--;
   18552   if( p->nRef==0 ) p->owner = 0;
   18553   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   18554 #endif
   18555   LeaveCriticalSection(&p->mutex);
   18556 #ifdef SQLITE_DEBUG
   18557   if( p->trace ){
   18558     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   18559   }
   18560 #endif
   18561 }
   18562 
   18563 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   18564   static const sqlite3_mutex_methods sMutex = {
   18565     winMutexInit,
   18566     winMutexEnd,
   18567     winMutexAlloc,
   18568     winMutexFree,
   18569     winMutexEnter,
   18570     winMutexTry,
   18571     winMutexLeave,
   18572 #ifdef SQLITE_DEBUG
   18573     winMutexHeld,
   18574     winMutexNotheld
   18575 #else
   18576     0,
   18577     0
   18578 #endif
   18579   };
   18580 
   18581   return &sMutex;
   18582 }
   18583 #endif /* SQLITE_MUTEX_W32 */
   18584 
   18585 /************** End of mutex_w32.c *******************************************/
   18586 /************** Begin file malloc.c ******************************************/
   18587 /*
   18588 ** 2001 September 15
   18589 **
   18590 ** The author disclaims copyright to this source code.  In place of
   18591 ** a legal notice, here is a blessing:
   18592 **
   18593 **    May you do good and not evil.
   18594 **    May you find forgiveness for yourself and forgive others.
   18595 **    May you share freely, never taking more than you give.
   18596 **
   18597 *************************************************************************
   18598 **
   18599 ** Memory allocation functions used throughout sqlite.
   18600 */
   18601 /* #include <stdarg.h> */
   18602 
   18603 /*
   18604 ** Attempt to release up to n bytes of non-essential memory currently
   18605 ** held by SQLite. An example of non-essential memory is memory used to
   18606 ** cache database pages that are not currently in use.
   18607 */
   18608 SQLITE_API int sqlite3_release_memory(int n){
   18609 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   18610   return sqlite3PcacheReleaseMemory(n);
   18611 #else
   18612   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
   18613   ** is a no-op returning zero if SQLite is not compiled with
   18614   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
   18615   UNUSED_PARAMETER(n);
   18616   return 0;
   18617 #endif
   18618 }
   18619 
   18620 /*
   18621 ** An instance of the following object records the location of
   18622 ** each unused scratch buffer.
   18623 */
   18624 typedef struct ScratchFreeslot {
   18625   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
   18626 } ScratchFreeslot;
   18627 
   18628 /*
   18629 ** State information local to the memory allocation subsystem.
   18630 */
   18631 static SQLITE_WSD struct Mem0Global {
   18632   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   18633 
   18634   /*
   18635   ** The alarm callback and its arguments.  The mem0.mutex lock will
   18636   ** be held while the callback is running.  Recursive calls into
   18637   ** the memory subsystem are allowed, but no new callbacks will be
   18638   ** issued.
   18639   */
   18640   sqlite3_int64 alarmThreshold;
   18641   void (*alarmCallback)(void*, sqlite3_int64,int);
   18642   void *alarmArg;
   18643 
   18644   /*
   18645   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
   18646   ** (so that a range test can be used to determine if an allocation
   18647   ** being freed came from pScratch) and a pointer to the list of
   18648   ** unused scratch allocations.
   18649   */
   18650   void *pScratchEnd;
   18651   ScratchFreeslot *pScratchFree;
   18652   u32 nScratchFree;
   18653 
   18654   /*
   18655   ** True if heap is nearly "full" where "full" is defined by the
   18656   ** sqlite3_soft_heap_limit() setting.
   18657   */
   18658   int nearlyFull;
   18659 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
   18660 
   18661 #define mem0 GLOBAL(struct Mem0Global, mem0)
   18662 
   18663 /*
   18664 ** This routine runs when the memory allocator sees that the
   18665 ** total memory allocation is about to exceed the soft heap
   18666 ** limit.
   18667 */
   18668 static void softHeapLimitEnforcer(
   18669   void *NotUsed,
   18670   sqlite3_int64 NotUsed2,
   18671   int allocSize
   18672 ){
   18673   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   18674   sqlite3_release_memory(allocSize);
   18675 }
   18676 
   18677 /*
   18678 ** Change the alarm callback
   18679 */
   18680 static int sqlite3MemoryAlarm(
   18681   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   18682   void *pArg,
   18683   sqlite3_int64 iThreshold
   18684 ){
   18685   int nUsed;
   18686   sqlite3_mutex_enter(mem0.mutex);
   18687   mem0.alarmCallback = xCallback;
   18688   mem0.alarmArg = pArg;
   18689   mem0.alarmThreshold = iThreshold;
   18690   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   18691   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
   18692   sqlite3_mutex_leave(mem0.mutex);
   18693   return SQLITE_OK;
   18694 }
   18695 
   18696 #ifndef SQLITE_OMIT_DEPRECATED
   18697 /*
   18698 ** Deprecated external interface.  Internal/core SQLite code
   18699 ** should call sqlite3MemoryAlarm.
   18700 */
   18701 SQLITE_API int sqlite3_memory_alarm(
   18702   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   18703   void *pArg,
   18704   sqlite3_int64 iThreshold
   18705 ){
   18706   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
   18707 }
   18708 #endif
   18709 
   18710 /*
   18711 ** Set the soft heap-size limit for the library. Passing a zero or
   18712 ** negative value indicates no limit.
   18713 */
   18714 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   18715   sqlite3_int64 priorLimit;
   18716   sqlite3_int64 excess;
   18717 #ifndef SQLITE_OMIT_AUTOINIT
   18718   int rc = sqlite3_initialize();
   18719   if( rc ) return -1;
   18720 #endif
   18721   sqlite3_mutex_enter(mem0.mutex);
   18722   priorLimit = mem0.alarmThreshold;
   18723   sqlite3_mutex_leave(mem0.mutex);
   18724   if( n<0 ) return priorLimit;
   18725   if( n>0 ){
   18726     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
   18727   }else{
   18728     sqlite3MemoryAlarm(0, 0, 0);
   18729   }
   18730   excess = sqlite3_memory_used() - n;
   18731   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
   18732   return priorLimit;
   18733 }
   18734 SQLITE_API void sqlite3_soft_heap_limit(int n){
   18735   if( n<0 ) n = 0;
   18736   sqlite3_soft_heap_limit64(n);
   18737 }
   18738 
   18739 /*
   18740 ** Initialize the memory allocation subsystem.
   18741 */
   18742 SQLITE_PRIVATE int sqlite3MallocInit(void){
   18743   if( sqlite3GlobalConfig.m.xMalloc==0 ){
   18744     sqlite3MemSetDefault();
   18745   }
   18746   memset(&mem0, 0, sizeof(mem0));
   18747   if( sqlite3GlobalConfig.bCoreMutex ){
   18748     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   18749   }
   18750   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
   18751       && sqlite3GlobalConfig.nScratch>0 ){
   18752     int i, n, sz;
   18753     ScratchFreeslot *pSlot;
   18754     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
   18755     sqlite3GlobalConfig.szScratch = sz;
   18756     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
   18757     n = sqlite3GlobalConfig.nScratch;
   18758     mem0.pScratchFree = pSlot;
   18759     mem0.nScratchFree = n;
   18760     for(i=0; i<n-1; i++){
   18761       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
   18762       pSlot = pSlot->pNext;
   18763     }
   18764     pSlot->pNext = 0;
   18765     mem0.pScratchEnd = (void*)&pSlot[1];
   18766   }else{
   18767     mem0.pScratchEnd = 0;
   18768     sqlite3GlobalConfig.pScratch = 0;
   18769     sqlite3GlobalConfig.szScratch = 0;
   18770     sqlite3GlobalConfig.nScratch = 0;
   18771   }
   18772   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
   18773       || sqlite3GlobalConfig.nPage<1 ){
   18774     sqlite3GlobalConfig.pPage = 0;
   18775     sqlite3GlobalConfig.szPage = 0;
   18776     sqlite3GlobalConfig.nPage = 0;
   18777   }
   18778   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
   18779 }
   18780 
   18781 /*
   18782 ** Return true if the heap is currently under memory pressure - in other
   18783 ** words if the amount of heap used is close to the limit set by
   18784 ** sqlite3_soft_heap_limit().
   18785 */
   18786 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
   18787   return mem0.nearlyFull;
   18788 }
   18789 
   18790 /*
   18791 ** Deinitialize the memory allocation subsystem.
   18792 */
   18793 SQLITE_PRIVATE void sqlite3MallocEnd(void){
   18794   if( sqlite3GlobalConfig.m.xShutdown ){
   18795     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
   18796   }
   18797   memset(&mem0, 0, sizeof(mem0));
   18798 }
   18799 
   18800 /*
   18801 ** Return the amount of memory currently checked out.
   18802 */
   18803 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
   18804   int n, mx;
   18805   sqlite3_int64 res;
   18806   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
   18807   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
   18808   return res;
   18809 }
   18810 
   18811 /*
   18812 ** Return the maximum amount of memory that has ever been
   18813 ** checked out since either the beginning of this process
   18814 ** or since the most recent reset.
   18815 */
   18816 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
   18817   int n, mx;
   18818   sqlite3_int64 res;
   18819   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
   18820   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
   18821   return res;
   18822 }
   18823 
   18824 /*
   18825 ** Trigger the alarm
   18826 */
   18827 static void sqlite3MallocAlarm(int nByte){
   18828   void (*xCallback)(void*,sqlite3_int64,int);
   18829   sqlite3_int64 nowUsed;
   18830   void *pArg;
   18831   if( mem0.alarmCallback==0 ) return;
   18832   xCallback = mem0.alarmCallback;
   18833   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   18834   pArg = mem0.alarmArg;
   18835   mem0.alarmCallback = 0;
   18836   sqlite3_mutex_leave(mem0.mutex);
   18837   xCallback(pArg, nowUsed, nByte);
   18838   sqlite3_mutex_enter(mem0.mutex);
   18839   mem0.alarmCallback = xCallback;
   18840   mem0.alarmArg = pArg;
   18841 }
   18842 
   18843 /*
   18844 ** Do a memory allocation with statistics and alarms.  Assume the
   18845 ** lock is already held.
   18846 */
   18847 static int mallocWithAlarm(int n, void **pp){
   18848   int nFull;
   18849   void *p;
   18850   assert( sqlite3_mutex_held(mem0.mutex) );
   18851   nFull = sqlite3GlobalConfig.m.xRoundup(n);
   18852   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
   18853   if( mem0.alarmCallback!=0 ){
   18854     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   18855     if( nUsed >= mem0.alarmThreshold - nFull ){
   18856       mem0.nearlyFull = 1;
   18857       sqlite3MallocAlarm(nFull);
   18858     }else{
   18859       mem0.nearlyFull = 0;
   18860     }
   18861   }
   18862   p = sqlite3GlobalConfig.m.xMalloc(nFull);
   18863 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   18864   if( p==0 && mem0.alarmCallback ){
   18865     sqlite3MallocAlarm(nFull);
   18866     p = sqlite3GlobalConfig.m.xMalloc(nFull);
   18867   }
   18868 #endif
   18869   if( p ){
   18870     nFull = sqlite3MallocSize(p);
   18871     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
   18872     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
   18873   }
   18874   *pp = p;
   18875   return nFull;
   18876 }
   18877 
   18878 /*
   18879 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
   18880 ** assumes the memory subsystem has already been initialized.
   18881 */
   18882 SQLITE_PRIVATE void *sqlite3Malloc(int n){
   18883   void *p;
   18884   if( n<=0               /* IMP: R-65312-04917 */
   18885    || n>=0x7fffff00
   18886   ){
   18887     /* A memory allocation of a number of bytes which is near the maximum
   18888     ** signed integer value might cause an integer overflow inside of the
   18889     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
   18890     ** 255 bytes of overhead.  SQLite itself will never use anything near
   18891     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
   18892     p = 0;
   18893   }else if( sqlite3GlobalConfig.bMemstat ){
   18894     sqlite3_mutex_enter(mem0.mutex);
   18895     mallocWithAlarm(n, &p);
   18896     sqlite3_mutex_leave(mem0.mutex);
   18897   }else{
   18898     p = sqlite3GlobalConfig.m.xMalloc(n);
   18899   }
   18900   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
   18901   return p;
   18902 }
   18903 
   18904 /*
   18905 ** This version of the memory allocation is for use by the application.
   18906 ** First make sure the memory subsystem is initialized, then do the
   18907 ** allocation.
   18908 */
   18909 SQLITE_API void *sqlite3_malloc(int n){
   18910 #ifndef SQLITE_OMIT_AUTOINIT
   18911   if( sqlite3_initialize() ) return 0;
   18912 #endif
   18913   return sqlite3Malloc(n);
   18914 }
   18915 
   18916 /*
   18917 ** Each thread may only have a single outstanding allocation from
   18918 ** xScratchMalloc().  We verify this constraint in the single-threaded
   18919 ** case by setting scratchAllocOut to 1 when an allocation
   18920 ** is outstanding clearing it when the allocation is freed.
   18921 */
   18922 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   18923 static int scratchAllocOut = 0;
   18924 #endif
   18925 
   18926 
   18927 /*
   18928 ** Allocate memory that is to be used and released right away.
   18929 ** This routine is similar to alloca() in that it is not intended
   18930 ** for situations where the memory might be held long-term.  This
   18931 ** routine is intended to get memory to old large transient data
   18932 ** structures that would not normally fit on the stack of an
   18933 ** embedded processor.
   18934 */
   18935 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
   18936   void *p;
   18937   assert( n>0 );
   18938 
   18939   sqlite3_mutex_enter(mem0.mutex);
   18940   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
   18941     p = mem0.pScratchFree;
   18942     mem0.pScratchFree = mem0.pScratchFree->pNext;
   18943     mem0.nScratchFree--;
   18944     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
   18945     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   18946     sqlite3_mutex_leave(mem0.mutex);
   18947   }else{
   18948     if( sqlite3GlobalConfig.bMemstat ){
   18949       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   18950       n = mallocWithAlarm(n, &p);
   18951       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
   18952       sqlite3_mutex_leave(mem0.mutex);
   18953     }else{
   18954       sqlite3_mutex_leave(mem0.mutex);
   18955       p = sqlite3GlobalConfig.m.xMalloc(n);
   18956     }
   18957     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
   18958   }
   18959   assert( sqlite3_mutex_notheld(mem0.mutex) );
   18960 
   18961 
   18962 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   18963   /* Verify that no more than two scratch allocations per thread
   18964   ** are outstanding at one time.  (This is only checked in the
   18965   ** single-threaded case since checking in the multi-threaded case
   18966   ** would be much more complicated.) */
   18967   assert( scratchAllocOut<=1 );
   18968   if( p ) scratchAllocOut++;
   18969 #endif
   18970 
   18971   return p;
   18972 }
   18973 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
   18974   if( p ){
   18975 
   18976 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   18977     /* Verify that no more than two scratch allocation per thread
   18978     ** is outstanding at one time.  (This is only checked in the
   18979     ** single-threaded case since checking in the multi-threaded case
   18980     ** would be much more complicated.) */
   18981     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
   18982     scratchAllocOut--;
   18983 #endif
   18984 
   18985     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
   18986       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
   18987       ScratchFreeslot *pSlot;
   18988       pSlot = (ScratchFreeslot*)p;
   18989       sqlite3_mutex_enter(mem0.mutex);
   18990       pSlot->pNext = mem0.pScratchFree;
   18991       mem0.pScratchFree = pSlot;
   18992       mem0.nScratchFree++;
   18993       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
   18994       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
   18995       sqlite3_mutex_leave(mem0.mutex);
   18996     }else{
   18997       /* Release memory back to the heap */
   18998       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
   18999       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
   19000       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   19001       if( sqlite3GlobalConfig.bMemstat ){
   19002         int iSize = sqlite3MallocSize(p);
   19003         sqlite3_mutex_enter(mem0.mutex);
   19004         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
   19005         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
   19006         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   19007         sqlite3GlobalConfig.m.xFree(p);
   19008         sqlite3_mutex_leave(mem0.mutex);
   19009       }else{
   19010         sqlite3GlobalConfig.m.xFree(p);
   19011       }
   19012     }
   19013   }
   19014 }
   19015 
   19016 /*
   19017 ** TRUE if p is a lookaside memory allocation from db
   19018 */
   19019 #ifndef SQLITE_OMIT_LOOKASIDE
   19020 static int isLookaside(sqlite3 *db, void *p){
   19021   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
   19022 }
   19023 #else
   19024 #define isLookaside(A,B) 0
   19025 #endif
   19026 
   19027 /*
   19028 ** Return the size of a memory allocation previously obtained from
   19029 ** sqlite3Malloc() or sqlite3_malloc().
   19030 */
   19031 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
   19032   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   19033   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   19034   return sqlite3GlobalConfig.m.xSize(p);
   19035 }
   19036 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
   19037   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   19038   if( db && isLookaside(db, p) ){
   19039     return db->lookaside.sz;
   19040   }else{
   19041     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   19042     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   19043     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   19044     return sqlite3GlobalConfig.m.xSize(p);
   19045   }
   19046 }
   19047 
   19048 /*
   19049 ** Free memory previously obtained from sqlite3Malloc().
   19050 */
   19051 SQLITE_API void sqlite3_free(void *p){
   19052   if( p==0 ) return;  /* IMP: R-49053-54554 */
   19053   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   19054   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   19055   if( sqlite3GlobalConfig.bMemstat ){
   19056     sqlite3_mutex_enter(mem0.mutex);
   19057     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
   19058     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   19059     sqlite3GlobalConfig.m.xFree(p);
   19060     sqlite3_mutex_leave(mem0.mutex);
   19061   }else{
   19062     sqlite3GlobalConfig.m.xFree(p);
   19063   }
   19064 }
   19065 
   19066 /*
   19067 ** Free memory that might be associated with a particular database
   19068 ** connection.
   19069 */
   19070 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
   19071   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   19072   if( db ){
   19073     if( db->pnBytesFreed ){
   19074       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
   19075       return;
   19076     }
   19077     if( isLookaside(db, p) ){
   19078       LookasideSlot *pBuf = (LookasideSlot*)p;
   19079       pBuf->pNext = db->lookaside.pFree;
   19080       db->lookaside.pFree = pBuf;
   19081       db->lookaside.nOut--;
   19082       return;
   19083     }
   19084   }
   19085   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   19086   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   19087   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   19088   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   19089   sqlite3_free(p);
   19090 }
   19091 
   19092 /*
   19093 ** Change the size of an existing memory allocation
   19094 */
   19095 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
   19096   int nOld, nNew, nDiff;
   19097   void *pNew;
   19098   if( pOld==0 ){
   19099     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
   19100   }
   19101   if( nBytes<=0 ){
   19102     sqlite3_free(pOld); /* IMP: R-31593-10574 */
   19103     return 0;
   19104   }
   19105   if( nBytes>=0x7fffff00 ){
   19106     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
   19107     return 0;
   19108   }
   19109   nOld = sqlite3MallocSize(pOld);
   19110   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
   19111   ** argument to xRealloc is always a value returned by a prior call to
   19112   ** xRoundup. */
   19113   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
   19114   if( nOld==nNew ){
   19115     pNew = pOld;
   19116   }else if( sqlite3GlobalConfig.bMemstat ){
   19117     sqlite3_mutex_enter(mem0.mutex);
   19118     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
   19119     nDiff = nNew - nOld;
   19120     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
   19121           mem0.alarmThreshold-nDiff ){
   19122       sqlite3MallocAlarm(nDiff);
   19123     }
   19124     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
   19125     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
   19126     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   19127     if( pNew==0 && mem0.alarmCallback ){
   19128       sqlite3MallocAlarm(nBytes);
   19129       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   19130     }
   19131     if( pNew ){
   19132       nNew = sqlite3MallocSize(pNew);
   19133       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
   19134     }
   19135     sqlite3_mutex_leave(mem0.mutex);
   19136   }else{
   19137     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   19138   }
   19139   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
   19140   return pNew;
   19141 }
   19142 
   19143 /*
   19144 ** The public interface to sqlite3Realloc.  Make sure that the memory
   19145 ** subsystem is initialized prior to invoking sqliteRealloc.
   19146 */
   19147 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
   19148 #ifndef SQLITE_OMIT_AUTOINIT
   19149   if( sqlite3_initialize() ) return 0;
   19150 #endif
   19151   return sqlite3Realloc(pOld, n);
   19152 }
   19153 
   19154 
   19155 /*
   19156 ** Allocate and zero memory.
   19157 */
   19158 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
   19159   void *p = sqlite3Malloc(n);
   19160   if( p ){
   19161     memset(p, 0, n);
   19162   }
   19163   return p;
   19164 }
   19165 
   19166 /*
   19167 ** Allocate and zero memory.  If the allocation fails, make
   19168 ** the mallocFailed flag in the connection pointer.
   19169 */
   19170 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
   19171   void *p = sqlite3DbMallocRaw(db, n);
   19172   if( p ){
   19173     memset(p, 0, n);
   19174   }
   19175   return p;
   19176 }
   19177 
   19178 /*
   19179 ** Allocate and zero memory.  If the allocation fails, make
   19180 ** the mallocFailed flag in the connection pointer.
   19181 **
   19182 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
   19183 ** failure on the same database connection) then always return 0.
   19184 ** Hence for a particular database connection, once malloc starts
   19185 ** failing, it fails consistently until mallocFailed is reset.
   19186 ** This is an important assumption.  There are many places in the
   19187 ** code that do things like this:
   19188 **
   19189 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   19190 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   19191 **         if( b ) a[10] = 9;
   19192 **
   19193 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   19194 ** that all prior mallocs (ex: "a") worked too.
   19195 */
   19196 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
   19197   void *p;
   19198   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   19199   assert( db==0 || db->pnBytesFreed==0 );
   19200 #ifndef SQLITE_OMIT_LOOKASIDE
   19201   if( db ){
   19202     LookasideSlot *pBuf;
   19203     if( db->mallocFailed ){
   19204       return 0;
   19205     }
   19206     if( db->lookaside.bEnabled ){
   19207       if( n>db->lookaside.sz ){
   19208         db->lookaside.anStat[1]++;
   19209       }else if( (pBuf = db->lookaside.pFree)==0 ){
   19210         db->lookaside.anStat[2]++;
   19211       }else{
   19212         db->lookaside.pFree = pBuf->pNext;
   19213         db->lookaside.nOut++;
   19214         db->lookaside.anStat[0]++;
   19215         if( db->lookaside.nOut>db->lookaside.mxOut ){
   19216           db->lookaside.mxOut = db->lookaside.nOut;
   19217         }
   19218         return (void*)pBuf;
   19219       }
   19220     }
   19221   }
   19222 #else
   19223   if( db && db->mallocFailed ){
   19224     return 0;
   19225   }
   19226 #endif
   19227   p = sqlite3Malloc(n);
   19228   if( !p && db ){
   19229     db->mallocFailed = 1;
   19230   }
   19231   sqlite3MemdebugSetType(p, MEMTYPE_DB |
   19232          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   19233   return p;
   19234 }
   19235 
   19236 /*
   19237 ** Resize the block of memory pointed to by p to n bytes. If the
   19238 ** resize fails, set the mallocFailed flag in the connection object.
   19239 */
   19240 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
   19241   void *pNew = 0;
   19242   assert( db!=0 );
   19243   assert( sqlite3_mutex_held(db->mutex) );
   19244   if( db->mallocFailed==0 ){
   19245     if( p==0 ){
   19246       return sqlite3DbMallocRaw(db, n);
   19247     }
   19248     if( isLookaside(db, p) ){
   19249       if( n<=db->lookaside.sz ){
   19250         return p;
   19251       }
   19252       pNew = sqlite3DbMallocRaw(db, n);
   19253       if( pNew ){
   19254         memcpy(pNew, p, db->lookaside.sz);
   19255         sqlite3DbFree(db, p);
   19256       }
   19257     }else{
   19258       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   19259       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   19260       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   19261       pNew = sqlite3_realloc(p, n);
   19262       if( !pNew ){
   19263         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
   19264         db->mallocFailed = 1;
   19265       }
   19266       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
   19267             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   19268     }
   19269   }
   19270   return pNew;
   19271 }
   19272 
   19273 /*
   19274 ** Attempt to reallocate p.  If the reallocation fails, then free p
   19275 ** and set the mallocFailed flag in the database connection.
   19276 */
   19277 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
   19278   void *pNew;
   19279   pNew = sqlite3DbRealloc(db, p, n);
   19280   if( !pNew ){
   19281     sqlite3DbFree(db, p);
   19282   }
   19283   return pNew;
   19284 }
   19285 
   19286 /*
   19287 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
   19288 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   19289 ** is because when memory debugging is turned on, these two functions are
   19290 ** called via macros that record the current file and line number in the
   19291 ** ThreadData structure.
   19292 */
   19293 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
   19294   char *zNew;
   19295   size_t n;
   19296   if( z==0 ){
   19297     return 0;
   19298   }
   19299   n = sqlite3Strlen30(z) + 1;
   19300   assert( (n&0x7fffffff)==n );
   19301   zNew = sqlite3DbMallocRaw(db, (int)n);
   19302   if( zNew ){
   19303     memcpy(zNew, z, n);
   19304   }
   19305   return zNew;
   19306 }
   19307 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
   19308   char *zNew;
   19309   if( z==0 ){
   19310     return 0;
   19311   }
   19312   assert( (n&0x7fffffff)==n );
   19313   zNew = sqlite3DbMallocRaw(db, n+1);
   19314   if( zNew ){
   19315     memcpy(zNew, z, n);
   19316     zNew[n] = 0;
   19317   }
   19318   return zNew;
   19319 }
   19320 
   19321 /*
   19322 ** Create a string from the zFromat argument and the va_list that follows.
   19323 ** Store the string in memory obtained from sqliteMalloc() and make *pz
   19324 ** point to that string.
   19325 */
   19326 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
   19327   va_list ap;
   19328   char *z;
   19329 
   19330   va_start(ap, zFormat);
   19331   z = sqlite3VMPrintf(db, zFormat, ap);
   19332   va_end(ap);
   19333   sqlite3DbFree(db, *pz);
   19334   *pz = z;
   19335 }
   19336 
   19337 
   19338 /*
   19339 ** This function must be called before exiting any API function (i.e.
   19340 ** returning control to the user) that has called sqlite3_malloc or
   19341 ** sqlite3_realloc.
   19342 **
   19343 ** The returned value is normally a copy of the second argument to this
   19344 ** function. However, if a malloc() failure has occurred since the previous
   19345 ** invocation SQLITE_NOMEM is returned instead.
   19346 **
   19347 ** If the first argument, db, is not NULL and a malloc() error has occurred,
   19348 ** then the connection error-code (the value returned by sqlite3_errcode())
   19349 ** is set to SQLITE_NOMEM.
   19350 */
   19351 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   19352   /* If the db handle is not NULL, then we must hold the connection handle
   19353   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
   19354   ** is unsafe, as is the call to sqlite3Error().
   19355   */
   19356   assert( !db || sqlite3_mutex_held(db->mutex) );
   19357   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
   19358     sqlite3Error(db, SQLITE_NOMEM, 0);
   19359     db->mallocFailed = 0;
   19360     rc = SQLITE_NOMEM;
   19361   }
   19362   return rc & (db ? db->errMask : 0xff);
   19363 }
   19364 
   19365 /************** End of malloc.c **********************************************/
   19366 /************** Begin file printf.c ******************************************/
   19367 /*
   19368 ** The "printf" code that follows dates from the 1980's.  It is in
   19369 ** the public domain.  The original comments are included here for
   19370 ** completeness.  They are very out-of-date but might be useful as
   19371 ** an historical reference.  Most of the "enhancements" have been backed
   19372 ** out so that the functionality is now the same as standard printf().
   19373 **
   19374 **************************************************************************
   19375 **
   19376 ** This file contains code for a set of "printf"-like routines.  These
   19377 ** routines format strings much like the printf() from the standard C
   19378 ** library, though the implementation here has enhancements to support
   19379 ** SQLlite.
   19380 */
   19381 
   19382 /*
   19383 ** Conversion types fall into various categories as defined by the
   19384 ** following enumeration.
   19385 */
   19386 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
   19387 #define etFLOAT       2 /* Floating point.  %f */
   19388 #define etEXP         3 /* Exponentional notation. %e and %E */
   19389 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
   19390 #define etSIZE        5 /* Return number of characters processed so far. %n */
   19391 #define etSTRING      6 /* Strings. %s */
   19392 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
   19393 #define etPERCENT     8 /* Percent symbol. %% */
   19394 #define etCHARX       9 /* Characters. %c */
   19395 /* The rest are extensions, not normally found in printf() */
   19396 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
   19397 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
   19398                           NULL pointers replaced by SQL NULL.  %Q */
   19399 #define etTOKEN      12 /* a pointer to a Token structure */
   19400 #define etSRCLIST    13 /* a pointer to a SrcList */
   19401 #define etPOINTER    14 /* The %p conversion */
   19402 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
   19403 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
   19404 
   19405 #define etINVALID     0 /* Any unrecognized conversion type */
   19406 
   19407 
   19408 /*
   19409 ** An "etByte" is an 8-bit unsigned value.
   19410 */
   19411 typedef unsigned char etByte;
   19412 
   19413 /*
   19414 ** Each builtin conversion character (ex: the 'd' in "%d") is described
   19415 ** by an instance of the following structure
   19416 */
   19417 typedef struct et_info {   /* Information about each format field */
   19418   char fmttype;            /* The format field code letter */
   19419   etByte base;             /* The base for radix conversion */
   19420   etByte flags;            /* One or more of FLAG_ constants below */
   19421   etByte type;             /* Conversion paradigm */
   19422   etByte charset;          /* Offset into aDigits[] of the digits string */
   19423   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
   19424 } et_info;
   19425 
   19426 /*
   19427 ** Allowed values for et_info.flags
   19428 */
   19429 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
   19430 #define FLAG_INTERN  2     /* True if for internal use only */
   19431 #define FLAG_STRING  4     /* Allow infinity precision */
   19432 
   19433 
   19434 /*
   19435 ** The following table is searched linearly, so it is good to put the
   19436 ** most frequently used conversion types first.
   19437 */
   19438 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
   19439 static const char aPrefix[] = "-x0\000X0";
   19440 static const et_info fmtinfo[] = {
   19441   {  'd', 10, 1, etRADIX,      0,  0 },
   19442   {  's',  0, 4, etSTRING,     0,  0 },
   19443   {  'g',  0, 1, etGENERIC,    30, 0 },
   19444   {  'z',  0, 4, etDYNSTRING,  0,  0 },
   19445   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
   19446   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
   19447   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
   19448   {  'c',  0, 0, etCHARX,      0,  0 },
   19449   {  'o',  8, 0, etRADIX,      0,  2 },
   19450   {  'u', 10, 0, etRADIX,      0,  0 },
   19451   {  'x', 16, 0, etRADIX,      16, 1 },
   19452   {  'X', 16, 0, etRADIX,      0,  4 },
   19453 #ifndef SQLITE_OMIT_FLOATING_POINT
   19454   {  'f',  0, 1, etFLOAT,      0,  0 },
   19455   {  'e',  0, 1, etEXP,        30, 0 },
   19456   {  'E',  0, 1, etEXP,        14, 0 },
   19457   {  'G',  0, 1, etGENERIC,    14, 0 },
   19458 #endif
   19459   {  'i', 10, 1, etRADIX,      0,  0 },
   19460   {  'n',  0, 0, etSIZE,       0,  0 },
   19461   {  '%',  0, 0, etPERCENT,    0,  0 },
   19462   {  'p', 16, 0, etPOINTER,    0,  1 },
   19463 
   19464 /* All the rest have the FLAG_INTERN bit set and are thus for internal
   19465 ** use only */
   19466   {  'T',  0, 2, etTOKEN,      0,  0 },
   19467   {  'S',  0, 2, etSRCLIST,    0,  0 },
   19468   {  'r', 10, 3, etORDINAL,    0,  0 },
   19469 };
   19470 
   19471 /*
   19472 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
   19473 ** conversions will work.
   19474 */
   19475 #ifndef SQLITE_OMIT_FLOATING_POINT
   19476 /*
   19477 ** "*val" is a double such that 0.1 <= *val < 10.0
   19478 ** Return the ascii code for the leading digit of *val, then
   19479 ** multiply "*val" by 10.0 to renormalize.
   19480 **
   19481 ** Example:
   19482 **     input:     *val = 3.14159
   19483 **     output:    *val = 1.4159    function return = '3'
   19484 **
   19485 ** The counter *cnt is incremented each time.  After counter exceeds
   19486 ** 16 (the number of significant digits in a 64-bit float) '0' is
   19487 ** always returned.
   19488 */
   19489 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
   19490   int digit;
   19491   LONGDOUBLE_TYPE d;
   19492   if( (*cnt)++ >= 16 ) return '0';
   19493   digit = (int)*val;
   19494   d = digit;
   19495   digit += '0';
   19496   *val = (*val - d)*10.0;
   19497   return (char)digit;
   19498 }
   19499 #endif /* SQLITE_OMIT_FLOATING_POINT */
   19500 
   19501 /*
   19502 ** Append N space characters to the given string buffer.
   19503 */
   19504 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
   19505   static const char zSpaces[] = "                             ";
   19506   while( N>=(int)sizeof(zSpaces)-1 ){
   19507     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
   19508     N -= sizeof(zSpaces)-1;
   19509   }
   19510   if( N>0 ){
   19511     sqlite3StrAccumAppend(pAccum, zSpaces, N);
   19512   }
   19513 }
   19514 
   19515 /*
   19516 ** On machines with a small stack size, you can redefine the
   19517 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
   19518 */
   19519 #ifndef SQLITE_PRINT_BUF_SIZE
   19520 # define SQLITE_PRINT_BUF_SIZE 70
   19521 #endif
   19522 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
   19523 
   19524 /*
   19525 ** Render a string given by "fmt" into the StrAccum object.
   19526 */
   19527 SQLITE_PRIVATE void sqlite3VXPrintf(
   19528   StrAccum *pAccum,                  /* Accumulate results here */
   19529   int useExtended,                   /* Allow extended %-conversions */
   19530   const char *fmt,                   /* Format string */
   19531   va_list ap                         /* arguments */
   19532 ){
   19533   int c;                     /* Next character in the format string */
   19534   char *bufpt;               /* Pointer to the conversion buffer */
   19535   int precision;             /* Precision of the current field */
   19536   int length;                /* Length of the field */
   19537   int idx;                   /* A general purpose loop counter */
   19538   int width;                 /* Width of the current field */
   19539   etByte flag_leftjustify;   /* True if "-" flag is present */
   19540   etByte flag_plussign;      /* True if "+" flag is present */
   19541   etByte flag_blanksign;     /* True if " " flag is present */
   19542   etByte flag_alternateform; /* True if "#" flag is present */
   19543   etByte flag_altform2;      /* True if "!" flag is present */
   19544   etByte flag_zeropad;       /* True if field width constant starts with zero */
   19545   etByte flag_long;          /* True if "l" flag is present */
   19546   etByte flag_longlong;      /* True if the "ll" flag is present */
   19547   etByte done;               /* Loop termination flag */
   19548   etByte xtype = 0;          /* Conversion paradigm */
   19549   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
   19550   sqlite_uint64 longvalue;   /* Value for integer types */
   19551   LONGDOUBLE_TYPE realvalue; /* Value for real types */
   19552   const et_info *infop;      /* Pointer to the appropriate info structure */
   19553   char *zOut;                /* Rendering buffer */
   19554   int nOut;                  /* Size of the rendering buffer */
   19555   char *zExtra;              /* Malloced memory used by some conversion */
   19556 #ifndef SQLITE_OMIT_FLOATING_POINT
   19557   int  exp, e2;              /* exponent of real numbers */
   19558   int nsd;                   /* Number of significant digits returned */
   19559   double rounder;            /* Used for rounding floating point values */
   19560   etByte flag_dp;            /* True if decimal point should be shown */
   19561   etByte flag_rtz;           /* True if trailing zeros should be removed */
   19562 #endif
   19563   char buf[etBUFSIZE];       /* Conversion buffer */
   19564 
   19565   bufpt = 0;
   19566   for(; (c=(*fmt))!=0; ++fmt){
   19567     if( c!='%' ){
   19568       int amt;
   19569       bufpt = (char *)fmt;
   19570       amt = 1;
   19571       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
   19572       sqlite3StrAccumAppend(pAccum, bufpt, amt);
   19573       if( c==0 ) break;
   19574     }
   19575     if( (c=(*++fmt))==0 ){
   19576       sqlite3StrAccumAppend(pAccum, "%", 1);
   19577       break;
   19578     }
   19579     /* Find out what flags are present */
   19580     flag_leftjustify = flag_plussign = flag_blanksign =
   19581      flag_alternateform = flag_altform2 = flag_zeropad = 0;
   19582     done = 0;
   19583     do{
   19584       switch( c ){
   19585         case '-':   flag_leftjustify = 1;     break;
   19586         case '+':   flag_plussign = 1;        break;
   19587         case ' ':   flag_blanksign = 1;       break;
   19588         case '#':   flag_alternateform = 1;   break;
   19589         case '!':   flag_altform2 = 1;        break;
   19590         case '0':   flag_zeropad = 1;         break;
   19591         default:    done = 1;                 break;
   19592       }
   19593     }while( !done && (c=(*++fmt))!=0 );
   19594     /* Get the field width */
   19595     width = 0;
   19596     if( c=='*' ){
   19597       width = va_arg(ap,int);
   19598       if( width<0 ){
   19599         flag_leftjustify = 1;
   19600         width = -width;
   19601       }
   19602       c = *++fmt;
   19603     }else{
   19604       while( c>='0' && c<='9' ){
   19605         width = width*10 + c - '0';
   19606         c = *++fmt;
   19607       }
   19608     }
   19609     /* Get the precision */
   19610     if( c=='.' ){
   19611       precision = 0;
   19612       c = *++fmt;
   19613       if( c=='*' ){
   19614         precision = va_arg(ap,int);
   19615         if( precision<0 ) precision = -precision;
   19616         c = *++fmt;
   19617       }else{
   19618         while( c>='0' && c<='9' ){
   19619           precision = precision*10 + c - '0';
   19620           c = *++fmt;
   19621         }
   19622       }
   19623     }else{
   19624       precision = -1;
   19625     }
   19626     /* Get the conversion type modifier */
   19627     if( c=='l' ){
   19628       flag_long = 1;
   19629       c = *++fmt;
   19630       if( c=='l' ){
   19631         flag_longlong = 1;
   19632         c = *++fmt;
   19633       }else{
   19634         flag_longlong = 0;
   19635       }
   19636     }else{
   19637       flag_long = flag_longlong = 0;
   19638     }
   19639     /* Fetch the info entry for the field */
   19640     infop = &fmtinfo[0];
   19641     xtype = etINVALID;
   19642     for(idx=0; idx<ArraySize(fmtinfo); idx++){
   19643       if( c==fmtinfo[idx].fmttype ){
   19644         infop = &fmtinfo[idx];
   19645         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
   19646           xtype = infop->type;
   19647         }else{
   19648           return;
   19649         }
   19650         break;
   19651       }
   19652     }
   19653     zExtra = 0;
   19654 
   19655     /*
   19656     ** At this point, variables are initialized as follows:
   19657     **
   19658     **   flag_alternateform          TRUE if a '#' is present.
   19659     **   flag_altform2               TRUE if a '!' is present.
   19660     **   flag_plussign               TRUE if a '+' is present.
   19661     **   flag_leftjustify            TRUE if a '-' is present or if the
   19662     **                               field width was negative.
   19663     **   flag_zeropad                TRUE if the width began with 0.
   19664     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
   19665     **                               the conversion character.
   19666     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
   19667     **                               the conversion character.
   19668     **   flag_blanksign              TRUE if a ' ' is present.
   19669     **   width                       The specified field width.  This is
   19670     **                               always non-negative.  Zero is the default.
   19671     **   precision                   The specified precision.  The default
   19672     **                               is -1.
   19673     **   xtype                       The class of the conversion.
   19674     **   infop                       Pointer to the appropriate info struct.
   19675     */
   19676     switch( xtype ){
   19677       case etPOINTER:
   19678         flag_longlong = sizeof(char*)==sizeof(i64);
   19679         flag_long = sizeof(char*)==sizeof(long int);
   19680         /* Fall through into the next case */
   19681       case etORDINAL:
   19682       case etRADIX:
   19683         if( infop->flags & FLAG_SIGNED ){
   19684           i64 v;
   19685           if( flag_longlong ){
   19686             v = va_arg(ap,i64);
   19687           }else if( flag_long ){
   19688             v = va_arg(ap,long int);
   19689           }else{
   19690             v = va_arg(ap,int);
   19691           }
   19692           if( v<0 ){
   19693             if( v==SMALLEST_INT64 ){
   19694               longvalue = ((u64)1)<<63;
   19695             }else{
   19696               longvalue = -v;
   19697             }
   19698             prefix = '-';
   19699           }else{
   19700             longvalue = v;
   19701             if( flag_plussign )        prefix = '+';
   19702             else if( flag_blanksign )  prefix = ' ';
   19703             else                       prefix = 0;
   19704           }
   19705         }else{
   19706           if( flag_longlong ){
   19707             longvalue = va_arg(ap,u64);
   19708           }else if( flag_long ){
   19709             longvalue = va_arg(ap,unsigned long int);
   19710           }else{
   19711             longvalue = va_arg(ap,unsigned int);
   19712           }
   19713           prefix = 0;
   19714         }
   19715         if( longvalue==0 ) flag_alternateform = 0;
   19716         if( flag_zeropad && precision<width-(prefix!=0) ){
   19717           precision = width-(prefix!=0);
   19718         }
   19719         if( precision<etBUFSIZE-10 ){
   19720           nOut = etBUFSIZE;
   19721           zOut = buf;
   19722         }else{
   19723           nOut = precision + 10;
   19724           zOut = zExtra = sqlite3Malloc( nOut );
   19725           if( zOut==0 ){
   19726             pAccum->mallocFailed = 1;
   19727             return;
   19728           }
   19729         }
   19730         bufpt = &zOut[nOut-1];
   19731         if( xtype==etORDINAL ){
   19732           static const char zOrd[] = "thstndrd";
   19733           int x = (int)(longvalue % 10);
   19734           if( x>=4 || (longvalue/10)%10==1 ){
   19735             x = 0;
   19736           }
   19737           *(--bufpt) = zOrd[x*2+1];
   19738           *(--bufpt) = zOrd[x*2];
   19739         }
   19740         {
   19741           register const char *cset;      /* Use registers for speed */
   19742           register int base;
   19743           cset = &aDigits[infop->charset];
   19744           base = infop->base;
   19745           do{                                           /* Convert to ascii */
   19746             *(--bufpt) = cset[longvalue%base];
   19747             longvalue = longvalue/base;
   19748           }while( longvalue>0 );
   19749         }
   19750         length = (int)(&zOut[nOut-1]-bufpt);
   19751         for(idx=precision-length; idx>0; idx--){
   19752           *(--bufpt) = '0';                             /* Zero pad */
   19753         }
   19754         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
   19755         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
   19756           const char *pre;
   19757           char x;
   19758           pre = &aPrefix[infop->prefix];
   19759           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
   19760         }
   19761         length = (int)(&zOut[nOut-1]-bufpt);
   19762         break;
   19763       case etFLOAT:
   19764       case etEXP:
   19765       case etGENERIC:
   19766         realvalue = va_arg(ap,double);
   19767 #ifdef SQLITE_OMIT_FLOATING_POINT
   19768         length = 0;
   19769 #else
   19770         if( precision<0 ) precision = 6;         /* Set default precision */
   19771         if( realvalue<0.0 ){
   19772           realvalue = -realvalue;
   19773           prefix = '-';
   19774         }else{
   19775           if( flag_plussign )          prefix = '+';
   19776           else if( flag_blanksign )    prefix = ' ';
   19777           else                         prefix = 0;
   19778         }
   19779         if( xtype==etGENERIC && precision>0 ) precision--;
   19780 #if 0
   19781         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
   19782         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
   19783 #else
   19784         /* It makes more sense to use 0.5 */
   19785         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
   19786 #endif
   19787         if( xtype==etFLOAT ) realvalue += rounder;
   19788         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
   19789         exp = 0;
   19790         if( sqlite3IsNaN((double)realvalue) ){
   19791           bufpt = "NaN";
   19792           length = 3;
   19793           break;
   19794         }
   19795         if( realvalue>0.0 ){
   19796           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
   19797           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
   19798           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
   19799           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
   19800           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
   19801           if( exp>350 ){
   19802             if( prefix=='-' ){
   19803               bufpt = "-Inf";
   19804             }else if( prefix=='+' ){
   19805               bufpt = "+Inf";
   19806             }else{
   19807               bufpt = "Inf";
   19808             }
   19809             length = sqlite3Strlen30(bufpt);
   19810             break;
   19811           }
   19812         }
   19813         bufpt = buf;
   19814         /*
   19815         ** If the field type is etGENERIC, then convert to either etEXP
   19816         ** or etFLOAT, as appropriate.
   19817         */
   19818         if( xtype!=etFLOAT ){
   19819           realvalue += rounder;
   19820           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
   19821         }
   19822         if( xtype==etGENERIC ){
   19823           flag_rtz = !flag_alternateform;
   19824           if( exp<-4 || exp>precision ){
   19825             xtype = etEXP;
   19826           }else{
   19827             precision = precision - exp;
   19828             xtype = etFLOAT;
   19829           }
   19830         }else{
   19831           flag_rtz = 0;
   19832         }
   19833         if( xtype==etEXP ){
   19834           e2 = 0;
   19835         }else{
   19836           e2 = exp;
   19837         }
   19838         if( e2+precision+width > etBUFSIZE - 15 ){
   19839           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
   19840           if( bufpt==0 ){
   19841             pAccum->mallocFailed = 1;
   19842             return;
   19843           }
   19844         }
   19845         zOut = bufpt;
   19846         nsd = 0;
   19847         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
   19848         /* The sign in front of the number */
   19849         if( prefix ){
   19850           *(bufpt++) = prefix;
   19851         }
   19852         /* Digits prior to the decimal point */
   19853         if( e2<0 ){
   19854           *(bufpt++) = '0';
   19855         }else{
   19856           for(; e2>=0; e2--){
   19857             *(bufpt++) = et_getdigit(&realvalue,&nsd);
   19858           }
   19859         }
   19860         /* The decimal point */
   19861         if( flag_dp ){
   19862           *(bufpt++) = '.';
   19863         }
   19864         /* "0" digits after the decimal point but before the first
   19865         ** significant digit of the number */
   19866         for(e2++; e2<0; precision--, e2++){
   19867           assert( precision>0 );
   19868           *(bufpt++) = '0';
   19869         }
   19870         /* Significant digits after the decimal point */
   19871         while( (precision--)>0 ){
   19872           *(bufpt++) = et_getdigit(&realvalue,&nsd);
   19873         }
   19874         /* Remove trailing zeros and the "." if no digits follow the "." */
   19875         if( flag_rtz && flag_dp ){
   19876           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
   19877           assert( bufpt>zOut );
   19878           if( bufpt[-1]=='.' ){
   19879             if( flag_altform2 ){
   19880               *(bufpt++) = '0';
   19881             }else{
   19882               *(--bufpt) = 0;
   19883             }
   19884           }
   19885         }
   19886         /* Add the "eNNN" suffix */
   19887         if( xtype==etEXP ){
   19888           *(bufpt++) = aDigits[infop->charset];
   19889           if( exp<0 ){
   19890             *(bufpt++) = '-'; exp = -exp;
   19891           }else{
   19892             *(bufpt++) = '+';
   19893           }
   19894           if( exp>=100 ){
   19895             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
   19896             exp %= 100;
   19897           }
   19898           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
   19899           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
   19900         }
   19901         *bufpt = 0;
   19902 
   19903         /* The converted number is in buf[] and zero terminated. Output it.
   19904         ** Note that the number is in the usual order, not reversed as with
   19905         ** integer conversions. */
   19906         length = (int)(bufpt-zOut);
   19907         bufpt = zOut;
   19908 
   19909         /* Special case:  Add leading zeros if the flag_zeropad flag is
   19910         ** set and we are not left justified */
   19911         if( flag_zeropad && !flag_leftjustify && length < width){
   19912           int i;
   19913           int nPad = width - length;
   19914           for(i=width; i>=nPad; i--){
   19915             bufpt[i] = bufpt[i-nPad];
   19916           }
   19917           i = prefix!=0;
   19918           while( nPad-- ) bufpt[i++] = '0';
   19919           length = width;
   19920         }
   19921 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
   19922         break;
   19923       case etSIZE:
   19924         *(va_arg(ap,int*)) = pAccum->nChar;
   19925         length = width = 0;
   19926         break;
   19927       case etPERCENT:
   19928         buf[0] = '%';
   19929         bufpt = buf;
   19930         length = 1;
   19931         break;
   19932       case etCHARX:
   19933         c = va_arg(ap,int);
   19934         buf[0] = (char)c;
   19935         if( precision>=0 ){
   19936           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
   19937           length = precision;
   19938         }else{
   19939           length =1;
   19940         }
   19941         bufpt = buf;
   19942         break;
   19943       case etSTRING:
   19944       case etDYNSTRING:
   19945         bufpt = va_arg(ap,char*);
   19946         if( bufpt==0 ){
   19947           bufpt = "";
   19948         }else if( xtype==etDYNSTRING ){
   19949           zExtra = bufpt;
   19950         }
   19951         if( precision>=0 ){
   19952           for(length=0; length<precision && bufpt[length]; length++){}
   19953         }else{
   19954           length = sqlite3Strlen30(bufpt);
   19955         }
   19956         break;
   19957       case etSQLESCAPE:
   19958       case etSQLESCAPE2:
   19959       case etSQLESCAPE3: {
   19960         int i, j, k, n, isnull;
   19961         int needQuote;
   19962         char ch;
   19963         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
   19964         char *escarg = va_arg(ap,char*);
   19965         isnull = escarg==0;
   19966         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
   19967         k = precision;
   19968         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
   19969           if( ch==q )  n++;
   19970         }
   19971         needQuote = !isnull && xtype==etSQLESCAPE2;
   19972         n += i + 1 + needQuote*2;
   19973         if( n>etBUFSIZE ){
   19974           bufpt = zExtra = sqlite3Malloc( n );
   19975           if( bufpt==0 ){
   19976             pAccum->mallocFailed = 1;
   19977             return;
   19978           }
   19979         }else{
   19980           bufpt = buf;
   19981         }
   19982         j = 0;
   19983         if( needQuote ) bufpt[j++] = q;
   19984         k = i;
   19985         for(i=0; i<k; i++){
   19986           bufpt[j++] = ch = escarg[i];
   19987           if( ch==q ) bufpt[j++] = ch;
   19988         }
   19989         if( needQuote ) bufpt[j++] = q;
   19990         bufpt[j] = 0;
   19991         length = j;
   19992         /* The precision in %q and %Q means how many input characters to
   19993         ** consume, not the length of the output...
   19994         ** if( precision>=0 && precision<length ) length = precision; */
   19995         break;
   19996       }
   19997       case etTOKEN: {
   19998         Token *pToken = va_arg(ap, Token*);
   19999         if( pToken ){
   20000           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
   20001         }
   20002         length = width = 0;
   20003         break;
   20004       }
   20005       case etSRCLIST: {
   20006         SrcList *pSrc = va_arg(ap, SrcList*);
   20007         int k = va_arg(ap, int);
   20008         struct SrcList_item *pItem = &pSrc->a[k];
   20009         assert( k>=0 && k<pSrc->nSrc );
   20010         if( pItem->zDatabase ){
   20011           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
   20012           sqlite3StrAccumAppend(pAccum, ".", 1);
   20013         }
   20014         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
   20015         length = width = 0;
   20016         break;
   20017       }
   20018       default: {
   20019         assert( xtype==etINVALID );
   20020         return;
   20021       }
   20022     }/* End switch over the format type */
   20023     /*
   20024     ** The text of the conversion is pointed to by "bufpt" and is
   20025     ** "length" characters long.  The field width is "width".  Do
   20026     ** the output.
   20027     */
   20028     if( !flag_leftjustify ){
   20029       register int nspace;
   20030       nspace = width-length;
   20031       if( nspace>0 ){
   20032         sqlite3AppendSpace(pAccum, nspace);
   20033       }
   20034     }
   20035     if( length>0 ){
   20036       sqlite3StrAccumAppend(pAccum, bufpt, length);
   20037     }
   20038     if( flag_leftjustify ){
   20039       register int nspace;
   20040       nspace = width-length;
   20041       if( nspace>0 ){
   20042         sqlite3AppendSpace(pAccum, nspace);
   20043       }
   20044     }
   20045     sqlite3_free(zExtra);
   20046   }/* End for loop over the format string */
   20047 } /* End of function */
   20048 
   20049 /*
   20050 ** Append N bytes of text from z to the StrAccum object.
   20051 */
   20052 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
   20053   assert( z!=0 || N==0 );
   20054   if( p->tooBig | p->mallocFailed ){
   20055     testcase(p->tooBig);
   20056     testcase(p->mallocFailed);
   20057     return;
   20058   }
   20059   assert( p->zText!=0 || p->nChar==0 );
   20060   if( N<0 ){
   20061     N = sqlite3Strlen30(z);
   20062   }
   20063   if( N==0 || NEVER(z==0) ){
   20064     return;
   20065   }
   20066   if( p->nChar+N >= p->nAlloc ){
   20067     char *zNew;
   20068     if( !p->useMalloc ){
   20069       p->tooBig = 1;
   20070       N = p->nAlloc - p->nChar - 1;
   20071       if( N<=0 ){
   20072         return;
   20073       }
   20074     }else{
   20075       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
   20076       i64 szNew = p->nChar;
   20077       szNew += N + 1;
   20078       if( szNew > p->mxAlloc ){
   20079         sqlite3StrAccumReset(p);
   20080         p->tooBig = 1;
   20081         return;
   20082       }else{
   20083         p->nAlloc = (int)szNew;
   20084       }
   20085       if( p->useMalloc==1 ){
   20086         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
   20087       }else{
   20088         zNew = sqlite3_realloc(zOld, p->nAlloc);
   20089       }
   20090       if( zNew ){
   20091         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
   20092         p->zText = zNew;
   20093       }else{
   20094         p->mallocFailed = 1;
   20095         sqlite3StrAccumReset(p);
   20096         return;
   20097       }
   20098     }
   20099   }
   20100   assert( p->zText );
   20101   memcpy(&p->zText[p->nChar], z, N);
   20102   p->nChar += N;
   20103 }
   20104 
   20105 /*
   20106 ** Finish off a string by making sure it is zero-terminated.
   20107 ** Return a pointer to the resulting string.  Return a NULL
   20108 ** pointer if any kind of error was encountered.
   20109 */
   20110 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   20111   if( p->zText ){
   20112     p->zText[p->nChar] = 0;
   20113     if( p->useMalloc && p->zText==p->zBase ){
   20114       if( p->useMalloc==1 ){
   20115         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
   20116       }else{
   20117         p->zText = sqlite3_malloc(p->nChar+1);
   20118       }
   20119       if( p->zText ){
   20120         memcpy(p->zText, p->zBase, p->nChar+1);
   20121       }else{
   20122         p->mallocFailed = 1;
   20123       }
   20124     }
   20125   }
   20126   return p->zText;
   20127 }
   20128 
   20129 /*
   20130 ** Reset an StrAccum string.  Reclaim all malloced memory.
   20131 */
   20132 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
   20133   if( p->zText!=p->zBase ){
   20134     if( p->useMalloc==1 ){
   20135       sqlite3DbFree(p->db, p->zText);
   20136     }else{
   20137       sqlite3_free(p->zText);
   20138     }
   20139   }
   20140   p->zText = 0;
   20141 }
   20142 
   20143 /*
   20144 ** Initialize a string accumulator
   20145 */
   20146 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
   20147   p->zText = p->zBase = zBase;
   20148   p->db = 0;
   20149   p->nChar = 0;
   20150   p->nAlloc = n;
   20151   p->mxAlloc = mx;
   20152   p->useMalloc = 1;
   20153   p->tooBig = 0;
   20154   p->mallocFailed = 0;
   20155 }
   20156 
   20157 /*
   20158 ** Print into memory obtained from sqliteMalloc().  Use the internal
   20159 ** %-conversion extensions.
   20160 */
   20161 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   20162   char *z;
   20163   char zBase[SQLITE_PRINT_BUF_SIZE];
   20164   StrAccum acc;
   20165   assert( db!=0 );
   20166   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
   20167                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   20168   acc.db = db;
   20169   sqlite3VXPrintf(&acc, 1, zFormat, ap);
   20170   z = sqlite3StrAccumFinish(&acc);
   20171   if( acc.mallocFailed ){
   20172     db->mallocFailed = 1;
   20173   }
   20174   return z;
   20175 }
   20176 
   20177 /*
   20178 ** Print into memory obtained from sqliteMalloc().  Use the internal
   20179 ** %-conversion extensions.
   20180 */
   20181 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   20182   va_list ap;
   20183   char *z;
   20184   va_start(ap, zFormat);
   20185   z = sqlite3VMPrintf(db, zFormat, ap);
   20186   va_end(ap);
   20187   return z;
   20188 }
   20189 
   20190 /*
   20191 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
   20192 ** the string and before returnning.  This routine is intended to be used
   20193 ** to modify an existing string.  For example:
   20194 **
   20195 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
   20196 **
   20197 */
   20198 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
   20199   va_list ap;
   20200   char *z;
   20201   va_start(ap, zFormat);
   20202   z = sqlite3VMPrintf(db, zFormat, ap);
   20203   va_end(ap);
   20204   sqlite3DbFree(db, zStr);
   20205   return z;
   20206 }
   20207 
   20208 /*
   20209 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   20210 ** %-conversion extensions.
   20211 */
   20212 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   20213   char *z;
   20214   char zBase[SQLITE_PRINT_BUF_SIZE];
   20215   StrAccum acc;
   20216 #ifndef SQLITE_OMIT_AUTOINIT
   20217   if( sqlite3_initialize() ) return 0;
   20218 #endif
   20219   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
   20220   acc.useMalloc = 2;
   20221   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   20222   z = sqlite3StrAccumFinish(&acc);
   20223   return z;
   20224 }
   20225 
   20226 /*
   20227 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   20228 ** %-conversion extensions.
   20229 */
   20230 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
   20231   va_list ap;
   20232   char *z;
   20233 #ifndef SQLITE_OMIT_AUTOINIT
   20234   if( sqlite3_initialize() ) return 0;
   20235 #endif
   20236   va_start(ap, zFormat);
   20237   z = sqlite3_vmprintf(zFormat, ap);
   20238   va_end(ap);
   20239   return z;
   20240 }
   20241 
   20242 /*
   20243 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   20244 ** current locale settings.  This is important for SQLite because we
   20245 ** are not able to use a "," as the decimal point in place of "." as
   20246 ** specified by some locales.
   20247 **
   20248 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
   20249 ** from the snprintf() standard.  Unfortunately, it is too late to change
   20250 ** this without breaking compatibility, so we just have to live with the
   20251 ** mistake.
   20252 **
   20253 ** sqlite3_vsnprintf() is the varargs version.
   20254 */
   20255 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
   20256   StrAccum acc;
   20257   if( n<=0 ) return zBuf;
   20258   sqlite3StrAccumInit(&acc, zBuf, n, 0);
   20259   acc.useMalloc = 0;
   20260   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   20261   return sqlite3StrAccumFinish(&acc);
   20262 }
   20263 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   20264   char *z;
   20265   va_list ap;
   20266   va_start(ap,zFormat);
   20267   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
   20268   va_end(ap);
   20269   return z;
   20270 }
   20271 
   20272 /*
   20273 ** This is the routine that actually formats the sqlite3_log() message.
   20274 ** We house it in a separate routine from sqlite3_log() to avoid using
   20275 ** stack space on small-stack systems when logging is disabled.
   20276 **
   20277 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
   20278 ** allocate memory because it might be called while the memory allocator
   20279 ** mutex is held.
   20280 */
   20281 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
   20282   StrAccum acc;                          /* String accumulator */
   20283   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
   20284 
   20285   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
   20286   acc.useMalloc = 0;
   20287   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   20288   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
   20289                            sqlite3StrAccumFinish(&acc));
   20290 }
   20291 
   20292 /*
   20293 ** Format and write a message to the log if logging is enabled.
   20294 */
   20295 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
   20296   va_list ap;                             /* Vararg list */
   20297   if( sqlite3GlobalConfig.xLog ){
   20298     va_start(ap, zFormat);
   20299     renderLogMsg(iErrCode, zFormat, ap);
   20300     va_end(ap);
   20301   }
   20302 }
   20303 
   20304 #if defined(SQLITE_DEBUG)
   20305 /*
   20306 ** A version of printf() that understands %lld.  Used for debugging.
   20307 ** The printf() built into some versions of windows does not understand %lld
   20308 ** and segfaults if you give it a long long int.
   20309 */
   20310 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   20311   va_list ap;
   20312   StrAccum acc;
   20313   char zBuf[500];
   20314   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
   20315   acc.useMalloc = 0;
   20316   va_start(ap,zFormat);
   20317   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   20318   va_end(ap);
   20319   sqlite3StrAccumFinish(&acc);
   20320   fprintf(stdout,"%s", zBuf);
   20321   fflush(stdout);
   20322 }
   20323 #endif
   20324 
   20325 #ifndef SQLITE_OMIT_TRACE
   20326 /*
   20327 ** variable-argument wrapper around sqlite3VXPrintf().
   20328 */
   20329 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
   20330   va_list ap;
   20331   va_start(ap,zFormat);
   20332   sqlite3VXPrintf(p, 1, zFormat, ap);
   20333   va_end(ap);
   20334 }
   20335 #endif
   20336 
   20337 /************** End of printf.c **********************************************/
   20338 /************** Begin file random.c ******************************************/
   20339 /*
   20340 ** 2001 September 15
   20341 **
   20342 ** The author disclaims copyright to this source code.  In place of
   20343 ** a legal notice, here is a blessing:
   20344 **
   20345 **    May you do good and not evil.
   20346 **    May you find forgiveness for yourself and forgive others.
   20347 **    May you share freely, never taking more than you give.
   20348 **
   20349 *************************************************************************
   20350 ** This file contains code to implement a pseudo-random number
   20351 ** generator (PRNG) for SQLite.
   20352 **
   20353 ** Random numbers are used by some of the database backends in order
   20354 ** to generate random integer keys for tables or random filenames.
   20355 */
   20356 
   20357 
   20358 /* All threads share a single random number generator.
   20359 ** This structure is the current state of the generator.
   20360 */
   20361 static SQLITE_WSD struct sqlite3PrngType {
   20362   unsigned char isInit;          /* True if initialized */
   20363   unsigned char i, j;            /* State variables */
   20364   unsigned char s[256];          /* State variables */
   20365 } sqlite3Prng;
   20366 
   20367 /*
   20368 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
   20369 ** must be held while executing this routine.
   20370 **
   20371 ** Why not just use a library random generator like lrand48() for this?
   20372 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
   20373 ** good source of random numbers.  The lrand48() library function may
   20374 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
   20375 ** subtle problems on some systems that could cause problems.  It is hard
   20376 ** to know.  To minimize the risk of problems due to bad lrand48()
   20377 ** implementations, SQLite uses this random number generator based
   20378 ** on RC4, which we know works very well.
   20379 **
   20380 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
   20381 ** randomness any more.  But we will leave this code in all the same.
   20382 */
   20383 static u8 randomByte(void){
   20384   unsigned char t;
   20385 
   20386 
   20387   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
   20388   ** state vector.  If writable static data is unsupported on the target,
   20389   ** we have to locate the state vector at run-time.  In the more common
   20390   ** case where writable static data is supported, wsdPrng can refer directly
   20391   ** to the "sqlite3Prng" state vector declared above.
   20392   */
   20393 #ifdef SQLITE_OMIT_WSD
   20394   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
   20395 # define wsdPrng p[0]
   20396 #else
   20397 # define wsdPrng sqlite3Prng
   20398 #endif
   20399 
   20400 
   20401   /* Initialize the state of the random number generator once,
   20402   ** the first time this routine is called.  The seed value does
   20403   ** not need to contain a lot of randomness since we are not
   20404   ** trying to do secure encryption or anything like that...
   20405   **
   20406   ** Nothing in this file or anywhere else in SQLite does any kind of
   20407   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
   20408   ** number generator) not as an encryption device.
   20409   */
   20410   if( !wsdPrng.isInit ){
   20411     int i;
   20412     char k[256];
   20413     wsdPrng.j = 0;
   20414     wsdPrng.i = 0;
   20415     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
   20416     for(i=0; i<256; i++){
   20417       wsdPrng.s[i] = (u8)i;
   20418     }
   20419     for(i=0; i<256; i++){
   20420       wsdPrng.j += wsdPrng.s[i] + k[i];
   20421       t = wsdPrng.s[wsdPrng.j];
   20422       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
   20423       wsdPrng.s[i] = t;
   20424     }
   20425     wsdPrng.isInit = 1;
   20426   }
   20427 
   20428   /* Generate and return single random byte
   20429   */
   20430   wsdPrng.i++;
   20431   t = wsdPrng.s[wsdPrng.i];
   20432   wsdPrng.j += t;
   20433   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
   20434   wsdPrng.s[wsdPrng.j] = t;
   20435   t += wsdPrng.s[wsdPrng.i];
   20436   return wsdPrng.s[t];
   20437 }
   20438 
   20439 /*
   20440 ** Return N random bytes.
   20441 */
   20442 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   20443   unsigned char *zBuf = pBuf;
   20444 #if SQLITE_THREADSAFE
   20445   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
   20446 #endif
   20447   sqlite3_mutex_enter(mutex);
   20448   while( N-- ){
   20449     *(zBuf++) = randomByte();
   20450   }
   20451   sqlite3_mutex_leave(mutex);
   20452 }
   20453 
   20454 #ifndef SQLITE_OMIT_BUILTIN_TEST
   20455 /*
   20456 ** For testing purposes, we sometimes want to preserve the state of
   20457 ** PRNG and restore the PRNG to its saved state at a later time, or
   20458 ** to reset the PRNG to its initial state.  These routines accomplish
   20459 ** those tasks.
   20460 **
   20461 ** The sqlite3_test_control() interface calls these routines to
   20462 ** control the PRNG.
   20463 */
   20464 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
   20465 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
   20466   memcpy(
   20467     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   20468     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   20469     sizeof(sqlite3Prng)
   20470   );
   20471 }
   20472 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
   20473   memcpy(
   20474     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   20475     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   20476     sizeof(sqlite3Prng)
   20477   );
   20478 }
   20479 SQLITE_PRIVATE void sqlite3PrngResetState(void){
   20480   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
   20481 }
   20482 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   20483 
   20484 /************** End of random.c **********************************************/
   20485 /************** Begin file utf.c *********************************************/
   20486 /*
   20487 ** 2004 April 13
   20488 **
   20489 ** The author disclaims copyright to this source code.  In place of
   20490 ** a legal notice, here is a blessing:
   20491 **
   20492 **    May you do good and not evil.
   20493 **    May you find forgiveness for yourself and forgive others.
   20494 **    May you share freely, never taking more than you give.
   20495 **
   20496 *************************************************************************
   20497 ** This file contains routines used to translate between UTF-8,
   20498 ** UTF-16, UTF-16BE, and UTF-16LE.
   20499 **
   20500 ** Notes on UTF-8:
   20501 **
   20502 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
   20503 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
   20504 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
   20505 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
   20506 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
   20507 **
   20508 **
   20509 ** Notes on UTF-16:  (with wwww+1==uuuuu)
   20510 **
   20511 **      Word-0               Word-1          Value
   20512 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
   20513 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
   20514 **
   20515 **
   20516 ** BOM or Byte Order Mark:
   20517 **     0xff 0xfe   little-endian utf-16 follows
   20518 **     0xfe 0xff   big-endian utf-16 follows
   20519 **
   20520 */
   20521 /* #include <assert.h> */
   20522 
   20523 #ifndef SQLITE_AMALGAMATION
   20524 /*
   20525 ** The following constant value is used by the SQLITE_BIGENDIAN and
   20526 ** SQLITE_LITTLEENDIAN macros.
   20527 */
   20528 SQLITE_PRIVATE const int sqlite3one = 1;
   20529 #endif /* SQLITE_AMALGAMATION */
   20530 
   20531 /*
   20532 ** This lookup table is used to help decode the first byte of
   20533 ** a multi-byte UTF8 character.
   20534 */
   20535 static const unsigned char sqlite3Utf8Trans1[] = {
   20536   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   20537   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   20538   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   20539   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   20540   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   20541   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   20542   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   20543   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   20544 };
   20545 
   20546 
   20547 #define WRITE_UTF8(zOut, c) {                          \
   20548   if( c<0x00080 ){                                     \
   20549     *zOut++ = (u8)(c&0xFF);                            \
   20550   }                                                    \
   20551   else if( c<0x00800 ){                                \
   20552     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   20553     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   20554   }                                                    \
   20555   else if( c<0x10000 ){                                \
   20556     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   20557     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   20558     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   20559   }else{                                               \
   20560     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   20561     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   20562     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   20563     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   20564   }                                                    \
   20565 }
   20566 
   20567 #define WRITE_UTF16LE(zOut, c) {                                    \
   20568   if( c<=0xFFFF ){                                                  \
   20569     *zOut++ = (u8)(c&0x00FF);                                       \
   20570     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   20571   }else{                                                            \
   20572     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   20573     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   20574     *zOut++ = (u8)(c&0x00FF);                                       \
   20575     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   20576   }                                                                 \
   20577 }
   20578 
   20579 #define WRITE_UTF16BE(zOut, c) {                                    \
   20580   if( c<=0xFFFF ){                                                  \
   20581     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   20582     *zOut++ = (u8)(c&0x00FF);                                       \
   20583   }else{                                                            \
   20584     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   20585     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   20586     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   20587     *zOut++ = (u8)(c&0x00FF);                                       \
   20588   }                                                                 \
   20589 }
   20590 
   20591 #define READ_UTF16LE(zIn, TERM, c){                                   \
   20592   c = (*zIn++);                                                       \
   20593   c += ((*zIn++)<<8);                                                 \
   20594   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   20595     int c2 = (*zIn++);                                                \
   20596     c2 += ((*zIn++)<<8);                                              \
   20597     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   20598   }                                                                   \
   20599 }
   20600 
   20601 #define READ_UTF16BE(zIn, TERM, c){                                   \
   20602   c = ((*zIn++)<<8);                                                  \
   20603   c += (*zIn++);                                                      \
   20604   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   20605     int c2 = ((*zIn++)<<8);                                           \
   20606     c2 += (*zIn++);                                                   \
   20607     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   20608   }                                                                   \
   20609 }
   20610 
   20611 /*
   20612 ** Translate a single UTF-8 character.  Return the unicode value.
   20613 **
   20614 ** During translation, assume that the byte that zTerm points
   20615 ** is a 0x00.
   20616 **
   20617 ** Write a pointer to the next unread byte back into *pzNext.
   20618 **
   20619 ** Notes On Invalid UTF-8:
   20620 **
   20621 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
   20622 **     be encoded as a multi-byte character.  Any multi-byte character that
   20623 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
   20624 **
   20625 **  *  This routine never allows a UTF16 surrogate value to be encoded.
   20626 **     If a multi-byte character attempts to encode a value between
   20627 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
   20628 **
   20629 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
   20630 **     byte of a character are interpreted as single-byte characters
   20631 **     and rendered as themselves even though they are technically
   20632 **     invalid characters.
   20633 **
   20634 **  *  This routine accepts an infinite number of different UTF8 encodings
   20635 **     for unicode values 0x80 and greater.  It do not change over-length
   20636 **     encodings to 0xfffd as some systems recommend.
   20637 */
   20638 #define READ_UTF8(zIn, zTerm, c)                           \
   20639   c = *(zIn++);                                            \
   20640   if( c>=0xc0 ){                                           \
   20641     c = sqlite3Utf8Trans1[c-0xc0];                         \
   20642     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   20643       c = (c<<6) + (0x3f & *(zIn++));                      \
   20644     }                                                      \
   20645     if( c<0x80                                             \
   20646         || (c&0xFFFFF800)==0xD800                          \
   20647         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   20648   }
   20649 SQLITE_PRIVATE u32 sqlite3Utf8Read(
   20650   const unsigned char *zIn,       /* First byte of UTF-8 character */
   20651   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
   20652 ){
   20653   unsigned int c;
   20654 
   20655   /* Same as READ_UTF8() above but without the zTerm parameter.
   20656   ** For this routine, we assume the UTF8 string is always zero-terminated.
   20657   */
   20658   c = *(zIn++);
   20659   if( c>=0xc0 ){
   20660     c = sqlite3Utf8Trans1[c-0xc0];
   20661     while( (*zIn & 0xc0)==0x80 ){
   20662       c = (c<<6) + (0x3f & *(zIn++));
   20663     }
   20664     if( c<0x80
   20665         || (c&0xFFFFF800)==0xD800
   20666         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
   20667   }
   20668   *pzNext = zIn;
   20669   return c;
   20670 }
   20671 
   20672 
   20673 
   20674 
   20675 /*
   20676 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
   20677 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
   20678 */
   20679 /* #define TRANSLATE_TRACE 1 */
   20680 
   20681 #ifndef SQLITE_OMIT_UTF16
   20682 /*
   20683 ** This routine transforms the internal text encoding used by pMem to
   20684 ** desiredEnc. It is an error if the string is already of the desired
   20685 ** encoding, or if *pMem does not contain a string value.
   20686 */
   20687 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
   20688   int len;                    /* Maximum length of output string in bytes */
   20689   unsigned char *zOut;                  /* Output buffer */
   20690   unsigned char *zIn;                   /* Input iterator */
   20691   unsigned char *zTerm;                 /* End of input */
   20692   unsigned char *z;                     /* Output iterator */
   20693   unsigned int c;
   20694 
   20695   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   20696   assert( pMem->flags&MEM_Str );
   20697   assert( pMem->enc!=desiredEnc );
   20698   assert( pMem->enc!=0 );
   20699   assert( pMem->n>=0 );
   20700 
   20701 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   20702   {
   20703     char zBuf[100];
   20704     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   20705     fprintf(stderr, "INPUT:  %s\n", zBuf);
   20706   }
   20707 #endif
   20708 
   20709   /* If the translation is between UTF-16 little and big endian, then
   20710   ** all that is required is to swap the byte order. This case is handled
   20711   ** differently from the others.
   20712   */
   20713   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
   20714     u8 temp;
   20715     int rc;
   20716     rc = sqlite3VdbeMemMakeWriteable(pMem);
   20717     if( rc!=SQLITE_OK ){
   20718       assert( rc==SQLITE_NOMEM );
   20719       return SQLITE_NOMEM;
   20720     }
   20721     zIn = (u8*)pMem->z;
   20722     zTerm = &zIn[pMem->n&~1];
   20723     while( zIn<zTerm ){
   20724       temp = *zIn;
   20725       *zIn = *(zIn+1);
   20726       zIn++;
   20727       *zIn++ = temp;
   20728     }
   20729     pMem->enc = desiredEnc;
   20730     goto translate_out;
   20731   }
   20732 
   20733   /* Set len to the maximum number of bytes required in the output buffer. */
   20734   if( desiredEnc==SQLITE_UTF8 ){
   20735     /* When converting from UTF-16, the maximum growth results from
   20736     ** translating a 2-byte character to a 4-byte UTF-8 character.
   20737     ** A single byte is required for the output string
   20738     ** nul-terminator.
   20739     */
   20740     pMem->n &= ~1;
   20741     len = pMem->n * 2 + 1;
   20742   }else{
   20743     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
   20744     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
   20745     ** character. Two bytes are required in the output buffer for the
   20746     ** nul-terminator.
   20747     */
   20748     len = pMem->n * 2 + 2;
   20749   }
   20750 
   20751   /* Set zIn to point at the start of the input buffer and zTerm to point 1
   20752   ** byte past the end.
   20753   **
   20754   ** Variable zOut is set to point at the output buffer, space obtained
   20755   ** from sqlite3_malloc().
   20756   */
   20757   zIn = (u8*)pMem->z;
   20758   zTerm = &zIn[pMem->n];
   20759   zOut = sqlite3DbMallocRaw(pMem->db, len);
   20760   if( !zOut ){
   20761     return SQLITE_NOMEM;
   20762   }
   20763   z = zOut;
   20764 
   20765   if( pMem->enc==SQLITE_UTF8 ){
   20766     if( desiredEnc==SQLITE_UTF16LE ){
   20767       /* UTF-8 -> UTF-16 Little-endian */
   20768       while( zIn<zTerm ){
   20769         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   20770         READ_UTF8(zIn, zTerm, c);
   20771         WRITE_UTF16LE(z, c);
   20772       }
   20773     }else{
   20774       assert( desiredEnc==SQLITE_UTF16BE );
   20775       /* UTF-8 -> UTF-16 Big-endian */
   20776       while( zIn<zTerm ){
   20777         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   20778         READ_UTF8(zIn, zTerm, c);
   20779         WRITE_UTF16BE(z, c);
   20780       }
   20781     }
   20782     pMem->n = (int)(z - zOut);
   20783     *z++ = 0;
   20784   }else{
   20785     assert( desiredEnc==SQLITE_UTF8 );
   20786     if( pMem->enc==SQLITE_UTF16LE ){
   20787       /* UTF-16 Little-endian -> UTF-8 */
   20788       while( zIn<zTerm ){
   20789         READ_UTF16LE(zIn, zIn<zTerm, c);
   20790         WRITE_UTF8(z, c);
   20791       }
   20792     }else{
   20793       /* UTF-16 Big-endian -> UTF-8 */
   20794       while( zIn<zTerm ){
   20795         READ_UTF16BE(zIn, zIn<zTerm, c);
   20796         WRITE_UTF8(z, c);
   20797       }
   20798     }
   20799     pMem->n = (int)(z - zOut);
   20800   }
   20801   *z = 0;
   20802   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   20803 
   20804   sqlite3VdbeMemRelease(pMem);
   20805   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
   20806   pMem->enc = desiredEnc;
   20807   pMem->flags |= (MEM_Term|MEM_Dyn);
   20808   pMem->z = (char*)zOut;
   20809   pMem->zMalloc = pMem->z;
   20810 
   20811 translate_out:
   20812 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   20813   {
   20814     char zBuf[100];
   20815     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   20816     fprintf(stderr, "OUTPUT: %s\n", zBuf);
   20817   }
   20818 #endif
   20819   return SQLITE_OK;
   20820 }
   20821 
   20822 /*
   20823 ** This routine checks for a byte-order mark at the beginning of the
   20824 ** UTF-16 string stored in *pMem. If one is present, it is removed and
   20825 ** the encoding of the Mem adjusted. This routine does not do any
   20826 ** byte-swapping, it just sets Mem.enc appropriately.
   20827 **
   20828 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
   20829 ** changed by this function.
   20830 */
   20831 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
   20832   int rc = SQLITE_OK;
   20833   u8 bom = 0;
   20834 
   20835   assert( pMem->n>=0 );
   20836   if( pMem->n>1 ){
   20837     u8 b1 = *(u8 *)pMem->z;
   20838     u8 b2 = *(((u8 *)pMem->z) + 1);
   20839     if( b1==0xFE && b2==0xFF ){
   20840       bom = SQLITE_UTF16BE;
   20841     }
   20842     if( b1==0xFF && b2==0xFE ){
   20843       bom = SQLITE_UTF16LE;
   20844     }
   20845   }
   20846 
   20847   if( bom ){
   20848     rc = sqlite3VdbeMemMakeWriteable(pMem);
   20849     if( rc==SQLITE_OK ){
   20850       pMem->n -= 2;
   20851       memmove(pMem->z, &pMem->z[2], pMem->n);
   20852       pMem->z[pMem->n] = '\0';
   20853       pMem->z[pMem->n+1] = '\0';
   20854       pMem->flags |= MEM_Term;
   20855       pMem->enc = bom;
   20856     }
   20857   }
   20858   return rc;
   20859 }
   20860 #endif /* SQLITE_OMIT_UTF16 */
   20861 
   20862 /*
   20863 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
   20864 ** return the number of unicode characters in pZ up to (but not including)
   20865 ** the first 0x00 byte. If nByte is not less than zero, return the
   20866 ** number of unicode characters in the first nByte of pZ (or up to
   20867 ** the first 0x00, whichever comes first).
   20868 */
   20869 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   20870   int r = 0;
   20871   const u8 *z = (const u8*)zIn;
   20872   const u8 *zTerm;
   20873   if( nByte>=0 ){
   20874     zTerm = &z[nByte];
   20875   }else{
   20876     zTerm = (const u8*)(-1);
   20877   }
   20878   assert( z<=zTerm );
   20879   while( *z!=0 && z<zTerm ){
   20880     SQLITE_SKIP_UTF8(z);
   20881     r++;
   20882   }
   20883   return r;
   20884 }
   20885 
   20886 /* This test function is not currently used by the automated test-suite.
   20887 ** Hence it is only available in debug builds.
   20888 */
   20889 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   20890 /*
   20891 ** Translate UTF-8 to UTF-8.
   20892 **
   20893 ** This has the effect of making sure that the string is well-formed
   20894 ** UTF-8.  Miscoded characters are removed.
   20895 **
   20896 ** The translation is done in-place and aborted if the output
   20897 ** overruns the input.
   20898 */
   20899 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
   20900   unsigned char *zOut = zIn;
   20901   unsigned char *zStart = zIn;
   20902   u32 c;
   20903 
   20904   while( zIn[0] && zOut<=zIn ){
   20905     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
   20906     if( c!=0xfffd ){
   20907       WRITE_UTF8(zOut, c);
   20908     }
   20909   }
   20910   *zOut = 0;
   20911   return (int)(zOut - zStart);
   20912 }
   20913 #endif
   20914 
   20915 #ifndef SQLITE_OMIT_UTF16
   20916 /*
   20917 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
   20918 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
   20919 ** be freed by the calling function.
   20920 **
   20921 ** NULL is returned if there is an allocation error.
   20922 */
   20923 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
   20924   Mem m;
   20925   memset(&m, 0, sizeof(m));
   20926   m.db = db;
   20927   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
   20928   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   20929   if( db->mallocFailed ){
   20930     sqlite3VdbeMemRelease(&m);
   20931     m.z = 0;
   20932   }
   20933   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   20934   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   20935   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
   20936   assert( m.z || db->mallocFailed );
   20937   return m.z;
   20938 }
   20939 
   20940 /*
   20941 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
   20942 ** enc. A pointer to the new string is returned, and the value of *pnOut
   20943 ** is set to the length of the returned string in bytes. The call should
   20944 ** arrange to call sqlite3DbFree() on the returned pointer when it is
   20945 ** no longer required.
   20946 **
   20947 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
   20948 ** flag set.
   20949 */
   20950 #ifdef SQLITE_ENABLE_STAT3
   20951 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
   20952   Mem m;
   20953   memset(&m, 0, sizeof(m));
   20954   m.db = db;
   20955   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
   20956   if( sqlite3VdbeMemTranslate(&m, enc) ){
   20957     assert( db->mallocFailed );
   20958     return 0;
   20959   }
   20960   assert( m.z==m.zMalloc );
   20961   *pnOut = m.n;
   20962   return m.z;
   20963 }
   20964 #endif
   20965 
   20966 /*
   20967 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   20968 ** Return the number of bytes in the first nChar unicode characters
   20969 ** in pZ.  nChar must be non-negative.
   20970 */
   20971 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   20972   int c;
   20973   unsigned char const *z = zIn;
   20974   int n = 0;
   20975 
   20976   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
   20977     while( n<nChar ){
   20978       READ_UTF16BE(z, 1, c);
   20979       n++;
   20980     }
   20981   }else{
   20982     while( n<nChar ){
   20983       READ_UTF16LE(z, 1, c);
   20984       n++;
   20985     }
   20986   }
   20987   return (int)(z-(unsigned char const *)zIn);
   20988 }
   20989 
   20990 #if defined(SQLITE_TEST)
   20991 /*
   20992 ** This routine is called from the TCL test function "translate_selftest".
   20993 ** It checks that the primitives for serializing and deserializing
   20994 ** characters in each encoding are inverses of each other.
   20995 */
   20996 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
   20997   unsigned int i, t;
   20998   unsigned char zBuf[20];
   20999   unsigned char *z;
   21000   int n;
   21001   unsigned int c;
   21002 
   21003   for(i=0; i<0x00110000; i++){
   21004     z = zBuf;
   21005     WRITE_UTF8(z, i);
   21006     n = (int)(z-zBuf);
   21007     assert( n>0 && n<=4 );
   21008     z[0] = 0;
   21009     z = zBuf;
   21010     c = sqlite3Utf8Read(z, (const u8**)&z);
   21011     t = i;
   21012     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
   21013     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
   21014     assert( c==t );
   21015     assert( (z-zBuf)==n );
   21016   }
   21017   for(i=0; i<0x00110000; i++){
   21018     if( i>=0xD800 && i<0xE000 ) continue;
   21019     z = zBuf;
   21020     WRITE_UTF16LE(z, i);
   21021     n = (int)(z-zBuf);
   21022     assert( n>0 && n<=4 );
   21023     z[0] = 0;
   21024     z = zBuf;
   21025     READ_UTF16LE(z, 1, c);
   21026     assert( c==i );
   21027     assert( (z-zBuf)==n );
   21028   }
   21029   for(i=0; i<0x00110000; i++){
   21030     if( i>=0xD800 && i<0xE000 ) continue;
   21031     z = zBuf;
   21032     WRITE_UTF16BE(z, i);
   21033     n = (int)(z-zBuf);
   21034     assert( n>0 && n<=4 );
   21035     z[0] = 0;
   21036     z = zBuf;
   21037     READ_UTF16BE(z, 1, c);
   21038     assert( c==i );
   21039     assert( (z-zBuf)==n );
   21040   }
   21041 }
   21042 #endif /* SQLITE_TEST */
   21043 #endif /* SQLITE_OMIT_UTF16 */
   21044 
   21045 /************** End of utf.c *************************************************/
   21046 /************** Begin file util.c ********************************************/
   21047 /*
   21048 ** 2001 September 15
   21049 **
   21050 ** The author disclaims copyright to this source code.  In place of
   21051 ** a legal notice, here is a blessing:
   21052 **
   21053 **    May you do good and not evil.
   21054 **    May you find forgiveness for yourself and forgive others.
   21055 **    May you share freely, never taking more than you give.
   21056 **
   21057 *************************************************************************
   21058 ** Utility functions used throughout sqlite.
   21059 **
   21060 ** This file contains functions for allocating memory, comparing
   21061 ** strings, and stuff like that.
   21062 **
   21063 */
   21064 /* #include <stdarg.h> */
   21065 #ifdef SQLITE_HAVE_ISNAN
   21066 # include <math.h>
   21067 #endif
   21068 
   21069 /*
   21070 ** Routine needed to support the testcase() macro.
   21071 */
   21072 #ifdef SQLITE_COVERAGE_TEST
   21073 SQLITE_PRIVATE void sqlite3Coverage(int x){
   21074   static unsigned dummy = 0;
   21075   dummy += (unsigned)x;
   21076 }
   21077 #endif
   21078 
   21079 #ifndef SQLITE_OMIT_FLOATING_POINT
   21080 /*
   21081 ** Return true if the floating point value is Not a Number (NaN).
   21082 **
   21083 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
   21084 ** Otherwise, we have our own implementation that works on most systems.
   21085 */
   21086 SQLITE_PRIVATE int sqlite3IsNaN(double x){
   21087   int rc;   /* The value return */
   21088 #if !defined(SQLITE_HAVE_ISNAN)
   21089   /*
   21090   ** Systems that support the isnan() library function should probably
   21091   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
   21092   ** found that many systems do not have a working isnan() function so
   21093   ** this implementation is provided as an alternative.
   21094   **
   21095   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
   21096   ** On the other hand, the use of -ffast-math comes with the following
   21097   ** warning:
   21098   **
   21099   **      This option [-ffast-math] should never be turned on by any
   21100   **      -O option since it can result in incorrect output for programs
   21101   **      which depend on an exact implementation of IEEE or ISO
   21102   **      rules/specifications for math functions.
   21103   **
   21104   ** Under MSVC, this NaN test may fail if compiled with a floating-
   21105   ** point precision mode other than /fp:precise.  From the MSDN
   21106   ** documentation:
   21107   **
   21108   **      The compiler [with /fp:precise] will properly handle comparisons
   21109   **      involving NaN. For example, x != x evaluates to true if x is NaN
   21110   **      ...
   21111   */
   21112 #ifdef __FAST_MATH__
   21113 # error SQLite will not work correctly with the -ffast-math option of GCC.
   21114 #endif
   21115   volatile double y = x;
   21116   volatile double z = y;
   21117   rc = (y!=z);
   21118 #else  /* if defined(SQLITE_HAVE_ISNAN) */
   21119   rc = isnan(x);
   21120 #endif /* SQLITE_HAVE_ISNAN */
   21121   testcase( rc );
   21122   return rc;
   21123 }
   21124 #endif /* SQLITE_OMIT_FLOATING_POINT */
   21125 
   21126 /*
   21127 ** Compute a string length that is limited to what can be stored in
   21128 ** lower 30 bits of a 32-bit signed integer.
   21129 **
   21130 ** The value returned will never be negative.  Nor will it ever be greater
   21131 ** than the actual length of the string.  For very long strings (greater
   21132 ** than 1GiB) the value returned might be less than the true string length.
   21133 */
   21134 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
   21135   const char *z2 = z;
   21136   if( z==0 ) return 0;
   21137   while( *z2 ){ z2++; }
   21138   return 0x3fffffff & (int)(z2 - z);
   21139 }
   21140 
   21141 /*
   21142 ** Set the most recent error code and error string for the sqlite
   21143 ** handle "db". The error code is set to "err_code".
   21144 **
   21145 ** If it is not NULL, string zFormat specifies the format of the
   21146 ** error string in the style of the printf functions: The following
   21147 ** format characters are allowed:
   21148 **
   21149 **      %s      Insert a string
   21150 **      %z      A string that should be freed after use
   21151 **      %d      Insert an integer
   21152 **      %T      Insert a token
   21153 **      %S      Insert the first element of a SrcList
   21154 **
   21155 ** zFormat and any string tokens that follow it are assumed to be
   21156 ** encoded in UTF-8.
   21157 **
   21158 ** To clear the most recent error for sqlite handle "db", sqlite3Error
   21159 ** should be called with err_code set to SQLITE_OK and zFormat set
   21160 ** to NULL.
   21161 */
   21162 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
   21163   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
   21164     db->errCode = err_code;
   21165     if( zFormat ){
   21166       char *z;
   21167       va_list ap;
   21168       va_start(ap, zFormat);
   21169       z = sqlite3VMPrintf(db, zFormat, ap);
   21170       va_end(ap);
   21171       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
   21172     }else{
   21173       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
   21174     }
   21175   }
   21176 }
   21177 
   21178 /*
   21179 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
   21180 ** The following formatting characters are allowed:
   21181 **
   21182 **      %s      Insert a string
   21183 **      %z      A string that should be freed after use
   21184 **      %d      Insert an integer
   21185 **      %T      Insert a token
   21186 **      %S      Insert the first element of a SrcList
   21187 **
   21188 ** This function should be used to report any error that occurs whilst
   21189 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
   21190 ** last thing the sqlite3_prepare() function does is copy the error
   21191 ** stored by this function into the database handle using sqlite3Error().
   21192 ** Function sqlite3Error() should be used during statement execution
   21193 ** (sqlite3_step() etc.).
   21194 */
   21195 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   21196   char *zMsg;
   21197   va_list ap;
   21198   sqlite3 *db = pParse->db;
   21199   va_start(ap, zFormat);
   21200   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   21201   va_end(ap);
   21202   if( db->suppressErr ){
   21203     sqlite3DbFree(db, zMsg);
   21204   }else{
   21205     pParse->nErr++;
   21206     sqlite3DbFree(db, pParse->zErrMsg);
   21207     pParse->zErrMsg = zMsg;
   21208     pParse->rc = SQLITE_ERROR;
   21209   }
   21210 }
   21211 
   21212 /*
   21213 ** Convert an SQL-style quoted string into a normal string by removing
   21214 ** the quote characters.  The conversion is done in-place.  If the
   21215 ** input does not begin with a quote character, then this routine
   21216 ** is a no-op.
   21217 **
   21218 ** The input string must be zero-terminated.  A new zero-terminator
   21219 ** is added to the dequoted string.
   21220 **
   21221 ** The return value is -1 if no dequoting occurs or the length of the
   21222 ** dequoted string, exclusive of the zero terminator, if dequoting does
   21223 ** occur.
   21224 **
   21225 ** 2002-Feb-14: This routine is extended to remove MS-Access style
   21226 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
   21227 ** "a-b-c".
   21228 */
   21229 SQLITE_PRIVATE int sqlite3Dequote(char *z){
   21230   char quote;
   21231   int i, j;
   21232   if( z==0 ) return -1;
   21233   quote = z[0];
   21234   switch( quote ){
   21235     case '\'':  break;
   21236     case '"':   break;
   21237     case '`':   break;                /* For MySQL compatibility */
   21238     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
   21239     default:    return -1;
   21240   }
   21241   for(i=1, j=0; ALWAYS(z[i]); i++){
   21242     if( z[i]==quote ){
   21243       if( z[i+1]==quote ){
   21244         z[j++] = quote;
   21245         i++;
   21246       }else{
   21247         break;
   21248       }
   21249     }else{
   21250       z[j++] = z[i];
   21251     }
   21252   }
   21253   z[j] = 0;
   21254   return j;
   21255 }
   21256 
   21257 /* Convenient short-hand */
   21258 #define UpperToLower sqlite3UpperToLower
   21259 
   21260 /*
   21261 ** Some systems have stricmp().  Others have strcasecmp().  Because
   21262 ** there is no consistency, we will define our own.
   21263 **
   21264 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
   21265 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
   21266 ** the contents of two buffers containing UTF-8 strings in a
   21267 ** case-independent fashion, using the same definition of "case
   21268 ** independence" that SQLite uses internally when comparing identifiers.
   21269 */
   21270 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
   21271   register unsigned char *a, *b;
   21272   a = (unsigned char *)zLeft;
   21273   b = (unsigned char *)zRight;
   21274   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   21275   return UpperToLower[*a] - UpperToLower[*b];
   21276 }
   21277 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
   21278   register unsigned char *a, *b;
   21279   a = (unsigned char *)zLeft;
   21280   b = (unsigned char *)zRight;
   21281   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   21282   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
   21283 }
   21284 
   21285 /*
   21286 ** The string z[] is an text representation of a real number.
   21287 ** Convert this string to a double and write it into *pResult.
   21288 **
   21289 ** The string z[] is length bytes in length (bytes, not characters) and
   21290 ** uses the encoding enc.  The string is not necessarily zero-terminated.
   21291 **
   21292 ** Return TRUE if the result is a valid real number (or integer) and FALSE
   21293 ** if the string is empty or contains extraneous text.  Valid numbers
   21294 ** are in one of these formats:
   21295 **
   21296 **    [+-]digits[E[+-]digits]
   21297 **    [+-]digits.[digits][E[+-]digits]
   21298 **    [+-].digits[E[+-]digits]
   21299 **
   21300 ** Leading and trailing whitespace is ignored for the purpose of determining
   21301 ** validity.
   21302 **
   21303 ** If some prefix of the input string is a valid number, this routine
   21304 ** returns FALSE but it still converts the prefix and writes the result
   21305 ** into *pResult.
   21306 */
   21307 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
   21308 #ifndef SQLITE_OMIT_FLOATING_POINT
   21309   int incr = (enc==SQLITE_UTF8?1:2);
   21310   const char *zEnd = z + length;
   21311   /* sign * significand * (10 ^ (esign * exponent)) */
   21312   int sign = 1;    /* sign of significand */
   21313   i64 s = 0;       /* significand */
   21314   int d = 0;       /* adjust exponent for shifting decimal point */
   21315   int esign = 1;   /* sign of exponent */
   21316   int e = 0;       /* exponent */
   21317   int eValid = 1;  /* True exponent is either not used or is well-formed */
   21318   double result;
   21319   int nDigits = 0;
   21320 
   21321   *pResult = 0.0;   /* Default return value, in case of an error */
   21322 
   21323   if( enc==SQLITE_UTF16BE ) z++;
   21324 
   21325   /* skip leading spaces */
   21326   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   21327   if( z>=zEnd ) return 0;
   21328 
   21329   /* get sign of significand */
   21330   if( *z=='-' ){
   21331     sign = -1;
   21332     z+=incr;
   21333   }else if( *z=='+' ){
   21334     z+=incr;
   21335   }
   21336 
   21337   /* skip leading zeroes */
   21338   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
   21339 
   21340   /* copy max significant digits to significand */
   21341   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   21342     s = s*10 + (*z - '0');
   21343     z+=incr, nDigits++;
   21344   }
   21345 
   21346   /* skip non-significant significand digits
   21347   ** (increase exponent by d to shift decimal left) */
   21348   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
   21349   if( z>=zEnd ) goto do_atof_calc;
   21350 
   21351   /* if decimal point is present */
   21352   if( *z=='.' ){
   21353     z+=incr;
   21354     /* copy digits from after decimal to significand
   21355     ** (decrease exponent by d to shift decimal right) */
   21356     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   21357       s = s*10 + (*z - '0');
   21358       z+=incr, nDigits++, d--;
   21359     }
   21360     /* skip non-significant digits */
   21361     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
   21362   }
   21363   if( z>=zEnd ) goto do_atof_calc;
   21364 
   21365   /* if exponent is present */
   21366   if( *z=='e' || *z=='E' ){
   21367     z+=incr;
   21368     eValid = 0;
   21369     if( z>=zEnd ) goto do_atof_calc;
   21370     /* get sign of exponent */
   21371     if( *z=='-' ){
   21372       esign = -1;
   21373       z+=incr;
   21374     }else if( *z=='+' ){
   21375       z+=incr;
   21376     }
   21377     /* copy digits to exponent */
   21378     while( z<zEnd && sqlite3Isdigit(*z) ){
   21379       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
   21380       z+=incr;
   21381       eValid = 1;
   21382     }
   21383   }
   21384 
   21385   /* skip trailing spaces */
   21386   if( nDigits && eValid ){
   21387     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   21388   }
   21389 
   21390 do_atof_calc:
   21391   /* adjust exponent by d, and update sign */
   21392   e = (e*esign) + d;
   21393   if( e<0 ) {
   21394     esign = -1;
   21395     e *= -1;
   21396   } else {
   21397     esign = 1;
   21398   }
   21399 
   21400   /* if 0 significand */
   21401   if( !s ) {
   21402     /* In the IEEE 754 standard, zero is signed.
   21403     ** Add the sign if we've seen at least one digit */
   21404     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
   21405   } else {
   21406     /* attempt to reduce exponent */
   21407     if( esign>0 ){
   21408       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
   21409     }else{
   21410       while( !(s%10) && e>0 ) e--,s/=10;
   21411     }
   21412 
   21413     /* adjust the sign of significand */
   21414     s = sign<0 ? -s : s;
   21415 
   21416     /* if exponent, scale significand as appropriate
   21417     ** and store in result. */
   21418     if( e ){
   21419       double scale = 1.0;
   21420       /* attempt to handle extremely small/large numbers better */
   21421       if( e>307 && e<342 ){
   21422         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
   21423         if( esign<0 ){
   21424           result = s / scale;
   21425           result /= 1.0e+308;
   21426         }else{
   21427           result = s * scale;
   21428           result *= 1.0e+308;
   21429         }
   21430       }else if( e>=342 ){
   21431         if( esign<0 ){
   21432           result = 0.0*s;
   21433         }else{
   21434           result = 1e308*1e308*s;  /* Infinity */
   21435         }
   21436       }else{
   21437         /* 1.0e+22 is the largest power of 10 than can be
   21438         ** represented exactly. */
   21439         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
   21440         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
   21441         if( esign<0 ){
   21442           result = s / scale;
   21443         }else{
   21444           result = s * scale;
   21445         }
   21446       }
   21447     } else {
   21448       result = (double)s;
   21449     }
   21450   }
   21451 
   21452   /* store the result */
   21453   *pResult = result;
   21454 
   21455   /* return true if number and no extra non-whitespace chracters after */
   21456   return z>=zEnd && nDigits>0 && eValid;
   21457 #else
   21458   return !sqlite3Atoi64(z, pResult, length, enc);
   21459 #endif /* SQLITE_OMIT_FLOATING_POINT */
   21460 }
   21461 
   21462 /*
   21463 ** Compare the 19-character string zNum against the text representation
   21464 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
   21465 ** if zNum is less than, equal to, or greater than the string.
   21466 ** Note that zNum must contain exactly 19 characters.
   21467 **
   21468 ** Unlike memcmp() this routine is guaranteed to return the difference
   21469 ** in the values of the last digit if the only difference is in the
   21470 ** last digit.  So, for example,
   21471 **
   21472 **      compare2pow63("9223372036854775800", 1)
   21473 **
   21474 ** will return -8.
   21475 */
   21476 static int compare2pow63(const char *zNum, int incr){
   21477   int c = 0;
   21478   int i;
   21479                     /* 012345678901234567 */
   21480   const char *pow63 = "922337203685477580";
   21481   for(i=0; c==0 && i<18; i++){
   21482     c = (zNum[i*incr]-pow63[i])*10;
   21483   }
   21484   if( c==0 ){
   21485     c = zNum[18*incr] - '8';
   21486     testcase( c==(-1) );
   21487     testcase( c==0 );
   21488     testcase( c==(+1) );
   21489   }
   21490   return c;
   21491 }
   21492 
   21493 
   21494 /*
   21495 ** Convert zNum to a 64-bit signed integer.
   21496 **
   21497 ** If the zNum value is representable as a 64-bit twos-complement
   21498 ** integer, then write that value into *pNum and return 0.
   21499 **
   21500 ** If zNum is exactly 9223372036854665808, return 2.  This special
   21501 ** case is broken out because while 9223372036854665808 cannot be a
   21502 ** signed 64-bit integer, its negative -9223372036854665808 can be.
   21503 **
   21504 ** If zNum is too big for a 64-bit integer and is not
   21505 ** 9223372036854665808 then return 1.
   21506 **
   21507 ** length is the number of bytes in the string (bytes, not characters).
   21508 ** The string is not necessarily zero-terminated.  The encoding is
   21509 ** given by enc.
   21510 */
   21511 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
   21512   int incr = (enc==SQLITE_UTF8?1:2);
   21513   u64 u = 0;
   21514   int neg = 0; /* assume positive */
   21515   int i;
   21516   int c = 0;
   21517   const char *zStart;
   21518   const char *zEnd = zNum + length;
   21519   if( enc==SQLITE_UTF16BE ) zNum++;
   21520   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
   21521   if( zNum<zEnd ){
   21522     if( *zNum=='-' ){
   21523       neg = 1;
   21524       zNum+=incr;
   21525     }else if( *zNum=='+' ){
   21526       zNum+=incr;
   21527     }
   21528   }
   21529   zStart = zNum;
   21530   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
   21531   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
   21532     u = u*10 + c - '0';
   21533   }
   21534   if( u>LARGEST_INT64 ){
   21535     *pNum = SMALLEST_INT64;
   21536   }else if( neg ){
   21537     *pNum = -(i64)u;
   21538   }else{
   21539     *pNum = (i64)u;
   21540   }
   21541   testcase( i==18 );
   21542   testcase( i==19 );
   21543   testcase( i==20 );
   21544   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
   21545     /* zNum is empty or contains non-numeric text or is longer
   21546     ** than 19 digits (thus guaranteeing that it is too large) */
   21547     return 1;
   21548   }else if( i<19*incr ){
   21549     /* Less than 19 digits, so we know that it fits in 64 bits */
   21550     assert( u<=LARGEST_INT64 );
   21551     return 0;
   21552   }else{
   21553     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
   21554     c = compare2pow63(zNum, incr);
   21555     if( c<0 ){
   21556       /* zNum is less than 9223372036854775808 so it fits */
   21557       assert( u<=LARGEST_INT64 );
   21558       return 0;
   21559     }else if( c>0 ){
   21560       /* zNum is greater than 9223372036854775808 so it overflows */
   21561       return 1;
   21562     }else{
   21563       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
   21564       ** special case 2 overflow if positive */
   21565       assert( u-1==LARGEST_INT64 );
   21566       assert( (*pNum)==SMALLEST_INT64 );
   21567       return neg ? 0 : 2;
   21568     }
   21569   }
   21570 }
   21571 
   21572 /*
   21573 ** If zNum represents an integer that will fit in 32-bits, then set
   21574 ** *pValue to that integer and return true.  Otherwise return false.
   21575 **
   21576 ** Any non-numeric characters that following zNum are ignored.
   21577 ** This is different from sqlite3Atoi64() which requires the
   21578 ** input number to be zero-terminated.
   21579 */
   21580 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
   21581   sqlite_int64 v = 0;
   21582   int i, c;
   21583   int neg = 0;
   21584   if( zNum[0]=='-' ){
   21585     neg = 1;
   21586     zNum++;
   21587   }else if( zNum[0]=='+' ){
   21588     zNum++;
   21589   }
   21590   while( zNum[0]=='0' ) zNum++;
   21591   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
   21592     v = v*10 + c;
   21593   }
   21594 
   21595   /* The longest decimal representation of a 32 bit integer is 10 digits:
   21596   **
   21597   **             1234567890
   21598   **     2^31 -> 2147483648
   21599   */
   21600   testcase( i==10 );
   21601   if( i>10 ){
   21602     return 0;
   21603   }
   21604   testcase( v-neg==2147483647 );
   21605   if( v-neg>2147483647 ){
   21606     return 0;
   21607   }
   21608   if( neg ){
   21609     v = -v;
   21610   }
   21611   *pValue = (int)v;
   21612   return 1;
   21613 }
   21614 
   21615 /*
   21616 ** Return a 32-bit integer value extracted from a string.  If the
   21617 ** string is not an integer, just return 0.
   21618 */
   21619 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
   21620   int x = 0;
   21621   if( z ) sqlite3GetInt32(z, &x);
   21622   return x;
   21623 }
   21624 
   21625 /*
   21626 ** The variable-length integer encoding is as follows:
   21627 **
   21628 ** KEY:
   21629 **         A = 0xxxxxxx    7 bits of data and one flag bit
   21630 **         B = 1xxxxxxx    7 bits of data and one flag bit
   21631 **         C = xxxxxxxx    8 bits of data
   21632 **
   21633 **  7 bits - A
   21634 ** 14 bits - BA
   21635 ** 21 bits - BBA
   21636 ** 28 bits - BBBA
   21637 ** 35 bits - BBBBA
   21638 ** 42 bits - BBBBBA
   21639 ** 49 bits - BBBBBBA
   21640 ** 56 bits - BBBBBBBA
   21641 ** 64 bits - BBBBBBBBC
   21642 */
   21643 
   21644 /*
   21645 ** Write a 64-bit variable-length integer to memory starting at p[0].
   21646 ** The length of data write will be between 1 and 9 bytes.  The number
   21647 ** of bytes written is returned.
   21648 **
   21649 ** A variable-length integer consists of the lower 7 bits of each byte
   21650 ** for all bytes that have the 8th bit set and one byte with the 8th
   21651 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   21652 ** 8 bits and is the last byte.
   21653 */
   21654 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
   21655   int i, j, n;
   21656   u8 buf[10];
   21657   if( v & (((u64)0xff000000)<<32) ){
   21658     p[8] = (u8)v;
   21659     v >>= 8;
   21660     for(i=7; i>=0; i--){
   21661       p[i] = (u8)((v & 0x7f) | 0x80);
   21662       v >>= 7;
   21663     }
   21664     return 9;
   21665   }
   21666   n = 0;
   21667   do{
   21668     buf[n++] = (u8)((v & 0x7f) | 0x80);
   21669     v >>= 7;
   21670   }while( v!=0 );
   21671   buf[0] &= 0x7f;
   21672   assert( n<=9 );
   21673   for(i=0, j=n-1; j>=0; j--, i++){
   21674     p[i] = buf[j];
   21675   }
   21676   return n;
   21677 }
   21678 
   21679 /*
   21680 ** This routine is a faster version of sqlite3PutVarint() that only
   21681 ** works for 32-bit positive integers and which is optimized for
   21682 ** the common case of small integers.  A MACRO version, putVarint32,
   21683 ** is provided which inlines the single-byte case.  All code should use
   21684 ** the MACRO version as this function assumes the single-byte case has
   21685 ** already been handled.
   21686 */
   21687 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
   21688 #ifndef putVarint32
   21689   if( (v & ~0x7f)==0 ){
   21690     p[0] = v;
   21691     return 1;
   21692   }
   21693 #endif
   21694   if( (v & ~0x3fff)==0 ){
   21695     p[0] = (u8)((v>>7) | 0x80);
   21696     p[1] = (u8)(v & 0x7f);
   21697     return 2;
   21698   }
   21699   return sqlite3PutVarint(p, v);
   21700 }
   21701 
   21702 /*
   21703 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
   21704 ** are defined here rather than simply putting the constant expressions
   21705 ** inline in order to work around bugs in the RVT compiler.
   21706 **
   21707 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
   21708 **
   21709 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
   21710 */
   21711 #define SLOT_2_0     0x001fc07f
   21712 #define SLOT_4_2_0   0xf01fc07f
   21713 
   21714 
   21715 /*
   21716 ** Read a 64-bit variable-length integer from memory starting at p[0].
   21717 ** Return the number of bytes read.  The value is stored in *v.
   21718 */
   21719 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
   21720   u32 a,b,s;
   21721 
   21722   a = *p;
   21723   /* a: p0 (unmasked) */
   21724   if (!(a&0x80))
   21725   {
   21726     *v = a;
   21727     return 1;
   21728   }
   21729 
   21730   p++;
   21731   b = *p;
   21732   /* b: p1 (unmasked) */
   21733   if (!(b&0x80))
   21734   {
   21735     a &= 0x7f;
   21736     a = a<<7;
   21737     a |= b;
   21738     *v = a;
   21739     return 2;
   21740   }
   21741 
   21742   /* Verify that constants are precomputed correctly */
   21743   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
   21744   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
   21745 
   21746   p++;
   21747   a = a<<14;
   21748   a |= *p;
   21749   /* a: p0<<14 | p2 (unmasked) */
   21750   if (!(a&0x80))
   21751   {
   21752     a &= SLOT_2_0;
   21753     b &= 0x7f;
   21754     b = b<<7;
   21755     a |= b;
   21756     *v = a;
   21757     return 3;
   21758   }
   21759 
   21760   /* CSE1 from below */
   21761   a &= SLOT_2_0;
   21762   p++;
   21763   b = b<<14;
   21764   b |= *p;
   21765   /* b: p1<<14 | p3 (unmasked) */
   21766   if (!(b&0x80))
   21767   {
   21768     b &= SLOT_2_0;
   21769     /* moved CSE1 up */
   21770     /* a &= (0x7f<<14)|(0x7f); */
   21771     a = a<<7;
   21772     a |= b;
   21773     *v = a;
   21774     return 4;
   21775   }
   21776 
   21777   /* a: p0<<14 | p2 (masked) */
   21778   /* b: p1<<14 | p3 (unmasked) */
   21779   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   21780   /* moved CSE1 up */
   21781   /* a &= (0x7f<<14)|(0x7f); */
   21782   b &= SLOT_2_0;
   21783   s = a;
   21784   /* s: p0<<14 | p2 (masked) */
   21785 
   21786   p++;
   21787   a = a<<14;
   21788   a |= *p;
   21789   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   21790   if (!(a&0x80))
   21791   {
   21792     /* we can skip these cause they were (effectively) done above in calc'ing s */
   21793     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   21794     /* b &= (0x7f<<14)|(0x7f); */
   21795     b = b<<7;
   21796     a |= b;
   21797     s = s>>18;
   21798     *v = ((u64)s)<<32 | a;
   21799     return 5;
   21800   }
   21801 
   21802   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   21803   s = s<<7;
   21804   s |= b;
   21805   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   21806 
   21807   p++;
   21808   b = b<<14;
   21809   b |= *p;
   21810   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   21811   if (!(b&0x80))
   21812   {
   21813     /* we can skip this cause it was (effectively) done above in calc'ing s */
   21814     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   21815     a &= SLOT_2_0;
   21816     a = a<<7;
   21817     a |= b;
   21818     s = s>>18;
   21819     *v = ((u64)s)<<32 | a;
   21820     return 6;
   21821   }
   21822 
   21823   p++;
   21824   a = a<<14;
   21825   a |= *p;
   21826   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   21827   if (!(a&0x80))
   21828   {
   21829     a &= SLOT_4_2_0;
   21830     b &= SLOT_2_0;
   21831     b = b<<7;
   21832     a |= b;
   21833     s = s>>11;
   21834     *v = ((u64)s)<<32 | a;
   21835     return 7;
   21836   }
   21837 
   21838   /* CSE2 from below */
   21839   a &= SLOT_2_0;
   21840   p++;
   21841   b = b<<14;
   21842   b |= *p;
   21843   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   21844   if (!(b&0x80))
   21845   {
   21846     b &= SLOT_4_2_0;
   21847     /* moved CSE2 up */
   21848     /* a &= (0x7f<<14)|(0x7f); */
   21849     a = a<<7;
   21850     a |= b;
   21851     s = s>>4;
   21852     *v = ((u64)s)<<32 | a;
   21853     return 8;
   21854   }
   21855 
   21856   p++;
   21857   a = a<<15;
   21858   a |= *p;
   21859   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   21860 
   21861   /* moved CSE2 up */
   21862   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   21863   b &= SLOT_2_0;
   21864   b = b<<8;
   21865   a |= b;
   21866 
   21867   s = s<<4;
   21868   b = p[-4];
   21869   b &= 0x7f;
   21870   b = b>>3;
   21871   s |= b;
   21872 
   21873   *v = ((u64)s)<<32 | a;
   21874 
   21875   return 9;
   21876 }
   21877 
   21878 /*
   21879 ** Read a 32-bit variable-length integer from memory starting at p[0].
   21880 ** Return the number of bytes read.  The value is stored in *v.
   21881 **
   21882 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
   21883 ** integer, then set *v to 0xffffffff.
   21884 **
   21885 ** A MACRO version, getVarint32, is provided which inlines the
   21886 ** single-byte case.  All code should use the MACRO version as
   21887 ** this function assumes the single-byte case has already been handled.
   21888 */
   21889 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
   21890   u32 a,b;
   21891 
   21892   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
   21893   ** by the getVarin32() macro */
   21894   a = *p;
   21895   /* a: p0 (unmasked) */
   21896 #ifndef getVarint32
   21897   if (!(a&0x80))
   21898   {
   21899     /* Values between 0 and 127 */
   21900     *v = a;
   21901     return 1;
   21902   }
   21903 #endif
   21904 
   21905   /* The 2-byte case */
   21906   p++;
   21907   b = *p;
   21908   /* b: p1 (unmasked) */
   21909   if (!(b&0x80))
   21910   {
   21911     /* Values between 128 and 16383 */
   21912     a &= 0x7f;
   21913     a = a<<7;
   21914     *v = a | b;
   21915     return 2;
   21916   }
   21917 
   21918   /* The 3-byte case */
   21919   p++;
   21920   a = a<<14;
   21921   a |= *p;
   21922   /* a: p0<<14 | p2 (unmasked) */
   21923   if (!(a&0x80))
   21924   {
   21925     /* Values between 16384 and 2097151 */
   21926     a &= (0x7f<<14)|(0x7f);
   21927     b &= 0x7f;
   21928     b = b<<7;
   21929     *v = a | b;
   21930     return 3;
   21931   }
   21932 
   21933   /* A 32-bit varint is used to store size information in btrees.
   21934   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   21935   ** A 3-byte varint is sufficient, for example, to record the size
   21936   ** of a 1048569-byte BLOB or string.
   21937   **
   21938   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   21939   ** rare larger cases can be handled by the slower 64-bit varint
   21940   ** routine.
   21941   */
   21942 #if 1
   21943   {
   21944     u64 v64;
   21945     u8 n;
   21946 
   21947     p -= 2;
   21948     n = sqlite3GetVarint(p, &v64);
   21949     assert( n>3 && n<=9 );
   21950     if( (v64 & SQLITE_MAX_U32)!=v64 ){
   21951       *v = 0xffffffff;
   21952     }else{
   21953       *v = (u32)v64;
   21954     }
   21955     return n;
   21956   }
   21957 
   21958 #else
   21959   /* For following code (kept for historical record only) shows an
   21960   ** unrolling for the 3- and 4-byte varint cases.  This code is
   21961   ** slightly faster, but it is also larger and much harder to test.
   21962   */
   21963   p++;
   21964   b = b<<14;
   21965   b |= *p;
   21966   /* b: p1<<14 | p3 (unmasked) */
   21967   if (!(b&0x80))
   21968   {
   21969     /* Values between 2097152 and 268435455 */
   21970     b &= (0x7f<<14)|(0x7f);
   21971     a &= (0x7f<<14)|(0x7f);
   21972     a = a<<7;
   21973     *v = a | b;
   21974     return 4;
   21975   }
   21976 
   21977   p++;
   21978   a = a<<14;
   21979   a |= *p;
   21980   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   21981   if (!(a&0x80))
   21982   {
   21983     /* Values  between 268435456 and 34359738367 */
   21984     a &= SLOT_4_2_0;
   21985     b &= SLOT_4_2_0;
   21986     b = b<<7;
   21987     *v = a | b;
   21988     return 5;
   21989   }
   21990 
   21991   /* We can only reach this point when reading a corrupt database
   21992   ** file.  In that case we are not in any hurry.  Use the (relatively
   21993   ** slow) general-purpose sqlite3GetVarint() routine to extract the
   21994   ** value. */
   21995   {
   21996     u64 v64;
   21997     u8 n;
   21998 
   21999     p -= 4;
   22000     n = sqlite3GetVarint(p, &v64);
   22001     assert( n>5 && n<=9 );
   22002     *v = (u32)v64;
   22003     return n;
   22004   }
   22005 #endif
   22006 }
   22007 
   22008 /*
   22009 ** Return the number of bytes that will be needed to store the given
   22010 ** 64-bit integer.
   22011 */
   22012 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
   22013   int i = 0;
   22014   do{
   22015     i++;
   22016     v >>= 7;
   22017   }while( v!=0 && ALWAYS(i<9) );
   22018   return i;
   22019 }
   22020 
   22021 
   22022 /*
   22023 ** Read or write a four-byte big-endian integer value.
   22024 */
   22025 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
   22026   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
   22027 }
   22028 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
   22029   p[0] = (u8)(v>>24);
   22030   p[1] = (u8)(v>>16);
   22031   p[2] = (u8)(v>>8);
   22032   p[3] = (u8)v;
   22033 }
   22034 
   22035 
   22036 
   22037 /*
   22038 ** Translate a single byte of Hex into an integer.
   22039 ** This routine only works if h really is a valid hexadecimal
   22040 ** character:  0..9a..fA..F
   22041 */
   22042 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
   22043   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
   22044 #ifdef SQLITE_ASCII
   22045   h += 9*(1&(h>>6));
   22046 #endif
   22047 #ifdef SQLITE_EBCDIC
   22048   h += 9*(1&~(h>>4));
   22049 #endif
   22050   return (u8)(h & 0xf);
   22051 }
   22052 
   22053 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   22054 /*
   22055 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
   22056 ** value.  Return a pointer to its binary value.  Space to hold the
   22057 ** binary value has been obtained from malloc and must be freed by
   22058 ** the calling routine.
   22059 */
   22060 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   22061   char *zBlob;
   22062   int i;
   22063 
   22064   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
   22065   n--;
   22066   if( zBlob ){
   22067     for(i=0; i<n; i+=2){
   22068       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
   22069     }
   22070     zBlob[i/2] = 0;
   22071   }
   22072   return zBlob;
   22073 }
   22074 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   22075 
   22076 /*
   22077 ** Log an error that is an API call on a connection pointer that should
   22078 ** not have been used.  The "type" of connection pointer is given as the
   22079 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
   22080 */
   22081 static void logBadConnection(const char *zType){
   22082   sqlite3_log(SQLITE_MISUSE,
   22083      "API call with %s database connection pointer",
   22084      zType
   22085   );
   22086 }
   22087 
   22088 /*
   22089 ** Check to make sure we have a valid db pointer.  This test is not
   22090 ** foolproof but it does provide some measure of protection against
   22091 ** misuse of the interface such as passing in db pointers that are
   22092 ** NULL or which have been previously closed.  If this routine returns
   22093 ** 1 it means that the db pointer is valid and 0 if it should not be
   22094 ** dereferenced for any reason.  The calling function should invoke
   22095 ** SQLITE_MISUSE immediately.
   22096 **
   22097 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
   22098 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
   22099 ** open properly and is not fit for general use but which can be
   22100 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
   22101 */
   22102 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   22103   u32 magic;
   22104   if( db==0 ){
   22105     logBadConnection("NULL");
   22106     return 0;
   22107   }
   22108   magic = db->magic;
   22109   if( magic!=SQLITE_MAGIC_OPEN ){
   22110     if( sqlite3SafetyCheckSickOrOk(db) ){
   22111       testcase( sqlite3GlobalConfig.xLog!=0 );
   22112       logBadConnection("unopened");
   22113     }
   22114     return 0;
   22115   }else{
   22116     return 1;
   22117   }
   22118 }
   22119 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
   22120   u32 magic;
   22121   magic = db->magic;
   22122   if( magic!=SQLITE_MAGIC_SICK &&
   22123       magic!=SQLITE_MAGIC_OPEN &&
   22124       magic!=SQLITE_MAGIC_BUSY ){
   22125     testcase( sqlite3GlobalConfig.xLog!=0 );
   22126     logBadConnection("invalid");
   22127     return 0;
   22128   }else{
   22129     return 1;
   22130   }
   22131 }
   22132 
   22133 /*
   22134 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
   22135 ** the other 64-bit signed integer at *pA and store the result in *pA.
   22136 ** Return 0 on success.  Or if the operation would have resulted in an
   22137 ** overflow, leave *pA unchanged and return 1.
   22138 */
   22139 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
   22140   i64 iA = *pA;
   22141   testcase( iA==0 ); testcase( iA==1 );
   22142   testcase( iB==-1 ); testcase( iB==0 );
   22143   if( iB>=0 ){
   22144     testcase( iA>0 && LARGEST_INT64 - iA == iB );
   22145     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
   22146     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
   22147     *pA += iB;
   22148   }else{
   22149     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
   22150     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
   22151     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
   22152     *pA += iB;
   22153   }
   22154   return 0;
   22155 }
   22156 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
   22157   testcase( iB==SMALLEST_INT64+1 );
   22158   if( iB==SMALLEST_INT64 ){
   22159     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
   22160     if( (*pA)>=0 ) return 1;
   22161     *pA -= iB;
   22162     return 0;
   22163   }else{
   22164     return sqlite3AddInt64(pA, -iB);
   22165   }
   22166 }
   22167 #define TWOPOWER32 (((i64)1)<<32)
   22168 #define TWOPOWER31 (((i64)1)<<31)
   22169 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
   22170   i64 iA = *pA;
   22171   i64 iA1, iA0, iB1, iB0, r;
   22172 
   22173   iA1 = iA/TWOPOWER32;
   22174   iA0 = iA % TWOPOWER32;
   22175   iB1 = iB/TWOPOWER32;
   22176   iB0 = iB % TWOPOWER32;
   22177   if( iA1*iB1 != 0 ) return 1;
   22178   assert( iA1*iB0==0 || iA0*iB1==0 );
   22179   r = iA1*iB0 + iA0*iB1;
   22180   testcase( r==(-TWOPOWER31)-1 );
   22181   testcase( r==(-TWOPOWER31) );
   22182   testcase( r==TWOPOWER31 );
   22183   testcase( r==TWOPOWER31-1 );
   22184   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
   22185   r *= TWOPOWER32;
   22186   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
   22187   *pA = r;
   22188   return 0;
   22189 }
   22190 
   22191 /*
   22192 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
   22193 ** if the integer has a value of -2147483648, return +2147483647
   22194 */
   22195 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
   22196   if( x>=0 ) return x;
   22197   if( x==(int)0x80000000 ) return 0x7fffffff;
   22198   return -x;
   22199 }
   22200 
   22201 #ifdef SQLITE_ENABLE_8_3_NAMES
   22202 /*
   22203 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
   22204 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
   22205 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
   22206 ** three characters, then shorten the suffix on z[] to be the last three
   22207 ** characters of the original suffix.
   22208 **
   22209 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
   22210 ** do the suffix shortening regardless of URI parameter.
   22211 **
   22212 ** Examples:
   22213 **
   22214 **     test.db-journal    =>   test.nal
   22215 **     test.db-wal        =>   test.wal
   22216 **     test.db-shm        =>   test.shm
   22217 **     test.db-mj7f3319fa =>   test.9fa
   22218 */
   22219 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
   22220 #if SQLITE_ENABLE_8_3_NAMES<2
   22221   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
   22222 #endif
   22223   {
   22224     int i, sz;
   22225     sz = sqlite3Strlen30(z);
   22226     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
   22227     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
   22228   }
   22229 }
   22230 #endif
   22231 
   22232 /************** End of util.c ************************************************/
   22233 /************** Begin file hash.c ********************************************/
   22234 /*
   22235 ** 2001 September 22
   22236 **
   22237 ** The author disclaims copyright to this source code.  In place of
   22238 ** a legal notice, here is a blessing:
   22239 **
   22240 **    May you do good and not evil.
   22241 **    May you find forgiveness for yourself and forgive others.
   22242 **    May you share freely, never taking more than you give.
   22243 **
   22244 *************************************************************************
   22245 ** This is the implementation of generic hash-tables
   22246 ** used in SQLite.
   22247 */
   22248 /* #include <assert.h> */
   22249 
   22250 /* Turn bulk memory into a hash table object by initializing the
   22251 ** fields of the Hash structure.
   22252 **
   22253 ** "pNew" is a pointer to the hash table that is to be initialized.
   22254 */
   22255 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
   22256   assert( pNew!=0 );
   22257   pNew->first = 0;
   22258   pNew->count = 0;
   22259   pNew->htsize = 0;
   22260   pNew->ht = 0;
   22261 }
   22262 
   22263 /* Remove all entries from a hash table.  Reclaim all memory.
   22264 ** Call this routine to delete a hash table or to reset a hash table
   22265 ** to the empty state.
   22266 */
   22267 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
   22268   HashElem *elem;         /* For looping over all elements of the table */
   22269 
   22270   assert( pH!=0 );
   22271   elem = pH->first;
   22272   pH->first = 0;
   22273   sqlite3_free(pH->ht);
   22274   pH->ht = 0;
   22275   pH->htsize = 0;
   22276   while( elem ){
   22277     HashElem *next_elem = elem->next;
   22278     sqlite3_free(elem);
   22279     elem = next_elem;
   22280   }
   22281   pH->count = 0;
   22282 }
   22283 
   22284 /*
   22285 ** The hashing function.
   22286 */
   22287 static unsigned int strHash(const char *z, int nKey){
   22288   int h = 0;
   22289   assert( nKey>=0 );
   22290   while( nKey > 0  ){
   22291     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
   22292     nKey--;
   22293   }
   22294   return h;
   22295 }
   22296 
   22297 
   22298 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
   22299 ** insert pNew into the pEntry hash bucket.
   22300 */
   22301 static void insertElement(
   22302   Hash *pH,              /* The complete hash table */
   22303   struct _ht *pEntry,    /* The entry into which pNew is inserted */
   22304   HashElem *pNew         /* The element to be inserted */
   22305 ){
   22306   HashElem *pHead;       /* First element already in pEntry */
   22307   if( pEntry ){
   22308     pHead = pEntry->count ? pEntry->chain : 0;
   22309     pEntry->count++;
   22310     pEntry->chain = pNew;
   22311   }else{
   22312     pHead = 0;
   22313   }
   22314   if( pHead ){
   22315     pNew->next = pHead;
   22316     pNew->prev = pHead->prev;
   22317     if( pHead->prev ){ pHead->prev->next = pNew; }
   22318     else             { pH->first = pNew; }
   22319     pHead->prev = pNew;
   22320   }else{
   22321     pNew->next = pH->first;
   22322     if( pH->first ){ pH->first->prev = pNew; }
   22323     pNew->prev = 0;
   22324     pH->first = pNew;
   22325   }
   22326 }
   22327 
   22328 
   22329 /* Resize the hash table so that it cantains "new_size" buckets.
   22330 **
   22331 ** The hash table might fail to resize if sqlite3_malloc() fails or
   22332 ** if the new size is the same as the prior size.
   22333 ** Return TRUE if the resize occurs and false if not.
   22334 */
   22335 static int rehash(Hash *pH, unsigned int new_size){
   22336   struct _ht *new_ht;            /* The new hash table */
   22337   HashElem *elem, *next_elem;    /* For looping over existing elements */
   22338 
   22339 #if SQLITE_MALLOC_SOFT_LIMIT>0
   22340   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
   22341     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
   22342   }
   22343   if( new_size==pH->htsize ) return 0;
   22344 #endif
   22345 
   22346   /* The inability to allocates space for a larger hash table is
   22347   ** a performance hit but it is not a fatal error.  So mark the
   22348   ** allocation as a benign.
   22349   */
   22350   sqlite3BeginBenignMalloc();
   22351   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
   22352   sqlite3EndBenignMalloc();
   22353 
   22354   if( new_ht==0 ) return 0;
   22355   sqlite3_free(pH->ht);
   22356   pH->ht = new_ht;
   22357   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
   22358   memset(new_ht, 0, new_size*sizeof(struct _ht));
   22359   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   22360     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
   22361     next_elem = elem->next;
   22362     insertElement(pH, &new_ht[h], elem);
   22363   }
   22364   return 1;
   22365 }
   22366 
   22367 /* This function (for internal use only) locates an element in an
   22368 ** hash table that matches the given key.  The hash for this key has
   22369 ** already been computed and is passed as the 4th parameter.
   22370 */
   22371 static HashElem *findElementGivenHash(
   22372   const Hash *pH,     /* The pH to be searched */
   22373   const char *pKey,   /* The key we are searching for */
   22374   int nKey,           /* Bytes in key (not counting zero terminator) */
   22375   unsigned int h      /* The hash for this key. */
   22376 ){
   22377   HashElem *elem;                /* Used to loop thru the element list */
   22378   int count;                     /* Number of elements left to test */
   22379 
   22380   if( pH->ht ){
   22381     struct _ht *pEntry = &pH->ht[h];
   22382     elem = pEntry->chain;
   22383     count = pEntry->count;
   22384   }else{
   22385     elem = pH->first;
   22386     count = pH->count;
   22387   }
   22388   while( count-- && ALWAYS(elem) ){
   22389     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
   22390       return elem;
   22391     }
   22392     elem = elem->next;
   22393   }
   22394   return 0;
   22395 }
   22396 
   22397 /* Remove a single entry from the hash table given a pointer to that
   22398 ** element and a hash on the element's key.
   22399 */
   22400 static void removeElementGivenHash(
   22401   Hash *pH,         /* The pH containing "elem" */
   22402   HashElem* elem,   /* The element to be removed from the pH */
   22403   unsigned int h    /* Hash value for the element */
   22404 ){
   22405   struct _ht *pEntry;
   22406   if( elem->prev ){
   22407     elem->prev->next = elem->next;
   22408   }else{
   22409     pH->first = elem->next;
   22410   }
   22411   if( elem->next ){
   22412     elem->next->prev = elem->prev;
   22413   }
   22414   if( pH->ht ){
   22415     pEntry = &pH->ht[h];
   22416     if( pEntry->chain==elem ){
   22417       pEntry->chain = elem->next;
   22418     }
   22419     pEntry->count--;
   22420     assert( pEntry->count>=0 );
   22421   }
   22422   sqlite3_free( elem );
   22423   pH->count--;
   22424   if( pH->count<=0 ){
   22425     assert( pH->first==0 );
   22426     assert( pH->count==0 );
   22427     sqlite3HashClear(pH);
   22428   }
   22429 }
   22430 
   22431 /* Attempt to locate an element of the hash table pH with a key
   22432 ** that matches pKey,nKey.  Return the data for this element if it is
   22433 ** found, or NULL if there is no match.
   22434 */
   22435 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
   22436   HashElem *elem;    /* The element that matches key */
   22437   unsigned int h;    /* A hash on key */
   22438 
   22439   assert( pH!=0 );
   22440   assert( pKey!=0 );
   22441   assert( nKey>=0 );
   22442   if( pH->ht ){
   22443     h = strHash(pKey, nKey) % pH->htsize;
   22444   }else{
   22445     h = 0;
   22446   }
   22447   elem = findElementGivenHash(pH, pKey, nKey, h);
   22448   return elem ? elem->data : 0;
   22449 }
   22450 
   22451 /* Insert an element into the hash table pH.  The key is pKey,nKey
   22452 ** and the data is "data".
   22453 **
   22454 ** If no element exists with a matching key, then a new
   22455 ** element is created and NULL is returned.
   22456 **
   22457 ** If another element already exists with the same key, then the
   22458 ** new data replaces the old data and the old data is returned.
   22459 ** The key is not copied in this instance.  If a malloc fails, then
   22460 ** the new data is returned and the hash table is unchanged.
   22461 **
   22462 ** If the "data" parameter to this function is NULL, then the
   22463 ** element corresponding to "key" is removed from the hash table.
   22464 */
   22465 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
   22466   unsigned int h;       /* the hash of the key modulo hash table size */
   22467   HashElem *elem;       /* Used to loop thru the element list */
   22468   HashElem *new_elem;   /* New element added to the pH */
   22469 
   22470   assert( pH!=0 );
   22471   assert( pKey!=0 );
   22472   assert( nKey>=0 );
   22473   if( pH->htsize ){
   22474     h = strHash(pKey, nKey) % pH->htsize;
   22475   }else{
   22476     h = 0;
   22477   }
   22478   elem = findElementGivenHash(pH,pKey,nKey,h);
   22479   if( elem ){
   22480     void *old_data = elem->data;
   22481     if( data==0 ){
   22482       removeElementGivenHash(pH,elem,h);
   22483     }else{
   22484       elem->data = data;
   22485       elem->pKey = pKey;
   22486       assert(nKey==elem->nKey);
   22487     }
   22488     return old_data;
   22489   }
   22490   if( data==0 ) return 0;
   22491   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
   22492   if( new_elem==0 ) return data;
   22493   new_elem->pKey = pKey;
   22494   new_elem->nKey = nKey;
   22495   new_elem->data = data;
   22496   pH->count++;
   22497   if( pH->count>=10 && pH->count > 2*pH->htsize ){
   22498     if( rehash(pH, pH->count*2) ){
   22499       assert( pH->htsize>0 );
   22500       h = strHash(pKey, nKey) % pH->htsize;
   22501     }
   22502   }
   22503   if( pH->ht ){
   22504     insertElement(pH, &pH->ht[h], new_elem);
   22505   }else{
   22506     insertElement(pH, 0, new_elem);
   22507   }
   22508   return 0;
   22509 }
   22510 
   22511 /************** End of hash.c ************************************************/
   22512 /************** Begin file opcodes.c *****************************************/
   22513 /* Automatically generated.  Do not edit */
   22514 /* See the mkopcodec.awk script for details. */
   22515 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   22516 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
   22517  static const char *const azName[] = { "?",
   22518      /*   1 */ "Goto",
   22519      /*   2 */ "Gosub",
   22520      /*   3 */ "Return",
   22521      /*   4 */ "Yield",
   22522      /*   5 */ "HaltIfNull",
   22523      /*   6 */ "Halt",
   22524      /*   7 */ "Integer",
   22525      /*   8 */ "Int64",
   22526      /*   9 */ "String",
   22527      /*  10 */ "Null",
   22528      /*  11 */ "Blob",
   22529      /*  12 */ "Variable",
   22530      /*  13 */ "Move",
   22531      /*  14 */ "Copy",
   22532      /*  15 */ "SCopy",
   22533      /*  16 */ "ResultRow",
   22534      /*  17 */ "CollSeq",
   22535      /*  18 */ "Function",
   22536      /*  19 */ "Not",
   22537      /*  20 */ "AddImm",
   22538      /*  21 */ "MustBeInt",
   22539      /*  22 */ "RealAffinity",
   22540      /*  23 */ "Permutation",
   22541      /*  24 */ "Compare",
   22542      /*  25 */ "Jump",
   22543      /*  26 */ "Once",
   22544      /*  27 */ "If",
   22545      /*  28 */ "IfNot",
   22546      /*  29 */ "Column",
   22547      /*  30 */ "Affinity",
   22548      /*  31 */ "MakeRecord",
   22549      /*  32 */ "Count",
   22550      /*  33 */ "Savepoint",
   22551      /*  34 */ "AutoCommit",
   22552      /*  35 */ "Transaction",
   22553      /*  36 */ "ReadCookie",
   22554      /*  37 */ "SetCookie",
   22555      /*  38 */ "VerifyCookie",
   22556      /*  39 */ "OpenRead",
   22557      /*  40 */ "OpenWrite",
   22558      /*  41 */ "OpenAutoindex",
   22559      /*  42 */ "OpenEphemeral",
   22560      /*  43 */ "SorterOpen",
   22561      /*  44 */ "OpenPseudo",
   22562      /*  45 */ "Close",
   22563      /*  46 */ "SeekLt",
   22564      /*  47 */ "SeekLe",
   22565      /*  48 */ "SeekGe",
   22566      /*  49 */ "SeekGt",
   22567      /*  50 */ "Seek",
   22568      /*  51 */ "NotFound",
   22569      /*  52 */ "Found",
   22570      /*  53 */ "IsUnique",
   22571      /*  54 */ "NotExists",
   22572      /*  55 */ "Sequence",
   22573      /*  56 */ "NewRowid",
   22574      /*  57 */ "Insert",
   22575      /*  58 */ "InsertInt",
   22576      /*  59 */ "Delete",
   22577      /*  60 */ "ResetCount",
   22578      /*  61 */ "SorterCompare",
   22579      /*  62 */ "SorterData",
   22580      /*  63 */ "RowKey",
   22581      /*  64 */ "RowData",
   22582      /*  65 */ "Rowid",
   22583      /*  66 */ "NullRow",
   22584      /*  67 */ "Last",
   22585      /*  68 */ "Or",
   22586      /*  69 */ "And",
   22587      /*  70 */ "SorterSort",
   22588      /*  71 */ "Sort",
   22589      /*  72 */ "Rewind",
   22590      /*  73 */ "IsNull",
   22591      /*  74 */ "NotNull",
   22592      /*  75 */ "Ne",
   22593      /*  76 */ "Eq",
   22594      /*  77 */ "Gt",
   22595      /*  78 */ "Le",
   22596      /*  79 */ "Lt",
   22597      /*  80 */ "Ge",
   22598      /*  81 */ "SorterNext",
   22599      /*  82 */ "BitAnd",
   22600      /*  83 */ "BitOr",
   22601      /*  84 */ "ShiftLeft",
   22602      /*  85 */ "ShiftRight",
   22603      /*  86 */ "Add",
   22604      /*  87 */ "Subtract",
   22605      /*  88 */ "Multiply",
   22606      /*  89 */ "Divide",
   22607      /*  90 */ "Remainder",
   22608      /*  91 */ "Concat",
   22609      /*  92 */ "Prev",
   22610      /*  93 */ "BitNot",
   22611      /*  94 */ "String8",
   22612      /*  95 */ "Next",
   22613      /*  96 */ "SorterInsert",
   22614      /*  97 */ "IdxInsert",
   22615      /*  98 */ "IdxDelete",
   22616      /*  99 */ "IdxRowid",
   22617      /* 100 */ "IdxLT",
   22618      /* 101 */ "IdxGE",
   22619      /* 102 */ "Destroy",
   22620      /* 103 */ "Clear",
   22621      /* 104 */ "CreateIndex",
   22622      /* 105 */ "CreateTable",
   22623      /* 106 */ "ParseSchema",
   22624      /* 107 */ "LoadAnalysis",
   22625      /* 108 */ "DropTable",
   22626      /* 109 */ "DropIndex",
   22627      /* 110 */ "DropTrigger",
   22628      /* 111 */ "IntegrityCk",
   22629      /* 112 */ "RowSetAdd",
   22630      /* 113 */ "RowSetRead",
   22631      /* 114 */ "RowSetTest",
   22632      /* 115 */ "Program",
   22633      /* 116 */ "Param",
   22634      /* 117 */ "FkCounter",
   22635      /* 118 */ "FkIfZero",
   22636      /* 119 */ "MemMax",
   22637      /* 120 */ "IfPos",
   22638      /* 121 */ "IfNeg",
   22639      /* 122 */ "IfZero",
   22640      /* 123 */ "AggStep",
   22641      /* 124 */ "AggFinal",
   22642      /* 125 */ "Checkpoint",
   22643      /* 126 */ "JournalMode",
   22644      /* 127 */ "Vacuum",
   22645      /* 128 */ "IncrVacuum",
   22646      /* 129 */ "Expire",
   22647      /* 130 */ "Real",
   22648      /* 131 */ "TableLock",
   22649      /* 132 */ "VBegin",
   22650      /* 133 */ "VCreate",
   22651      /* 134 */ "VDestroy",
   22652      /* 135 */ "VOpen",
   22653      /* 136 */ "VFilter",
   22654      /* 137 */ "VColumn",
   22655      /* 138 */ "VNext",
   22656      /* 139 */ "VRename",
   22657      /* 140 */ "VUpdate",
   22658      /* 141 */ "ToText",
   22659      /* 142 */ "ToBlob",
   22660      /* 143 */ "ToNumeric",
   22661      /* 144 */ "ToInt",
   22662      /* 145 */ "ToReal",
   22663      /* 146 */ "Pagecount",
   22664      /* 147 */ "MaxPgcnt",
   22665      /* 148 */ "Trace",
   22666      /* 149 */ "Noop",
   22667      /* 150 */ "Explain",
   22668   };
   22669   return azName[i];
   22670 }
   22671 #endif
   22672 
   22673 /************** End of opcodes.c *********************************************/
   22674 /************** Begin file os_os2.c ******************************************/
   22675 /*
   22676 ** 2006 Feb 14
   22677 **
   22678 ** The author disclaims copyright to this source code.  In place of
   22679 ** a legal notice, here is a blessing:
   22680 **
   22681 **    May you do good and not evil.
   22682 **    May you find forgiveness for yourself and forgive others.
   22683 **    May you share freely, never taking more than you give.
   22684 **
   22685 ******************************************************************************
   22686 **
   22687 ** This file contains code that is specific to OS/2.
   22688 */
   22689 
   22690 
   22691 #if SQLITE_OS_OS2
   22692 
   22693 /*
   22694 ** A Note About Memory Allocation:
   22695 **
   22696 ** This driver uses malloc()/free() directly rather than going through
   22697 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
   22698 ** are designed for use on embedded systems where memory is scarce and
   22699 ** malloc failures happen frequently.  OS/2 does not typically run on
   22700 ** embedded systems, and when it does the developers normally have bigger
   22701 ** problems to worry about than running out of memory.  So there is not
   22702 ** a compelling need to use the wrappers.
   22703 **
   22704 ** But there is a good reason to not use the wrappers.  If we use the
   22705 ** wrappers then we will get simulated malloc() failures within this
   22706 ** driver.  And that causes all kinds of problems for our tests.  We
   22707 ** could enhance SQLite to deal with simulated malloc failures within
   22708 ** the OS driver, but the code to deal with those failure would not
   22709 ** be exercised on Linux (which does not need to malloc() in the driver)
   22710 ** and so we would have difficulty writing coverage tests for that
   22711 ** code.  Better to leave the code out, we think.
   22712 **
   22713 ** The point of this discussion is as follows:  When creating a new
   22714 ** OS layer for an embedded system, if you use this file as an example,
   22715 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
   22716 ** desktops but not so well in embedded systems.
   22717 */
   22718 
   22719 /*
   22720 ** Macros used to determine whether or not to use threads.
   22721 */
   22722 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
   22723 # define SQLITE_OS2_THREADS 1
   22724 #endif
   22725 
   22726 /*
   22727 ** Include code that is common to all os_*.c files
   22728 */
   22729 /************** Include os_common.h in the middle of os_os2.c ****************/
   22730 /************** Begin file os_common.h ***************************************/
   22731 /*
   22732 ** 2004 May 22
   22733 **
   22734 ** The author disclaims copyright to this source code.  In place of
   22735 ** a legal notice, here is a blessing:
   22736 **
   22737 **    May you do good and not evil.
   22738 **    May you find forgiveness for yourself and forgive others.
   22739 **    May you share freely, never taking more than you give.
   22740 **
   22741 ******************************************************************************
   22742 **
   22743 ** This file contains macros and a little bit of code that is common to
   22744 ** all of the platform-specific files (os_*.c) and is #included into those
   22745 ** files.
   22746 **
   22747 ** This file should be #included by the os_*.c files only.  It is not a
   22748 ** general purpose header file.
   22749 */
   22750 #ifndef _OS_COMMON_H_
   22751 #define _OS_COMMON_H_
   22752 
   22753 /*
   22754 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   22755 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   22756 ** switch.  The following code should catch this problem at compile-time.
   22757 */
   22758 #ifdef MEMORY_DEBUG
   22759 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   22760 #endif
   22761 
   22762 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   22763 # ifndef SQLITE_DEBUG_OS_TRACE
   22764 #   define SQLITE_DEBUG_OS_TRACE 0
   22765 # endif
   22766   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   22767 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   22768 #else
   22769 # define OSTRACE(X)
   22770 #endif
   22771 
   22772 /*
   22773 ** Macros for performance tracing.  Normally turned off.  Only works
   22774 ** on i486 hardware.
   22775 */
   22776 #ifdef SQLITE_PERFORMANCE_TRACE
   22777 
   22778 /*
   22779 ** hwtime.h contains inline assembler code for implementing
   22780 ** high-performance timing routines.
   22781 */
   22782 /************** Include hwtime.h in the middle of os_common.h ****************/
   22783 /************** Begin file hwtime.h ******************************************/
   22784 /*
   22785 ** 2008 May 27
   22786 **
   22787 ** The author disclaims copyright to this source code.  In place of
   22788 ** a legal notice, here is a blessing:
   22789 **
   22790 **    May you do good and not evil.
   22791 **    May you find forgiveness for yourself and forgive others.
   22792 **    May you share freely, never taking more than you give.
   22793 **
   22794 ******************************************************************************
   22795 **
   22796 ** This file contains inline asm code for retrieving "high-performance"
   22797 ** counters for x86 class CPUs.
   22798 */
   22799 #ifndef _HWTIME_H_
   22800 #define _HWTIME_H_
   22801 
   22802 /*
   22803 ** The following routine only works on pentium-class (or newer) processors.
   22804 ** It uses the RDTSC opcode to read the cycle count value out of the
   22805 ** processor and returns that value.  This can be used for high-res
   22806 ** profiling.
   22807 */
   22808 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   22809       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   22810 
   22811   #if defined(__GNUC__)
   22812 
   22813   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   22814      unsigned int lo, hi;
   22815      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   22816      return (sqlite_uint64)hi << 32 | lo;
   22817   }
   22818 
   22819   #elif defined(_MSC_VER)
   22820 
   22821   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   22822      __asm {
   22823         rdtsc
   22824         ret       ; return value at EDX:EAX
   22825      }
   22826   }
   22827 
   22828   #endif
   22829 
   22830 #elif (defined(__GNUC__) && defined(__x86_64__))
   22831 
   22832   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   22833       unsigned long val;
   22834       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   22835       return val;
   22836   }
   22837 
   22838 #elif (defined(__GNUC__) && defined(__ppc__))
   22839 
   22840   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   22841       unsigned long long retval;
   22842       unsigned long junk;
   22843       __asm__ __volatile__ ("\n\
   22844           1:      mftbu   %1\n\
   22845                   mftb    %L0\n\
   22846                   mftbu   %0\n\
   22847                   cmpw    %0,%1\n\
   22848                   bne     1b"
   22849                   : "=r" (retval), "=r" (junk));
   22850       return retval;
   22851   }
   22852 
   22853 #else
   22854 
   22855   #error Need implementation of sqlite3Hwtime() for your platform.
   22856 
   22857   /*
   22858   ** To compile without implementing sqlite3Hwtime() for your platform,
   22859   ** you can remove the above #error and use the following
   22860   ** stub function.  You will lose timing support for many
   22861   ** of the debugging and testing utilities, but it should at
   22862   ** least compile and run.
   22863   */
   22864 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   22865 
   22866 #endif
   22867 
   22868 #endif /* !defined(_HWTIME_H_) */
   22869 
   22870 /************** End of hwtime.h **********************************************/
   22871 /************** Continuing where we left off in os_common.h ******************/
   22872 
   22873 static sqlite_uint64 g_start;
   22874 static sqlite_uint64 g_elapsed;
   22875 #define TIMER_START       g_start=sqlite3Hwtime()
   22876 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   22877 #define TIMER_ELAPSED     g_elapsed
   22878 #else
   22879 #define TIMER_START
   22880 #define TIMER_END
   22881 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   22882 #endif
   22883 
   22884 /*
   22885 ** If we compile with the SQLITE_TEST macro set, then the following block
   22886 ** of code will give us the ability to simulate a disk I/O error.  This
   22887 ** is used for testing the I/O recovery logic.
   22888 */
   22889 #ifdef SQLITE_TEST
   22890 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   22891 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   22892 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   22893 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   22894 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   22895 SQLITE_API int sqlite3_diskfull_pending = 0;
   22896 SQLITE_API int sqlite3_diskfull = 0;
   22897 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   22898 #define SimulateIOError(CODE)  \
   22899   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   22900        || sqlite3_io_error_pending-- == 1 )  \
   22901               { local_ioerr(); CODE; }
   22902 static void local_ioerr(){
   22903   IOTRACE(("IOERR\n"));
   22904   sqlite3_io_error_hit++;
   22905   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   22906 }
   22907 #define SimulateDiskfullError(CODE) \
   22908    if( sqlite3_diskfull_pending ){ \
   22909      if( sqlite3_diskfull_pending == 1 ){ \
   22910        local_ioerr(); \
   22911        sqlite3_diskfull = 1; \
   22912        sqlite3_io_error_hit = 1; \
   22913        CODE; \
   22914      }else{ \
   22915        sqlite3_diskfull_pending--; \
   22916      } \
   22917    }
   22918 #else
   22919 #define SimulateIOErrorBenign(X)
   22920 #define SimulateIOError(A)
   22921 #define SimulateDiskfullError(A)
   22922 #endif
   22923 
   22924 /*
   22925 ** When testing, keep a count of the number of open files.
   22926 */
   22927 #ifdef SQLITE_TEST
   22928 SQLITE_API int sqlite3_open_file_count = 0;
   22929 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   22930 #else
   22931 #define OpenCounter(X)
   22932 #endif
   22933 
   22934 #endif /* !defined(_OS_COMMON_H_) */
   22935 
   22936 /************** End of os_common.h *******************************************/
   22937 /************** Continuing where we left off in os_os2.c *********************/
   22938 
   22939 /* Forward references */
   22940 typedef struct os2File os2File;         /* The file structure */
   22941 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
   22942 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
   22943 
   22944 /*
   22945 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
   22946 ** protability layer.
   22947 */
   22948 struct os2File {
   22949   const sqlite3_io_methods *pMethod;  /* Always the first entry */
   22950   HFILE h;                  /* Handle for accessing the file */
   22951   int flags;                /* Flags provided to os2Open() */
   22952   int locktype;             /* Type of lock currently held on this file */
   22953   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
   22954   char *zFullPathCp;        /* Full path name of this file */
   22955   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
   22956 };
   22957 
   22958 #define LOCK_TIMEOUT 10L /* the default locking timeout */
   22959 
   22960 /*
   22961 ** Missing from some versions of the OS/2 toolkit -
   22962 ** used to allocate from high memory if possible
   22963 */
   22964 #ifndef OBJ_ANY
   22965 # define OBJ_ANY 0x00000400
   22966 #endif
   22967 
   22968 /*****************************************************************************
   22969 ** The next group of routines implement the I/O methods specified
   22970 ** by the sqlite3_io_methods object.
   22971 ******************************************************************************/
   22972 
   22973 /*
   22974 ** Close a file.
   22975 */
   22976 static int os2Close( sqlite3_file *id ){
   22977   APIRET rc;
   22978   os2File *pFile = (os2File*)id;
   22979 
   22980   assert( id!=0 );
   22981   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
   22982 
   22983   rc = DosClose( pFile->h );
   22984 
   22985   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
   22986     DosForceDelete( (PSZ)pFile->zFullPathCp );
   22987 
   22988   free( pFile->zFullPathCp );
   22989   pFile->zFullPathCp = NULL;
   22990   pFile->locktype = NO_LOCK;
   22991   pFile->h = (HFILE)-1;
   22992   pFile->flags = 0;
   22993 
   22994   OpenCounter( -1 );
   22995   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   22996 }
   22997 
   22998 /*
   22999 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   23000 ** bytes were read successfully and SQLITE_IOERR if anything goes
   23001 ** wrong.
   23002 */
   23003 static int os2Read(
   23004   sqlite3_file *id,               /* File to read from */
   23005   void *pBuf,                     /* Write content into this buffer */
   23006   int amt,                        /* Number of bytes to read */
   23007   sqlite3_int64 offset            /* Begin reading at this offset */
   23008 ){
   23009   ULONG fileLocation = 0L;
   23010   ULONG got;
   23011   os2File *pFile = (os2File*)id;
   23012   assert( id!=0 );
   23013   SimulateIOError( return SQLITE_IOERR_READ );
   23014   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
   23015   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   23016     return SQLITE_IOERR;
   23017   }
   23018   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
   23019     return SQLITE_IOERR_READ;
   23020   }
   23021   if( got == (ULONG)amt )
   23022     return SQLITE_OK;
   23023   else {
   23024     /* Unread portions of the input buffer must be zero-filled */
   23025     memset(&((char*)pBuf)[got], 0, amt-got);
   23026     return SQLITE_IOERR_SHORT_READ;
   23027   }
   23028 }
   23029 
   23030 /*
   23031 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   23032 ** or some other error code on failure.
   23033 */
   23034 static int os2Write(
   23035   sqlite3_file *id,               /* File to write into */
   23036   const void *pBuf,               /* The bytes to be written */
   23037   int amt,                        /* Number of bytes to write */
   23038   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   23039 ){
   23040   ULONG fileLocation = 0L;
   23041   APIRET rc = NO_ERROR;
   23042   ULONG wrote;
   23043   os2File *pFile = (os2File*)id;
   23044   assert( id!=0 );
   23045   SimulateIOError( return SQLITE_IOERR_WRITE );
   23046   SimulateDiskfullError( return SQLITE_FULL );
   23047   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
   23048   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   23049     return SQLITE_IOERR;
   23050   }
   23051   assert( amt>0 );
   23052   while( amt > 0 &&
   23053          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
   23054          wrote > 0
   23055   ){
   23056     amt -= wrote;
   23057     pBuf = &((char*)pBuf)[wrote];
   23058   }
   23059 
   23060   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
   23061 }
   23062 
   23063 /*
   23064 ** Truncate an open file to a specified size
   23065 */
   23066 static int os2Truncate( sqlite3_file *id, i64 nByte ){
   23067   APIRET rc;
   23068   os2File *pFile = (os2File*)id;
   23069   assert( id!=0 );
   23070   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
   23071   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   23072 
   23073   /* If the user has configured a chunk-size for this file, truncate the
   23074   ** file so that it consists of an integer number of chunks (i.e. the
   23075   ** actual file size after the operation may be larger than the requested
   23076   ** size).
   23077   */
   23078   if( pFile->szChunk ){
   23079     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   23080   }
   23081 
   23082   rc = DosSetFileSize( pFile->h, nByte );
   23083   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
   23084 }
   23085 
   23086 #ifdef SQLITE_TEST
   23087 /*
   23088 ** Count the number of fullsyncs and normal syncs.  This is used to test
   23089 ** that syncs and fullsyncs are occuring at the right times.
   23090 */
   23091 SQLITE_API int sqlite3_sync_count = 0;
   23092 SQLITE_API int sqlite3_fullsync_count = 0;
   23093 #endif
   23094 
   23095 /*
   23096 ** Make sure all writes to a particular file are committed to disk.
   23097 */
   23098 static int os2Sync( sqlite3_file *id, int flags ){
   23099   os2File *pFile = (os2File*)id;
   23100   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
   23101 #ifdef SQLITE_TEST
   23102   if( flags & SQLITE_SYNC_FULL){
   23103     sqlite3_fullsync_count++;
   23104   }
   23105   sqlite3_sync_count++;
   23106 #endif
   23107   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   23108   ** no-op
   23109   */
   23110 #ifdef SQLITE_NO_SYNC
   23111   UNUSED_PARAMETER(pFile);
   23112   return SQLITE_OK;
   23113 #else
   23114   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   23115 #endif
   23116 }
   23117 
   23118 /*
   23119 ** Determine the current size of a file in bytes
   23120 */
   23121 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
   23122   APIRET rc = NO_ERROR;
   23123   FILESTATUS3 fsts3FileInfo;
   23124   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
   23125   assert( id!=0 );
   23126   SimulateIOError( return SQLITE_IOERR_FSTAT );
   23127   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
   23128   if( rc == NO_ERROR ){
   23129     *pSize = fsts3FileInfo.cbFile;
   23130     return SQLITE_OK;
   23131   }else{
   23132     return SQLITE_IOERR_FSTAT;
   23133   }
   23134 }
   23135 
   23136 /*
   23137 ** Acquire a reader lock.
   23138 */
   23139 static int getReadLock( os2File *pFile ){
   23140   FILELOCK  LockArea,
   23141             UnlockArea;
   23142   APIRET res;
   23143   memset(&LockArea, 0, sizeof(LockArea));
   23144   memset(&UnlockArea, 0, sizeof(UnlockArea));
   23145   LockArea.lOffset = SHARED_FIRST;
   23146   LockArea.lRange = SHARED_SIZE;
   23147   UnlockArea.lOffset = 0L;
   23148   UnlockArea.lRange = 0L;
   23149   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   23150   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
   23151   return res;
   23152 }
   23153 
   23154 /*
   23155 ** Undo a readlock
   23156 */
   23157 static int unlockReadLock( os2File *id ){
   23158   FILELOCK  LockArea,
   23159             UnlockArea;
   23160   APIRET res;
   23161   memset(&LockArea, 0, sizeof(LockArea));
   23162   memset(&UnlockArea, 0, sizeof(UnlockArea));
   23163   LockArea.lOffset = 0L;
   23164   LockArea.lRange = 0L;
   23165   UnlockArea.lOffset = SHARED_FIRST;
   23166   UnlockArea.lRange = SHARED_SIZE;
   23167   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   23168   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
   23169   return res;
   23170 }
   23171 
   23172 /*
   23173 ** Lock the file with the lock specified by parameter locktype - one
   23174 ** of the following:
   23175 **
   23176 **     (1) SHARED_LOCK
   23177 **     (2) RESERVED_LOCK
   23178 **     (3) PENDING_LOCK
   23179 **     (4) EXCLUSIVE_LOCK
   23180 **
   23181 ** Sometimes when requesting one lock state, additional lock states
   23182 ** are inserted in between.  The locking might fail on one of the later
   23183 ** transitions leaving the lock state different from what it started but
   23184 ** still short of its goal.  The following chart shows the allowed
   23185 ** transitions and the inserted intermediate states:
   23186 **
   23187 **    UNLOCKED -> SHARED
   23188 **    SHARED -> RESERVED
   23189 **    SHARED -> (PENDING) -> EXCLUSIVE
   23190 **    RESERVED -> (PENDING) -> EXCLUSIVE
   23191 **    PENDING -> EXCLUSIVE
   23192 **
   23193 ** This routine will only increase a lock.  The os2Unlock() routine
   23194 ** erases all locks at once and returns us immediately to locking level 0.
   23195 ** It is not possible to lower the locking level one step at a time.  You
   23196 ** must go straight to locking level 0.
   23197 */
   23198 static int os2Lock( sqlite3_file *id, int locktype ){
   23199   int rc = SQLITE_OK;       /* Return code from subroutines */
   23200   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
   23201   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   23202   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   23203   FILELOCK  LockArea,
   23204             UnlockArea;
   23205   os2File *pFile = (os2File*)id;
   23206   memset(&LockArea, 0, sizeof(LockArea));
   23207   memset(&UnlockArea, 0, sizeof(UnlockArea));
   23208   assert( pFile!=0 );
   23209   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
   23210 
   23211   /* If there is already a lock of this type or more restrictive on the
   23212   ** os2File, do nothing. Don't use the end_lock: exit path, as
   23213   ** sqlite3_mutex_enter() hasn't been called yet.
   23214   */
   23215   if( pFile->locktype>=locktype ){
   23216     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
   23217     return SQLITE_OK;
   23218   }
   23219 
   23220   /* Make sure the locking sequence is correct
   23221   */
   23222   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   23223   assert( locktype!=PENDING_LOCK );
   23224   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   23225 
   23226   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   23227   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   23228   ** the PENDING_LOCK byte is temporary.
   23229   */
   23230   newLocktype = pFile->locktype;
   23231   if( pFile->locktype==NO_LOCK
   23232       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
   23233   ){
   23234     LockArea.lOffset = PENDING_BYTE;
   23235     LockArea.lRange = 1L;
   23236     UnlockArea.lOffset = 0L;
   23237     UnlockArea.lRange = 0L;
   23238 
   23239     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
   23240     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
   23241     if( res == NO_ERROR ){
   23242       gotPendingLock = 1;
   23243       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
   23244     }
   23245   }
   23246 
   23247   /* Acquire a shared lock
   23248   */
   23249   if( locktype==SHARED_LOCK && res == NO_ERROR ){
   23250     assert( pFile->locktype==NO_LOCK );
   23251     res = getReadLock(pFile);
   23252     if( res == NO_ERROR ){
   23253       newLocktype = SHARED_LOCK;
   23254     }
   23255     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
   23256   }
   23257 
   23258   /* Acquire a RESERVED lock
   23259   */
   23260   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
   23261     assert( pFile->locktype==SHARED_LOCK );
   23262     LockArea.lOffset = RESERVED_BYTE;
   23263     LockArea.lRange = 1L;
   23264     UnlockArea.lOffset = 0L;
   23265     UnlockArea.lRange = 0L;
   23266     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23267     if( res == NO_ERROR ){
   23268       newLocktype = RESERVED_LOCK;
   23269     }
   23270     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
   23271   }
   23272 
   23273   /* Acquire a PENDING lock
   23274   */
   23275   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   23276     newLocktype = PENDING_LOCK;
   23277     gotPendingLock = 0;
   23278     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
   23279                pFile->h ));
   23280   }
   23281 
   23282   /* Acquire an EXCLUSIVE lock
   23283   */
   23284   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   23285     assert( pFile->locktype>=SHARED_LOCK );
   23286     res = unlockReadLock(pFile);
   23287     OSTRACE(( "unreadlock = %d\n", res ));
   23288     LockArea.lOffset = SHARED_FIRST;
   23289     LockArea.lRange = SHARED_SIZE;
   23290     UnlockArea.lOffset = 0L;
   23291     UnlockArea.lRange = 0L;
   23292     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23293     if( res == NO_ERROR ){
   23294       newLocktype = EXCLUSIVE_LOCK;
   23295     }else{
   23296       OSTRACE(( "OS/2 error-code = %d\n", res ));
   23297       getReadLock(pFile);
   23298     }
   23299     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
   23300   }
   23301 
   23302   /* If we are holding a PENDING lock that ought to be released, then
   23303   ** release it now.
   23304   */
   23305   if( gotPendingLock && locktype==SHARED_LOCK ){
   23306     int r;
   23307     LockArea.lOffset = 0L;
   23308     LockArea.lRange = 0L;
   23309     UnlockArea.lOffset = PENDING_BYTE;
   23310     UnlockArea.lRange = 1L;
   23311     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23312     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
   23313   }
   23314 
   23315   /* Update the state of the lock has held in the file descriptor then
   23316   ** return the appropriate result code.
   23317   */
   23318   if( res == NO_ERROR ){
   23319     rc = SQLITE_OK;
   23320   }else{
   23321     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   23322               locktype, newLocktype ));
   23323     rc = SQLITE_BUSY;
   23324   }
   23325   pFile->locktype = newLocktype;
   23326   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
   23327   return rc;
   23328 }
   23329 
   23330 /*
   23331 ** This routine checks if there is a RESERVED lock held on the specified
   23332 ** file by this or any other process. If such a lock is held, return
   23333 ** non-zero, otherwise zero.
   23334 */
   23335 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
   23336   int r = 0;
   23337   os2File *pFile = (os2File*)id;
   23338   assert( pFile!=0 );
   23339   if( pFile->locktype>=RESERVED_LOCK ){
   23340     r = 1;
   23341     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
   23342   }else{
   23343     FILELOCK  LockArea,
   23344               UnlockArea;
   23345     APIRET rc = NO_ERROR;
   23346     memset(&LockArea, 0, sizeof(LockArea));
   23347     memset(&UnlockArea, 0, sizeof(UnlockArea));
   23348     LockArea.lOffset = RESERVED_BYTE;
   23349     LockArea.lRange = 1L;
   23350     UnlockArea.lOffset = 0L;
   23351     UnlockArea.lRange = 0L;
   23352     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23353     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
   23354     if( rc == NO_ERROR ){
   23355       APIRET rcu = NO_ERROR; /* return code for unlocking */
   23356       LockArea.lOffset = 0L;
   23357       LockArea.lRange = 0L;
   23358       UnlockArea.lOffset = RESERVED_BYTE;
   23359       UnlockArea.lRange = 1L;
   23360       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23361       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
   23362     }
   23363     r = !(rc == NO_ERROR);
   23364     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
   23365   }
   23366   *pOut = r;
   23367   return SQLITE_OK;
   23368 }
   23369 
   23370 /*
   23371 ** Lower the locking level on file descriptor id to locktype.  locktype
   23372 ** must be either NO_LOCK or SHARED_LOCK.
   23373 **
   23374 ** If the locking level of the file descriptor is already at or below
   23375 ** the requested locking level, this routine is a no-op.
   23376 **
   23377 ** It is not possible for this routine to fail if the second argument
   23378 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   23379 ** might return SQLITE_IOERR;
   23380 */
   23381 static int os2Unlock( sqlite3_file *id, int locktype ){
   23382   int type;
   23383   os2File *pFile = (os2File*)id;
   23384   APIRET rc = SQLITE_OK;
   23385   APIRET res = NO_ERROR;
   23386   FILELOCK  LockArea,
   23387             UnlockArea;
   23388   memset(&LockArea, 0, sizeof(LockArea));
   23389   memset(&UnlockArea, 0, sizeof(UnlockArea));
   23390   assert( pFile!=0 );
   23391   assert( locktype<=SHARED_LOCK );
   23392   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
   23393   type = pFile->locktype;
   23394   if( type>=EXCLUSIVE_LOCK ){
   23395     LockArea.lOffset = 0L;
   23396     LockArea.lRange = 0L;
   23397     UnlockArea.lOffset = SHARED_FIRST;
   23398     UnlockArea.lRange = SHARED_SIZE;
   23399     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23400     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
   23401     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
   23402       /* This should never happen.  We should always be able to
   23403       ** reacquire the read lock */
   23404       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
   23405       rc = SQLITE_IOERR_UNLOCK;
   23406     }
   23407   }
   23408   if( type>=RESERVED_LOCK ){
   23409     LockArea.lOffset = 0L;
   23410     LockArea.lRange = 0L;
   23411     UnlockArea.lOffset = RESERVED_BYTE;
   23412     UnlockArea.lRange = 1L;
   23413     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23414     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
   23415   }
   23416   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   23417     res = unlockReadLock(pFile);
   23418     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
   23419               pFile->h, type, locktype, res ));
   23420   }
   23421   if( type>=PENDING_LOCK ){
   23422     LockArea.lOffset = 0L;
   23423     LockArea.lRange = 0L;
   23424     UnlockArea.lOffset = PENDING_BYTE;
   23425     UnlockArea.lRange = 1L;
   23426     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   23427     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
   23428   }
   23429   pFile->locktype = locktype;
   23430   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
   23431   return rc;
   23432 }
   23433 
   23434 /*
   23435 ** Control and query of the open file handle.
   23436 */
   23437 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
   23438   switch( op ){
   23439     case SQLITE_FCNTL_LOCKSTATE: {
   23440       *(int*)pArg = ((os2File*)id)->locktype;
   23441       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
   23442                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
   23443       return SQLITE_OK;
   23444     }
   23445     case SQLITE_FCNTL_CHUNK_SIZE: {
   23446       ((os2File*)id)->szChunk = *(int*)pArg;
   23447       return SQLITE_OK;
   23448     }
   23449     case SQLITE_FCNTL_SIZE_HINT: {
   23450       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
   23451       SimulateIOErrorBenign(1);
   23452       os2Truncate(id, sz);
   23453       SimulateIOErrorBenign(0);
   23454       return SQLITE_OK;
   23455     }
   23456     case SQLITE_FCNTL_SYNC_OMITTED: {
   23457       return SQLITE_OK;
   23458     }
   23459   }
   23460   return SQLITE_NOTFOUND;
   23461 }
   23462 
   23463 /*
   23464 ** Return the sector size in bytes of the underlying block device for
   23465 ** the specified file. This is almost always 512 bytes, but may be
   23466 ** larger for some devices.
   23467 **
   23468 ** SQLite code assumes this function cannot fail. It also assumes that
   23469 ** if two files are created in the same file-system directory (i.e.
   23470 ** a database and its journal file) that the sector size will be the
   23471 ** same for both.
   23472 */
   23473 static int os2SectorSize(sqlite3_file *id){
   23474   UNUSED_PARAMETER(id);
   23475   return SQLITE_DEFAULT_SECTOR_SIZE;
   23476 }
   23477 
   23478 /*
   23479 ** Return a vector of device characteristics.
   23480 */
   23481 static int os2DeviceCharacteristics(sqlite3_file *id){
   23482   UNUSED_PARAMETER(id);
   23483   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
   23484 }
   23485 
   23486 
   23487 /*
   23488 ** Character set conversion objects used by conversion routines.
   23489 */
   23490 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
   23491 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
   23492 
   23493 /*
   23494 ** Helper function to initialize the conversion objects from and to UTF-8.
   23495 */
   23496 static void initUconvObjects( void ){
   23497   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
   23498     ucUtf8 = NULL;
   23499   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
   23500     uclCp = NULL;
   23501 }
   23502 
   23503 /*
   23504 ** Helper function to free the conversion objects from and to UTF-8.
   23505 */
   23506 static void freeUconvObjects( void ){
   23507   if ( ucUtf8 )
   23508     UniFreeUconvObject( ucUtf8 );
   23509   if ( uclCp )
   23510     UniFreeUconvObject( uclCp );
   23511   ucUtf8 = NULL;
   23512   uclCp = NULL;
   23513 }
   23514 
   23515 /*
   23516 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
   23517 ** The two-step process: first convert the incoming UTF-8 string
   23518 ** into UCS-2 and then from UCS-2 to the current codepage.
   23519 ** The returned char pointer has to be freed.
   23520 */
   23521 static char *convertUtf8PathToCp( const char *in ){
   23522   UniChar tempPath[CCHMAXPATH];
   23523   char *out = (char *)calloc( CCHMAXPATH, 1 );
   23524 
   23525   if( !out )
   23526     return NULL;
   23527 
   23528   if( !ucUtf8 || !uclCp )
   23529     initUconvObjects();
   23530 
   23531   /* determine string for the conversion of UTF-8 which is CP1208 */
   23532   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   23533     return out; /* if conversion fails, return the empty string */
   23534 
   23535   /* conversion for current codepage which can be used for paths */
   23536   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
   23537 
   23538   return out;
   23539 }
   23540 
   23541 /*
   23542 ** Helper function to convert filenames from local codepage to UTF-8.
   23543 ** The two-step process: first convert the incoming codepage-specific
   23544 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
   23545 ** The returned char pointer has to be freed.
   23546 **
   23547 ** This function is non-static to be able to use this in shell.c and
   23548 ** similar applications that take command line arguments.
   23549 */
   23550 char *convertCpPathToUtf8( const char *in ){
   23551   UniChar tempPath[CCHMAXPATH];
   23552   char *out = (char *)calloc( CCHMAXPATH, 1 );
   23553 
   23554   if( !out )
   23555     return NULL;
   23556 
   23557   if( !ucUtf8 || !uclCp )
   23558     initUconvObjects();
   23559 
   23560   /* conversion for current codepage which can be used for paths */
   23561   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   23562     return out; /* if conversion fails, return the empty string */
   23563 
   23564   /* determine string for the conversion of UTF-8 which is CP1208 */
   23565   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
   23566 
   23567   return out;
   23568 }
   23569 
   23570 
   23571 #ifndef SQLITE_OMIT_WAL
   23572 
   23573 /*
   23574 ** Use main database file for interprocess locking. If un-defined
   23575 ** a separate file is created for this purpose. The file will be
   23576 ** used only to set file locks. There will be no data written to it.
   23577 */
   23578 #define SQLITE_OS2_NO_WAL_LOCK_FILE
   23579 
   23580 #if 0
   23581 static void _ERR_TRACE( const char *fmt, ... ) {
   23582   va_list  ap;
   23583   va_start(ap, fmt);
   23584   vfprintf(stderr, fmt, ap);
   23585   fflush(stderr);
   23586 }
   23587 #define ERR_TRACE(rc, msg)        \
   23588         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
   23589 #else
   23590 #define ERR_TRACE(rc, msg)
   23591 #endif
   23592 
   23593 /*
   23594 ** Helper functions to obtain and relinquish the global mutex. The
   23595 ** global mutex is used to protect os2ShmNodeList.
   23596 **
   23597 ** Function os2ShmMutexHeld() is used to assert() that the global mutex
   23598 ** is held when required. This function is only used as part of assert()
   23599 ** statements. e.g.
   23600 **
   23601 **   os2ShmEnterMutex()
   23602 **     assert( os2ShmMutexHeld() );
   23603 **   os2ShmLeaveMutex()
   23604 */
   23605 static void os2ShmEnterMutex(void){
   23606   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23607 }
   23608 static void os2ShmLeaveMutex(void){
   23609   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23610 }
   23611 #ifdef SQLITE_DEBUG
   23612 static int os2ShmMutexHeld(void) {
   23613   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23614 }
   23615 int GetCurrentProcessId(void) {
   23616   PPIB pib;
   23617   DosGetInfoBlocks(NULL, &pib);
   23618   return (int)pib->pib_ulpid;
   23619 }
   23620 #endif
   23621 
   23622 /*
   23623 ** Object used to represent a the shared memory area for a single log file.
   23624 ** When multiple threads all reference the same log-summary, each thread has
   23625 ** its own os2File object, but they all point to a single instance of this
   23626 ** object.  In other words, each log-summary is opened only once per process.
   23627 **
   23628 ** os2ShmMutexHeld() must be true when creating or destroying
   23629 ** this object or while reading or writing the following fields:
   23630 **
   23631 **      nRef
   23632 **      pNext
   23633 **
   23634 ** The following fields are read-only after the object is created:
   23635 **
   23636 **      szRegion
   23637 **      hLockFile
   23638 **      shmBaseName
   23639 **
   23640 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
   23641 ** os2ShmMutexHeld() is true when reading or writing any other field
   23642 ** in this structure.
   23643 **
   23644 */
   23645 struct os2ShmNode {
   23646   sqlite3_mutex *mutex;      /* Mutex to access this object */
   23647   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
   23648 
   23649   int szRegion;              /* Size of shared-memory regions */
   23650 
   23651   int nRegion;               /* Size of array apRegion */
   23652   void **apRegion;           /* Array of pointers to shared-memory regions */
   23653 
   23654   int nRef;                  /* Number of os2ShmLink objects pointing to this */
   23655   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
   23656 
   23657   HFILE hLockFile;           /* File used for inter-process memory locking */
   23658   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
   23659 };
   23660 
   23661 
   23662 /*
   23663 ** Structure used internally by this VFS to record the state of an
   23664 ** open shared memory connection.
   23665 **
   23666 ** The following fields are initialized when this object is created and
   23667 ** are read-only thereafter:
   23668 **
   23669 **    os2Shm.pShmNode
   23670 **    os2Shm.id
   23671 **
   23672 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
   23673 ** while accessing any read/write fields.
   23674 */
   23675 struct os2ShmLink {
   23676   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
   23677   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
   23678   u32 sharedMask;            /* Mask of shared locks held */
   23679   u32 exclMask;              /* Mask of exclusive locks held */
   23680 #ifdef SQLITE_DEBUG
   23681   u8 id;                     /* Id of this connection with its os2ShmNode */
   23682 #endif
   23683 };
   23684 
   23685 
   23686 /*
   23687 ** A global list of all os2ShmNode objects.
   23688 **
   23689 ** The os2ShmMutexHeld() must be true while reading or writing this list.
   23690 */
   23691 static os2ShmNode *os2ShmNodeList = NULL;
   23692 
   23693 /*
   23694 ** Constants used for locking
   23695 */
   23696 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
   23697 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
   23698 #else
   23699 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   23700 #endif
   23701 
   23702 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   23703 
   23704 /*
   23705 ** Apply advisory locks for all n bytes beginning at ofst.
   23706 */
   23707 #define _SHM_UNLCK  1   /* no lock */
   23708 #define _SHM_RDLCK  2   /* shared lock, no wait */
   23709 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
   23710 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
   23711 static int os2ShmSystemLock(
   23712   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
   23713   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
   23714   int ofst,             /* Offset to first byte to be locked/unlocked */
   23715   int nByte             /* Number of bytes to lock or unlock */
   23716 ){
   23717   APIRET rc;
   23718   FILELOCK area;
   23719   ULONG mode, timeout;
   23720 
   23721   /* Access to the os2ShmNode object is serialized by the caller */
   23722   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
   23723 
   23724   mode = 1;     /* shared lock */
   23725   timeout = 0;  /* no wait */
   23726   area.lOffset = ofst;
   23727   area.lRange = nByte;
   23728 
   23729   switch( lockType ) {
   23730     case _SHM_WRLCK_WAIT:
   23731       timeout = (ULONG)-1;      /* wait forever */
   23732     case _SHM_WRLCK:
   23733       mode = 0;                 /* exclusive lock */
   23734     case _SHM_RDLCK:
   23735       rc = DosSetFileLocks(pNode->hLockFile,
   23736                            NULL, &area, timeout, mode);
   23737       break;
   23738     /* case _SHM_UNLCK: */
   23739     default:
   23740       rc = DosSetFileLocks(pNode->hLockFile,
   23741                            &area, NULL, 0, 0);
   23742       break;
   23743   }
   23744 
   23745   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
   23746            pNode->hLockFile,
   23747            rc==SQLITE_OK ? "ok" : "failed",
   23748            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
   23749            rc));
   23750 
   23751   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
   23752 
   23753   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
   23754 }
   23755 
   23756 /*
   23757 ** Find an os2ShmNode in global list or allocate a new one, if not found.
   23758 **
   23759 ** This is not a VFS shared-memory method; it is a utility function called
   23760 ** by VFS shared-memory methods.
   23761 */
   23762 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
   23763   os2ShmLink *pLink;
   23764   os2ShmNode *pNode;
   23765   int cbShmName, rc = SQLITE_OK;
   23766   char shmName[CCHMAXPATH + 30];
   23767 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
   23768   ULONG action;
   23769 #endif
   23770 
   23771   /* We need some additional space at the end to append the region number */
   23772   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
   23773   if( cbShmName >= CCHMAXPATH-8 )
   23774     return SQLITE_IOERR_SHMOPEN;
   23775 
   23776   /* Replace colon in file name to form a valid shared memory name */
   23777   shmName[10+1] = '!';
   23778 
   23779   /* Allocate link object (we free it later in case of failure) */
   23780   pLink = sqlite3_malloc( sizeof(*pLink) );
   23781   if( !pLink )
   23782     return SQLITE_NOMEM;
   23783 
   23784   /* Access node list */
   23785   os2ShmEnterMutex();
   23786 
   23787   /* Find node by it's shared memory base name */
   23788   for( pNode = os2ShmNodeList;
   23789        pNode && stricmp(shmName, pNode->shmBaseName) != 0;
   23790        pNode = pNode->pNext )   ;
   23791 
   23792   /* Not found: allocate a new node */
   23793   if( !pNode ) {
   23794     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
   23795     if( pNode ) {
   23796       memset(pNode, 0, sizeof(*pNode) );
   23797       pNode->szRegion = szRegion;
   23798       pNode->hLockFile = (HFILE)-1;
   23799       strcpy(pNode->shmBaseName, shmName);
   23800 
   23801 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
   23802       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
   23803 #else
   23804       sprintf(shmName, "%s-lck", fd->zFullPathCp);
   23805       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
   23806                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
   23807                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
   23808                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
   23809                   NULL) != 0 ) {
   23810 #endif
   23811         sqlite3_free(pNode);
   23812         rc = SQLITE_IOERR;
   23813       } else {
   23814         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   23815         if( !pNode->mutex ) {
   23816           sqlite3_free(pNode);
   23817           rc = SQLITE_NOMEM;
   23818         }
   23819       }
   23820     } else {
   23821       rc = SQLITE_NOMEM;
   23822     }
   23823 
   23824     if( rc == SQLITE_OK ) {
   23825       pNode->pNext = os2ShmNodeList;
   23826       os2ShmNodeList = pNode;
   23827     } else {
   23828       pNode = NULL;
   23829     }
   23830   } else if( pNode->szRegion != szRegion ) {
   23831     rc = SQLITE_IOERR_SHMSIZE;
   23832     pNode = NULL;
   23833   }
   23834 
   23835   if( pNode ) {
   23836     sqlite3_mutex_enter(pNode->mutex);
   23837 
   23838     memset(pLink, 0, sizeof(*pLink));
   23839 
   23840     pLink->pShmNode = pNode;
   23841     pLink->pNext = pNode->pFirst;
   23842     pNode->pFirst = pLink;
   23843     pNode->nRef++;
   23844 
   23845     fd->pShmLink = pLink;
   23846 
   23847     sqlite3_mutex_leave(pNode->mutex);
   23848 
   23849   } else {
   23850     /* Error occured. Free our link object. */
   23851     sqlite3_free(pLink);
   23852   }
   23853 
   23854   os2ShmLeaveMutex();
   23855 
   23856   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))
   23857 
   23858   return rc;
   23859 }
   23860 
   23861 /*
   23862 ** Purge the os2ShmNodeList list of all entries with nRef==0.
   23863 **
   23864 ** This is not a VFS shared-memory method; it is a utility function called
   23865 ** by VFS shared-memory methods.
   23866 */
   23867 static void os2PurgeShmNodes( int deleteFlag ) {
   23868   os2ShmNode *pNode;
   23869   os2ShmNode **ppNode;
   23870 
   23871   os2ShmEnterMutex();
   23872 
   23873   ppNode = &os2ShmNodeList;
   23874 
   23875   while( *ppNode ) {
   23876     pNode = *ppNode;
   23877 
   23878     if( pNode->nRef == 0 ) {
   23879       *ppNode = pNode->pNext;
   23880 
   23881       if( pNode->apRegion ) {
   23882         /* Prevent other processes from resizing the shared memory */
   23883         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
   23884 
   23885         while( pNode->nRegion-- ) {
   23886 #ifdef SQLITE_DEBUG
   23887           int rc =
   23888 #endif
   23889           DosFreeMem(pNode->apRegion[pNode->nRegion]);
   23890 
   23891           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
   23892                   (int)GetCurrentProcessId(), pNode->nRegion,
   23893                   rc == 0 ? "ok" : "failed"));
   23894         }
   23895 
   23896         /* Allow other processes to resize the shared memory */
   23897         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
   23898 
   23899         sqlite3_free(pNode->apRegion);
   23900       }
   23901 
   23902       DosClose(pNode->hLockFile);
   23903 
   23904 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
   23905       if( deleteFlag ) {
   23906          char fileName[CCHMAXPATH];
   23907          /* Skip "\\SHAREMEM\\" */
   23908          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
   23909          /* restore colon */
   23910          fileName[1] = ':';
   23911 
   23912          DosForceDelete(fileName);
   23913       }
   23914 #endif
   23915 
   23916       sqlite3_mutex_free(pNode->mutex);
   23917 
   23918       sqlite3_free(pNode);
   23919 
   23920     } else {
   23921       ppNode = &pNode->pNext;
   23922     }
   23923   }
   23924 
   23925   os2ShmLeaveMutex();
   23926 }
   23927 
   23928 /*
   23929 ** This function is called to obtain a pointer to region iRegion of the
   23930 ** shared-memory associated with the database file id. Shared-memory regions
   23931 ** are numbered starting from zero. Each shared-memory region is szRegion
   23932 ** bytes in size.
   23933 **
   23934 ** If an error occurs, an error code is returned and *pp is set to NULL.
   23935 **
   23936 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   23937 ** region has not been allocated (by any client, including one running in a
   23938 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   23939 ** bExtend is non-zero and the requested shared-memory region has not yet
   23940 ** been allocated, it is allocated by this function.
   23941 **
   23942 ** If the shared-memory region has already been allocated or is allocated by
   23943 ** this call as described above, then it is mapped into this processes
   23944 ** address space (if it is not already), *pp is set to point to the mapped
   23945 ** memory and SQLITE_OK returned.
   23946 */
   23947 static int os2ShmMap(
   23948   sqlite3_file *id,               /* Handle open on database file */
   23949   int iRegion,                    /* Region to retrieve */
   23950   int szRegion,                   /* Size of regions */
   23951   int bExtend,                    /* True to extend block if necessary */
   23952   void volatile **pp              /* OUT: Mapped memory */
   23953 ){
   23954   PVOID pvTemp;
   23955   void **apRegion;
   23956   os2ShmNode *pNode;
   23957   int n, rc = SQLITE_OK;
   23958   char shmName[CCHMAXPATH];
   23959   os2File *pFile = (os2File*)id;
   23960 
   23961   *pp = NULL;
   23962 
   23963   if( !pFile->pShmLink )
   23964     rc = os2OpenSharedMemory( pFile, szRegion );
   23965 
   23966   if( rc == SQLITE_OK ) {
   23967     pNode = pFile->pShmLink->pShmNode ;
   23968 
   23969     sqlite3_mutex_enter(pNode->mutex);
   23970 
   23971     assert( szRegion==pNode->szRegion );
   23972 
   23973     /* Unmapped region ? */
   23974     if( iRegion >= pNode->nRegion ) {
   23975       /* Prevent other processes from resizing the shared memory */
   23976       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
   23977 
   23978       apRegion = sqlite3_realloc(
   23979         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
   23980 
   23981       if( apRegion ) {
   23982         pNode->apRegion = apRegion;
   23983 
   23984         while( pNode->nRegion <= iRegion ) {
   23985           sprintf(shmName, "%s-%u",
   23986                   pNode->shmBaseName, pNode->nRegion);
   23987 
   23988           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
   23989                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
   23990             if( !bExtend )
   23991               break;
   23992 
   23993             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
   23994                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
   23995                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
   23996                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
   23997               rc = SQLITE_NOMEM;
   23998               break;
   23999             }
   24000           }
   24001 
   24002           apRegion[pNode->nRegion++] = pvTemp;
   24003         }
   24004 
   24005         /* zero out remaining entries */
   24006         for( n = pNode->nRegion; n <= iRegion; n++ )
   24007           pNode->apRegion[n] = NULL;
   24008 
   24009         /* Return this region (maybe zero) */
   24010         *pp = pNode->apRegion[iRegion];
   24011       } else {
   24012         rc = SQLITE_NOMEM;
   24013       }
   24014 
   24015       /* Allow other processes to resize the shared memory */
   24016       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
   24017 
   24018     } else {
   24019       /* Region has been mapped previously */
   24020       *pp = pNode->apRegion[iRegion];
   24021     }
   24022 
   24023     sqlite3_mutex_leave(pNode->mutex);
   24024   }
   24025 
   24026   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
   24027                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
   24028 
   24029   return rc;
   24030 }
   24031 
   24032 /*
   24033 ** Close a connection to shared-memory.  Delete the underlying
   24034 ** storage if deleteFlag is true.
   24035 **
   24036 ** If there is no shared memory associated with the connection then this
   24037 ** routine is a harmless no-op.
   24038 */
   24039 static int os2ShmUnmap(
   24040   sqlite3_file *id,               /* The underlying database file */
   24041   int deleteFlag                  /* Delete shared-memory if true */
   24042 ){
   24043   os2File *pFile = (os2File*)id;
   24044   os2ShmLink *pLink = pFile->pShmLink;
   24045 
   24046   if( pLink ) {
   24047     int nRef = -1;
   24048     os2ShmLink **ppLink;
   24049     os2ShmNode *pNode = pLink->pShmNode;
   24050 
   24051     sqlite3_mutex_enter(pNode->mutex);
   24052 
   24053     for( ppLink = &pNode->pFirst;
   24054          *ppLink && *ppLink != pLink;
   24055          ppLink = &(*ppLink)->pNext )   ;
   24056 
   24057     assert(*ppLink);
   24058 
   24059     if( *ppLink ) {
   24060       *ppLink = pLink->pNext;
   24061       nRef = --pNode->nRef;
   24062     } else {
   24063       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
   24064                     pNode->shmBaseName))
   24065     }
   24066 
   24067     pFile->pShmLink = NULL;
   24068     sqlite3_free(pLink);
   24069 
   24070     sqlite3_mutex_leave(pNode->mutex);
   24071 
   24072     if( nRef == 0 )
   24073       os2PurgeShmNodes( deleteFlag );
   24074   }
   24075 
   24076   return SQLITE_OK;
   24077 }
   24078 
   24079 /*
   24080 ** Change the lock state for a shared-memory segment.
   24081 **
   24082 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   24083 ** different here than in posix.  In xShmLock(), one can go from unlocked
   24084 ** to shared and back or from unlocked to exclusive and back.  But one may
   24085 ** not go from shared to exclusive or from exclusive to shared.
   24086 */
   24087 static int os2ShmLock(
   24088   sqlite3_file *id,          /* Database file holding the shared memory */
   24089   int ofst,                  /* First lock to acquire or release */
   24090   int n,                     /* Number of locks to acquire or release */
   24091   int flags                  /* What to do with the lock */
   24092 ){
   24093   u32 mask;                             /* Mask of locks to take or release */
   24094   int rc = SQLITE_OK;                   /* Result code */
   24095   os2File *pFile = (os2File*)id;
   24096   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
   24097   os2ShmLink *pX;                       /* For looping over all siblings */
   24098   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
   24099 
   24100   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   24101   assert( n>=1 );
   24102   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   24103        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   24104        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   24105        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   24106   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   24107 
   24108   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
   24109   assert( n>1 || mask==(1<<ofst) );
   24110 
   24111 
   24112   sqlite3_mutex_enter(pShmNode->mutex);
   24113 
   24114   if( flags & SQLITE_SHM_UNLOCK ){
   24115     u32 allMask = 0; /* Mask of locks held by siblings */
   24116 
   24117     /* See if any siblings hold this same lock */
   24118     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   24119       if( pX==p ) continue;
   24120       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   24121       allMask |= pX->sharedMask;
   24122     }
   24123 
   24124     /* Unlock the system-level locks */
   24125     if( (mask & allMask)==0 ){
   24126       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
   24127     }else{
   24128       rc = SQLITE_OK;
   24129     }
   24130 
   24131     /* Undo the local locks */
   24132     if( rc==SQLITE_OK ){
   24133       p->exclMask &= ~mask;
   24134       p->sharedMask &= ~mask;
   24135     }
   24136   }else if( flags & SQLITE_SHM_SHARED ){
   24137     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
   24138 
   24139     /* Find out which shared locks are already held by sibling connections.
   24140     ** If any sibling already holds an exclusive lock, go ahead and return
   24141     ** SQLITE_BUSY.
   24142     */
   24143     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   24144       if( (pX->exclMask & mask)!=0 ){
   24145         rc = SQLITE_BUSY;
   24146         break;
   24147       }
   24148       allShared |= pX->sharedMask;
   24149     }
   24150 
   24151     /* Get shared locks at the system level, if necessary */
   24152     if( rc==SQLITE_OK ){
   24153       if( (allShared & mask)==0 ){
   24154         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
   24155       }else{
   24156         rc = SQLITE_OK;
   24157       }
   24158     }
   24159 
   24160     /* Get the local shared locks */
   24161     if( rc==SQLITE_OK ){
   24162       p->sharedMask |= mask;
   24163     }
   24164   }else{
   24165     /* Make sure no sibling connections hold locks that will block this
   24166     ** lock.  If any do, return SQLITE_BUSY right away.
   24167     */
   24168     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   24169       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   24170         rc = SQLITE_BUSY;
   24171         break;
   24172       }
   24173     }
   24174 
   24175     /* Get the exclusive locks at the system level.  Then if successful
   24176     ** also mark the local connection as being locked.
   24177     */
   24178     if( rc==SQLITE_OK ){
   24179       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
   24180       if( rc==SQLITE_OK ){
   24181         assert( (p->sharedMask & mask)==0 );
   24182         p->exclMask |= mask;
   24183       }
   24184     }
   24185   }
   24186 
   24187   sqlite3_mutex_leave(pShmNode->mutex);
   24188 
   24189   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
   24190            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
   24191            rc ? "failed" : "ok"));
   24192 
   24193   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
   24194                  ofst, n, flags, rc))
   24195 
   24196   return rc;
   24197 }
   24198 
   24199 /*
   24200 ** Implement a memory barrier or memory fence on shared memory.
   24201 **
   24202 ** All loads and stores begun before the barrier must complete before
   24203 ** any load or store begun after the barrier.
   24204 */
   24205 static void os2ShmBarrier(
   24206   sqlite3_file *id                /* Database file holding the shared memory */
   24207 ){
   24208   UNUSED_PARAMETER(id);
   24209   os2ShmEnterMutex();
   24210   os2ShmLeaveMutex();
   24211 }
   24212 
   24213 #else
   24214 # define os2ShmMap     0
   24215 # define os2ShmLock    0
   24216 # define os2ShmBarrier 0
   24217 # define os2ShmUnmap   0
   24218 #endif /* #ifndef SQLITE_OMIT_WAL */
   24219 
   24220 
   24221 /*
   24222 ** This vector defines all the methods that can operate on an
   24223 ** sqlite3_file for os2.
   24224 */
   24225 static const sqlite3_io_methods os2IoMethod = {
   24226   2,                              /* iVersion */
   24227   os2Close,                       /* xClose */
   24228   os2Read,                        /* xRead */
   24229   os2Write,                       /* xWrite */
   24230   os2Truncate,                    /* xTruncate */
   24231   os2Sync,                        /* xSync */
   24232   os2FileSize,                    /* xFileSize */
   24233   os2Lock,                        /* xLock */
   24234   os2Unlock,                      /* xUnlock */
   24235   os2CheckReservedLock,           /* xCheckReservedLock */
   24236   os2FileControl,                 /* xFileControl */
   24237   os2SectorSize,                  /* xSectorSize */
   24238   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
   24239   os2ShmMap,                      /* xShmMap */
   24240   os2ShmLock,                     /* xShmLock */
   24241   os2ShmBarrier,                  /* xShmBarrier */
   24242   os2ShmUnmap                     /* xShmUnmap */
   24243 };
   24244 
   24245 
   24246 /***************************************************************************
   24247 ** Here ends the I/O methods that form the sqlite3_io_methods object.
   24248 **
   24249 ** The next block of code implements the VFS methods.
   24250 ****************************************************************************/
   24251 
   24252 /*
   24253 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   24254 ** hold at pVfs->mxPathname characters.
   24255 */
   24256 static int getTempname(int nBuf, char *zBuf ){
   24257   static const char zChars[] =
   24258     "abcdefghijklmnopqrstuvwxyz"
   24259     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   24260     "0123456789";
   24261   int i, j;
   24262   PSZ zTempPathCp;
   24263   char zTempPath[CCHMAXPATH];
   24264   ULONG ulDriveNum, ulDriveMap;
   24265 
   24266   /* It's odd to simulate an io-error here, but really this is just
   24267   ** using the io-error infrastructure to test that SQLite handles this
   24268   ** function failing.
   24269   */
   24270   SimulateIOError( return SQLITE_IOERR );
   24271 
   24272   if( sqlite3_temp_directory ) {
   24273     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
   24274   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
   24275              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
   24276              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
   24277     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
   24278     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
   24279     free( zTempPathUTF );
   24280   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
   24281     zTempPath[0] = (char)('A' + ulDriveNum - 1);
   24282     zTempPath[1] = ':';
   24283     zTempPath[2] = '\0';
   24284   } else {
   24285     zTempPath[0] = '\0';
   24286   }
   24287 
   24288   /* Strip off a trailing slashes or backslashes, otherwise we would get *
   24289    * multiple (back)slashes which causes DosOpen() to fail.              *
   24290    * Trailing spaces are not allowed, either.                            */
   24291   j = sqlite3Strlen30(zTempPath);
   24292   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
   24293                     zTempPath[j-1] == ' ' ) ){
   24294     j--;
   24295   }
   24296   zTempPath[j] = '\0';
   24297 
   24298   /* We use 20 bytes to randomize the name */
   24299   sqlite3_snprintf(nBuf-22, zBuf,
   24300                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
   24301   j = sqlite3Strlen30(zBuf);
   24302   sqlite3_randomness( 20, &zBuf[j] );
   24303   for( i = 0; i < 20; i++, j++ ){
   24304     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   24305   }
   24306   zBuf[j] = 0;
   24307 
   24308   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
   24309   return SQLITE_OK;
   24310 }
   24311 
   24312 
   24313 /*
   24314 ** Turn a relative pathname into a full pathname.  Write the full
   24315 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
   24316 ** bytes in size.
   24317 */
   24318 static int os2FullPathname(
   24319   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
   24320   const char *zRelative,      /* Possibly relative input path */
   24321   int nFull,                  /* Size of output buffer in bytes */
   24322   char *zFull                 /* Output buffer */
   24323 ){
   24324   char *zRelativeCp = convertUtf8PathToCp( zRelative );
   24325   char zFullCp[CCHMAXPATH] = "\0";
   24326   char *zFullUTF;
   24327   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
   24328                                 zFullCp, CCHMAXPATH );
   24329   free( zRelativeCp );
   24330   zFullUTF = convertCpPathToUtf8( zFullCp );
   24331   sqlite3_snprintf( nFull, zFull, zFullUTF );
   24332   free( zFullUTF );
   24333   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   24334 }
   24335 
   24336 
   24337 /*
   24338 ** Open a file.
   24339 */
   24340 static int os2Open(
   24341   sqlite3_vfs *pVfs,            /* Not used */
   24342   const char *zName,            /* Name of the file (UTF-8) */
   24343   sqlite3_file *id,             /* Write the SQLite file handle here */
   24344   int flags,                    /* Open mode flags */
   24345   int *pOutFlags                /* Status return flags */
   24346 ){
   24347   HFILE h;
   24348   ULONG ulOpenFlags = 0;
   24349   ULONG ulOpenMode = 0;
   24350   ULONG ulAction = 0;
   24351   ULONG rc;
   24352   os2File *pFile = (os2File*)id;
   24353   const char *zUtf8Name = zName;
   24354   char *zNameCp;
   24355   char  zTmpname[CCHMAXPATH];
   24356 
   24357   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   24358   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   24359   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   24360 #ifndef NDEBUG
   24361   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   24362   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   24363   int eType        = (flags & 0xFFFFFF00);
   24364   int isOpenJournal = (isCreate && (
   24365         eType==SQLITE_OPEN_MASTER_JOURNAL
   24366      || eType==SQLITE_OPEN_MAIN_JOURNAL
   24367      || eType==SQLITE_OPEN_WAL
   24368   ));
   24369 #endif
   24370 
   24371   UNUSED_PARAMETER(pVfs);
   24372   assert( id!=0 );
   24373 
   24374   /* Check the following statements are true:
   24375   **
   24376   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   24377   **   (b) if CREATE is set, then READWRITE must also be set, and
   24378   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   24379   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   24380   */
   24381   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   24382   assert(isCreate==0 || isReadWrite);
   24383   assert(isExclusive==0 || isCreate);
   24384   assert(isDelete==0 || isCreate);
   24385 
   24386   /* The main DB, main journal, WAL file and master journal are never
   24387   ** automatically deleted. Nor are they ever temporary files.  */
   24388   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   24389   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   24390   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   24391   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   24392 
   24393   /* Assert that the upper layer has set one of the "file-type" flags. */
   24394   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   24395        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   24396        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   24397        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   24398   );
   24399 
   24400   memset( pFile, 0, sizeof(*pFile) );
   24401   pFile->h = (HFILE)-1;
   24402 
   24403   /* If the second argument to this function is NULL, generate a
   24404   ** temporary file name to use
   24405   */
   24406   if( !zUtf8Name ){
   24407     assert(isDelete && !isOpenJournal);
   24408     rc = getTempname(CCHMAXPATH, zTmpname);
   24409     if( rc!=SQLITE_OK ){
   24410       return rc;
   24411     }
   24412     zUtf8Name = zTmpname;
   24413   }
   24414 
   24415   if( isReadWrite ){
   24416     ulOpenMode |= OPEN_ACCESS_READWRITE;
   24417   }else{
   24418     ulOpenMode |= OPEN_ACCESS_READONLY;
   24419   }
   24420 
   24421   /* Open in random access mode for possibly better speed.  Allow full
   24422   ** sharing because file locks will provide exclusive access when needed.
   24423   ** The handle should not be inherited by child processes and we don't
   24424   ** want popups from the critical error handler.
   24425   */
   24426   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
   24427                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
   24428 
   24429   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   24430   ** created. SQLite doesn't use it to indicate "exclusive access"
   24431   ** as it is usually understood.
   24432   */
   24433   if( isExclusive ){
   24434     /* Creates a new file, only if it does not already exist. */
   24435     /* If the file exists, it fails. */
   24436     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
   24437   }else if( isCreate ){
   24438     /* Open existing file, or create if it doesn't exist */
   24439     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
   24440   }else{
   24441     /* Opens a file, only if it exists. */
   24442     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
   24443   }
   24444 
   24445   zNameCp = convertUtf8PathToCp( zUtf8Name );
   24446   rc = DosOpen( (PSZ)zNameCp,
   24447                 &h,
   24448                 &ulAction,
   24449                 0L,
   24450                 FILE_NORMAL,
   24451                 ulOpenFlags,
   24452                 ulOpenMode,
   24453                 (PEAOP2)NULL );
   24454   free( zNameCp );
   24455 
   24456   if( rc != NO_ERROR ){
   24457     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
   24458               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
   24459 
   24460     if( isReadWrite ){
   24461       return os2Open( pVfs, zName, id,
   24462                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
   24463                       pOutFlags );
   24464     }else{
   24465       return SQLITE_CANTOPEN;
   24466     }
   24467   }
   24468 
   24469   if( pOutFlags ){
   24470     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
   24471   }
   24472 
   24473   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
   24474   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
   24475   pFile->pMethod = &os2IoMethod;
   24476   pFile->flags = flags;
   24477   pFile->h = h;
   24478 
   24479   OpenCounter(+1);
   24480   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
   24481   return SQLITE_OK;
   24482 }
   24483 
   24484 /*
   24485 ** Delete the named file.
   24486 */
   24487 static int os2Delete(
   24488   sqlite3_vfs *pVfs,                     /* Not used on os2 */
   24489   const char *zFilename,                 /* Name of file to delete */
   24490   int syncDir                            /* Not used on os2 */
   24491 ){
   24492   APIRET rc;
   24493   char *zFilenameCp;
   24494   SimulateIOError( return SQLITE_IOERR_DELETE );
   24495   zFilenameCp = convertUtf8PathToCp( zFilename );
   24496   rc = DosDelete( (PSZ)zFilenameCp );
   24497   free( zFilenameCp );
   24498   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
   24499   return (rc == NO_ERROR ||
   24500           rc == ERROR_FILE_NOT_FOUND ||
   24501           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
   24502 }
   24503 
   24504 /*
   24505 ** Check the existance and status of a file.
   24506 */
   24507 static int os2Access(
   24508   sqlite3_vfs *pVfs,        /* Not used on os2 */
   24509   const char *zFilename,    /* Name of file to check */
   24510   int flags,                /* Type of test to make on this file */
   24511   int *pOut                 /* Write results here */
   24512 ){
   24513   APIRET rc;
   24514   FILESTATUS3 fsts3ConfigInfo;
   24515   char *zFilenameCp;
   24516 
   24517   UNUSED_PARAMETER(pVfs);
   24518   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   24519 
   24520   zFilenameCp = convertUtf8PathToCp( zFilename );
   24521   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
   24522                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
   24523   free( zFilenameCp );
   24524   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
   24525             fsts3ConfigInfo.attrFile, flags, rc ));
   24526 
   24527   switch( flags ){
   24528     case SQLITE_ACCESS_EXISTS:
   24529       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   24530       ** as if it does not exist.
   24531       */
   24532       if( fsts3ConfigInfo.cbFile == 0 )
   24533         rc = ERROR_FILE_NOT_FOUND;
   24534       break;
   24535     case SQLITE_ACCESS_READ:
   24536       break;
   24537     case SQLITE_ACCESS_READWRITE:
   24538       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
   24539         rc = ERROR_ACCESS_DENIED;
   24540       break;
   24541     default:
   24542       rc = ERROR_FILE_NOT_FOUND;
   24543       assert( !"Invalid flags argument" );
   24544   }
   24545 
   24546   *pOut = (rc == NO_ERROR);
   24547   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
   24548 
   24549   return SQLITE_OK;
   24550 }
   24551 
   24552 
   24553 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   24554 /*
   24555 ** Interfaces for opening a shared library, finding entry points
   24556 ** within the shared library, and closing the shared library.
   24557 */
   24558 /*
   24559 ** Interfaces for opening a shared library, finding entry points
   24560 ** within the shared library, and closing the shared library.
   24561 */
   24562 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   24563   HMODULE hmod;
   24564   APIRET rc;
   24565   char *zFilenameCp = convertUtf8PathToCp(zFilename);
   24566   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
   24567   free(zFilenameCp);
   24568   return rc != NO_ERROR ? 0 : (void*)hmod;
   24569 }
   24570 /*
   24571 ** A no-op since the error code is returned on the DosLoadModule call.
   24572 ** os2Dlopen returns zero if DosLoadModule is not successful.
   24573 */
   24574 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   24575 /* no-op */
   24576 }
   24577 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
   24578   PFN pfn;
   24579   APIRET rc;
   24580   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
   24581   if( rc != NO_ERROR ){
   24582     /* if the symbol itself was not found, search again for the same
   24583      * symbol with an extra underscore, that might be needed depending
   24584      * on the calling convention */
   24585     char _zSymbol[256] = "_";
   24586     strncat(_zSymbol, zSymbol, 254);
   24587     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
   24588   }
   24589   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
   24590 }
   24591 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
   24592   DosFreeModule((HMODULE)pHandle);
   24593 }
   24594 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   24595   #define os2DlOpen 0
   24596   #define os2DlError 0
   24597   #define os2DlSym 0
   24598   #define os2DlClose 0
   24599 #endif
   24600 
   24601 
   24602 /*
   24603 ** Write up to nBuf bytes of randomness into zBuf.
   24604 */
   24605 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
   24606   int n = 0;
   24607 #if defined(SQLITE_TEST)
   24608   n = nBuf;
   24609   memset(zBuf, 0, nBuf);
   24610 #else
   24611   int i;
   24612   PPIB ppib;
   24613   PTIB ptib;
   24614   DATETIME dt;
   24615   static unsigned c = 0;
   24616   /* Ordered by variation probability */
   24617   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
   24618                             QSV_MAXPRMEM, QSV_MAXSHMEM,
   24619                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
   24620 
   24621   /* 8 bytes; timezone and weekday don't increase the randomness much */
   24622   if( (int)sizeof(dt)-3 <= nBuf - n ){
   24623     c += 0x0100;
   24624     DosGetDateTime(&dt);
   24625     dt.year = (USHORT)((dt.year - 1900) | c);
   24626     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
   24627     n += sizeof(dt)-3;
   24628   }
   24629 
   24630   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
   24631   if( (int)sizeof(ULONG) <= nBuf - n ){
   24632     DosGetInfoBlocks(&ptib, &ppib);
   24633     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
   24634                                  ptib->tib_ptib2->tib2_ultid);
   24635     n += sizeof(ULONG);
   24636   }
   24637 
   24638   /* Up to 6 * 4 bytes; variables depend on the system state */
   24639   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
   24640     DosQuerySysInfo(svIdx[i], svIdx[i],
   24641                     (PULONG)&zBuf[n], sizeof(ULONG));
   24642     n += sizeof(ULONG);
   24643   }
   24644 #endif
   24645 
   24646   return n;
   24647 }
   24648 
   24649 /*
   24650 ** Sleep for a little while.  Return the amount of time slept.
   24651 ** The argument is the number of microseconds we want to sleep.
   24652 ** The return value is the number of microseconds of sleep actually
   24653 ** requested from the underlying operating system, a number which
   24654 ** might be greater than or equal to the argument, but not less
   24655 ** than the argument.
   24656 */
   24657 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
   24658   DosSleep( (microsec/1000) );
   24659   return microsec;
   24660 }
   24661 
   24662 /*
   24663 ** The following variable, if set to a non-zero value, becomes the result
   24664 ** returned from sqlite3OsCurrentTime().  This is used for testing.
   24665 */
   24666 #ifdef SQLITE_TEST
   24667 SQLITE_API int sqlite3_current_time = 0;
   24668 #endif
   24669 
   24670 /*
   24671 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   24672 ** the current time and date as a Julian Day number times 86_400_000.  In
   24673 ** other words, write into *piNow the number of milliseconds since the Julian
   24674 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   24675 ** proleptic Gregorian calendar.
   24676 **
   24677 ** On success, return 0.  Return 1 if the time and date cannot be found.
   24678 */
   24679 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   24680 #ifdef SQLITE_TEST
   24681   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   24682 #endif
   24683   int year, month, datepart, timepart;
   24684 
   24685   DATETIME dt;
   24686   DosGetDateTime( &dt );
   24687 
   24688   year = dt.year;
   24689   month = dt.month;
   24690 
   24691   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
   24692   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
   24693   ** Calculate the Julian days
   24694   */
   24695   datepart = (int)dt.day - 32076 +
   24696     1461*(year + 4800 + (month - 14)/12)/4 +
   24697     367*(month - 2 - (month - 14)/12*12)/12 -
   24698     3*((year + 4900 + (month - 14)/12)/100)/4;
   24699 
   24700   /* Time in milliseconds, hours to noon added */
   24701   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
   24702     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
   24703 
   24704   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
   24705 
   24706 #ifdef SQLITE_TEST
   24707   if( sqlite3_current_time ){
   24708     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   24709   }
   24710 #endif
   24711 
   24712   UNUSED_PARAMETER(pVfs);
   24713   return 0;
   24714 }
   24715 
   24716 /*
   24717 ** Find the current time (in Universal Coordinated Time).  Write the
   24718 ** current time and date as a Julian Day number into *prNow and
   24719 ** return 0.  Return 1 if the time and date cannot be found.
   24720 */
   24721 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
   24722   int rc;
   24723   sqlite3_int64 i;
   24724   rc = os2CurrentTimeInt64(pVfs, &i);
   24725   if( !rc ){
   24726     *prNow = i/86400000.0;
   24727   }
   24728   return rc;
   24729 }
   24730 
   24731 /*
   24732 ** The idea is that this function works like a combination of
   24733 ** GetLastError() and FormatMessage() on windows (or errno and
   24734 ** strerror_r() on unix). After an error is returned by an OS
   24735 ** function, SQLite calls this function with zBuf pointing to
   24736 ** a buffer of nBuf bytes. The OS layer should populate the
   24737 ** buffer with a nul-terminated UTF-8 encoded error message
   24738 ** describing the last IO error to have occurred within the calling
   24739 ** thread.
   24740 **
   24741 ** If the error message is too large for the supplied buffer,
   24742 ** it should be truncated. The return value of xGetLastError
   24743 ** is zero if the error message fits in the buffer, or non-zero
   24744 ** otherwise (if the message was truncated). If non-zero is returned,
   24745 ** then it is not necessary to include the nul-terminator character
   24746 ** in the output buffer.
   24747 **
   24748 ** Not supplying an error message will have no adverse effect
   24749 ** on SQLite. It is fine to have an implementation that never
   24750 ** returns an error message:
   24751 **
   24752 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   24753 **     assert(zBuf[0]=='\0');
   24754 **     return 0;
   24755 **   }
   24756 **
   24757 ** However if an error message is supplied, it will be incorporated
   24758 ** by sqlite into the error message available to the user using
   24759 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   24760 */
   24761 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   24762   assert(zBuf[0]=='\0');
   24763   return 0;
   24764 }
   24765 
   24766 /*
   24767 ** Initialize and deinitialize the operating system interface.
   24768 */
   24769 SQLITE_API int sqlite3_os_init(void){
   24770   static sqlite3_vfs os2Vfs = {
   24771     3,                 /* iVersion */
   24772     sizeof(os2File),   /* szOsFile */
   24773     CCHMAXPATH,        /* mxPathname */
   24774     0,                 /* pNext */
   24775     "os2",             /* zName */
   24776     0,                 /* pAppData */
   24777 
   24778     os2Open,           /* xOpen */
   24779     os2Delete,         /* xDelete */
   24780     os2Access,         /* xAccess */
   24781     os2FullPathname,   /* xFullPathname */
   24782     os2DlOpen,         /* xDlOpen */
   24783     os2DlError,        /* xDlError */
   24784     os2DlSym,          /* xDlSym */
   24785     os2DlClose,        /* xDlClose */
   24786     os2Randomness,     /* xRandomness */
   24787     os2Sleep,          /* xSleep */
   24788     os2CurrentTime,    /* xCurrentTime */
   24789     os2GetLastError,   /* xGetLastError */
   24790     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
   24791     0,                 /* xSetSystemCall */
   24792     0,                 /* xGetSystemCall */
   24793     0                  /* xNextSystemCall */
   24794   };
   24795   sqlite3_vfs_register(&os2Vfs, 1);
   24796   initUconvObjects();
   24797 /*  sqlite3OSTrace = 1; */
   24798   return SQLITE_OK;
   24799 }
   24800 SQLITE_API int sqlite3_os_end(void){
   24801   freeUconvObjects();
   24802   return SQLITE_OK;
   24803 }
   24804 
   24805 #endif /* SQLITE_OS_OS2 */
   24806 
   24807 /************** End of os_os2.c **********************************************/
   24808 /************** Begin file os_unix.c *****************************************/
   24809 /*
   24810 ** 2004 May 22
   24811 **
   24812 ** The author disclaims copyright to this source code.  In place of
   24813 ** a legal notice, here is a blessing:
   24814 **
   24815 **    May you do good and not evil.
   24816 **    May you find forgiveness for yourself and forgive others.
   24817 **    May you share freely, never taking more than you give.
   24818 **
   24819 ******************************************************************************
   24820 **
   24821 ** This file contains the VFS implementation for unix-like operating systems
   24822 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
   24823 **
   24824 ** There are actually several different VFS implementations in this file.
   24825 ** The differences are in the way that file locking is done.  The default
   24826 ** implementation uses Posix Advisory Locks.  Alternative implementations
   24827 ** use flock(), dot-files, various proprietary locking schemas, or simply
   24828 ** skip locking all together.
   24829 **
   24830 ** This source file is organized into divisions where the logic for various
   24831 ** subfunctions is contained within the appropriate division.  PLEASE
   24832 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
   24833 ** in the correct division and should be clearly labeled.
   24834 **
   24835 ** The layout of divisions is as follows:
   24836 **
   24837 **   *  General-purpose declarations and utility functions.
   24838 **   *  Unique file ID logic used by VxWorks.
   24839 **   *  Various locking primitive implementations (all except proxy locking):
   24840 **      + for Posix Advisory Locks
   24841 **      + for no-op locks
   24842 **      + for dot-file locks
   24843 **      + for flock() locking
   24844 **      + for named semaphore locks (VxWorks only)
   24845 **      + for AFP filesystem locks (MacOSX only)
   24846 **   *  sqlite3_file methods not associated with locking.
   24847 **   *  Definitions of sqlite3_io_methods objects for all locking
   24848 **      methods plus "finder" functions for each locking method.
   24849 **   *  sqlite3_vfs method implementations.
   24850 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
   24851 **   *  Definitions of sqlite3_vfs objects for all locking methods
   24852 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
   24853 */
   24854 #if SQLITE_OS_UNIX              /* This file is used on unix only */
   24855 
   24856 /* Use posix_fallocate() if it is available
   24857 */
   24858 #if !defined(HAVE_POSIX_FALLOCATE) \
   24859       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
   24860 # define HAVE_POSIX_FALLOCATE 1
   24861 #endif
   24862 
   24863 /*
   24864 ** There are various methods for file locking used for concurrency
   24865 ** control:
   24866 **
   24867 **   1. POSIX locking (the default),
   24868 **   2. No locking,
   24869 **   3. Dot-file locking,
   24870 **   4. flock() locking,
   24871 **   5. AFP locking (OSX only),
   24872 **   6. Named POSIX semaphores (VXWorks only),
   24873 **   7. proxy locking. (OSX only)
   24874 **
   24875 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   24876 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   24877 ** selection of the appropriate locking style based on the filesystem
   24878 ** where the database is located.
   24879 */
   24880 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   24881 #  if defined(__APPLE__)
   24882 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   24883 #  else
   24884 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   24885 #  endif
   24886 #endif
   24887 
   24888 /*
   24889 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   24890 ** vxworks, or 0 otherwise.
   24891 */
   24892 #ifndef OS_VXWORKS
   24893 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   24894 #    define OS_VXWORKS 1
   24895 #  else
   24896 #    define OS_VXWORKS 0
   24897 #  endif
   24898 #endif
   24899 
   24900 /*
   24901 ** These #defines should enable >2GB file support on Posix if the
   24902 ** underlying operating system supports it.  If the OS lacks
   24903 ** large file support, these should be no-ops.
   24904 **
   24905 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   24906 ** on the compiler command line.  This is necessary if you are compiling
   24907 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
   24908 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
   24909 ** without this option, LFS is enable.  But LFS does not exist in the kernel
   24910 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
   24911 ** portability you should omit LFS.
   24912 **
   24913 ** The previous paragraph was written in 2005.  (This paragraph is written
   24914 ** on 2008-11-28.) These days, all Linux kernels support large files, so
   24915 ** you should probably leave LFS enabled.  But some embedded platforms might
   24916 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   24917 */
   24918 #ifndef SQLITE_DISABLE_LFS
   24919 # define _LARGE_FILE       1
   24920 # ifndef _FILE_OFFSET_BITS
   24921 #   define _FILE_OFFSET_BITS 64
   24922 # endif
   24923 # define _LARGEFILE_SOURCE 1
   24924 #endif
   24925 
   24926 /*
   24927 ** standard include files.
   24928 */
   24929 #include <sys/types.h>
   24930 #include <sys/stat.h>
   24931 #include <fcntl.h>
   24932 #include <unistd.h>
   24933 /* #include <time.h> */
   24934 #include <sys/time.h>
   24935 #include <errno.h>
   24936 #ifndef SQLITE_OMIT_WAL
   24937 #include <sys/mman.h>
   24938 #endif
   24939 
   24940 
   24941 #if SQLITE_ENABLE_LOCKING_STYLE
   24942 # include <sys/ioctl.h>
   24943 # if OS_VXWORKS
   24944 #  include <semaphore.h>
   24945 #  include <limits.h>
   24946 # else
   24947 #  include <sys/file.h>
   24948 #  include <sys/param.h>
   24949 # endif
   24950 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   24951 
   24952 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24953 # include <sys/mount.h>
   24954 #endif
   24955 
   24956 #ifdef HAVE_UTIME
   24957 # include <utime.h>
   24958 #endif
   24959 
   24960 /*
   24961 ** Allowed values of unixFile.fsFlags
   24962 */
   24963 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   24964 
   24965 /*
   24966 ** If we are to be thread-safe, include the pthreads header and define
   24967 ** the SQLITE_UNIX_THREADS macro.
   24968 */
   24969 #if SQLITE_THREADSAFE
   24970 /* # include <pthread.h> */
   24971 # define SQLITE_UNIX_THREADS 1
   24972 #endif
   24973 
   24974 /*
   24975 ** Default permissions when creating a new file
   24976 */
   24977 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   24978 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   24979 #endif
   24980 
   24981 /*
   24982  ** Default permissions when creating auto proxy dir
   24983  */
   24984 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   24985 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   24986 #endif
   24987 
   24988 /*
   24989 ** Maximum supported path-length.
   24990 */
   24991 #define MAX_PATHNAME 512
   24992 
   24993 /*
   24994 ** Only set the lastErrno if the error code is a real error and not
   24995 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   24996 */
   24997 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   24998 
   24999 /* Forward references */
   25000 typedef struct unixShm unixShm;               /* Connection shared memory */
   25001 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   25002 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   25003 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   25004 
   25005 /*
   25006 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   25007 ** cannot be closed immediately. In these cases, instances of the following
   25008 ** structure are used to store the file descriptor while waiting for an
   25009 ** opportunity to either close or reuse it.
   25010 */
   25011 struct UnixUnusedFd {
   25012   int fd;                   /* File descriptor to close */
   25013   int flags;                /* Flags this file descriptor was opened with */
   25014   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   25015 };
   25016 
   25017 /*
   25018 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   25019 ** VFS implementations.
   25020 */
   25021 typedef struct unixFile unixFile;
   25022 struct unixFile {
   25023   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   25024   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   25025   unixInodeInfo *pInode;              /* Info about locks on this inode */
   25026   int h;                              /* The file descriptor */
   25027   unsigned char eFileLock;            /* The type of lock held on this fd */
   25028   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
   25029   int lastErrno;                      /* The unix errno from last I/O error */
   25030   void *lockingContext;               /* Locking style specific state */
   25031   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
   25032   const char *zPath;                  /* Name of the file */
   25033   unixShm *pShm;                      /* Shared memory segment information */
   25034   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   25035 #if SQLITE_ENABLE_LOCKING_STYLE
   25036   int openFlags;                      /* The flags specified at open() */
   25037 #endif
   25038 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   25039   unsigned fsFlags;                   /* cached details from statfs() */
   25040 #endif
   25041 #if OS_VXWORKS
   25042   struct vxworksFileId *pId;          /* Unique file ID */
   25043 #endif
   25044 #ifndef NDEBUG
   25045   /* The next group of variables are used to track whether or not the
   25046   ** transaction counter in bytes 24-27 of database files are updated
   25047   ** whenever any part of the database changes.  An assertion fault will
   25048   ** occur if a file is updated without also updating the transaction
   25049   ** counter.  This test is made to avoid new problems similar to the
   25050   ** one described by ticket #3584.
   25051   */
   25052   unsigned char transCntrChng;   /* True if the transaction counter changed */
   25053   unsigned char dbUpdate;        /* True if any part of database file changed */
   25054   unsigned char inNormalWrite;   /* True if in a normal write operation */
   25055 #endif
   25056 #ifdef SQLITE_TEST
   25057   /* In test mode, increase the size of this structure a bit so that
   25058   ** it is larger than the struct CrashFile defined in test6.c.
   25059   */
   25060   char aPadding[32];
   25061 #endif
   25062 };
   25063 
   25064 /*
   25065 ** Allowed values for the unixFile.ctrlFlags bitmask:
   25066 */
   25067 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
   25068 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   25069 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   25070 #ifndef SQLITE_DISABLE_DIRSYNC
   25071 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   25072 #else
   25073 # define UNIXFILE_DIRSYNC    0x00
   25074 #endif
   25075 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   25076 #define UNIXFILE_DELETE      0x20     /* Delete on close */
   25077 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
   25078 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
   25079 #define UNIXFILE_CHOWN      0x100     /* File ownership was changed */
   25080 
   25081 /*
   25082 ** Include code that is common to all os_*.c files
   25083 */
   25084 /************** Include os_common.h in the middle of os_unix.c ***************/
   25085 /************** Begin file os_common.h ***************************************/
   25086 /*
   25087 ** 2004 May 22
   25088 **
   25089 ** The author disclaims copyright to this source code.  In place of
   25090 ** a legal notice, here is a blessing:
   25091 **
   25092 **    May you do good and not evil.
   25093 **    May you find forgiveness for yourself and forgive others.
   25094 **    May you share freely, never taking more than you give.
   25095 **
   25096 ******************************************************************************
   25097 **
   25098 ** This file contains macros and a little bit of code that is common to
   25099 ** all of the platform-specific files (os_*.c) and is #included into those
   25100 ** files.
   25101 **
   25102 ** This file should be #included by the os_*.c files only.  It is not a
   25103 ** general purpose header file.
   25104 */
   25105 #ifndef _OS_COMMON_H_
   25106 #define _OS_COMMON_H_
   25107 
   25108 /*
   25109 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   25110 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   25111 ** switch.  The following code should catch this problem at compile-time.
   25112 */
   25113 #ifdef MEMORY_DEBUG
   25114 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   25115 #endif
   25116 
   25117 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   25118 # ifndef SQLITE_DEBUG_OS_TRACE
   25119 #   define SQLITE_DEBUG_OS_TRACE 0
   25120 # endif
   25121   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   25122 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   25123 #else
   25124 # define OSTRACE(X)
   25125 #endif
   25126 
   25127 /*
   25128 ** Macros for performance tracing.  Normally turned off.  Only works
   25129 ** on i486 hardware.
   25130 */
   25131 #ifdef SQLITE_PERFORMANCE_TRACE
   25132 
   25133 /*
   25134 ** hwtime.h contains inline assembler code for implementing
   25135 ** high-performance timing routines.
   25136 */
   25137 /************** Include hwtime.h in the middle of os_common.h ****************/
   25138 /************** Begin file hwtime.h ******************************************/
   25139 /*
   25140 ** 2008 May 27
   25141 **
   25142 ** The author disclaims copyright to this source code.  In place of
   25143 ** a legal notice, here is a blessing:
   25144 **
   25145 **    May you do good and not evil.
   25146 **    May you find forgiveness for yourself and forgive others.
   25147 **    May you share freely, never taking more than you give.
   25148 **
   25149 ******************************************************************************
   25150 **
   25151 ** This file contains inline asm code for retrieving "high-performance"
   25152 ** counters for x86 class CPUs.
   25153 */
   25154 #ifndef _HWTIME_H_
   25155 #define _HWTIME_H_
   25156 
   25157 /*
   25158 ** The following routine only works on pentium-class (or newer) processors.
   25159 ** It uses the RDTSC opcode to read the cycle count value out of the
   25160 ** processor and returns that value.  This can be used for high-res
   25161 ** profiling.
   25162 */
   25163 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   25164       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   25165 
   25166   #if defined(__GNUC__)
   25167 
   25168   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25169      unsigned int lo, hi;
   25170      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   25171      return (sqlite_uint64)hi << 32 | lo;
   25172   }
   25173 
   25174   #elif defined(_MSC_VER)
   25175 
   25176   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   25177      __asm {
   25178         rdtsc
   25179         ret       ; return value at EDX:EAX
   25180      }
   25181   }
   25182 
   25183   #endif
   25184 
   25185 #elif (defined(__GNUC__) && defined(__x86_64__))
   25186 
   25187   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25188       unsigned long val;
   25189       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   25190       return val;
   25191   }
   25192 
   25193 #elif (defined(__GNUC__) && defined(__ppc__))
   25194 
   25195   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25196       unsigned long long retval;
   25197       unsigned long junk;
   25198       __asm__ __volatile__ ("\n\
   25199           1:      mftbu   %1\n\
   25200                   mftb    %L0\n\
   25201                   mftbu   %0\n\
   25202                   cmpw    %0,%1\n\
   25203                   bne     1b"
   25204                   : "=r" (retval), "=r" (junk));
   25205       return retval;
   25206   }
   25207 
   25208 #else
   25209 
   25210   #error Need implementation of sqlite3Hwtime() for your platform.
   25211 
   25212   /*
   25213   ** To compile without implementing sqlite3Hwtime() for your platform,
   25214   ** you can remove the above #error and use the following
   25215   ** stub function.  You will lose timing support for many
   25216   ** of the debugging and testing utilities, but it should at
   25217   ** least compile and run.
   25218   */
   25219 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   25220 
   25221 #endif
   25222 
   25223 #endif /* !defined(_HWTIME_H_) */
   25224 
   25225 /************** End of hwtime.h **********************************************/
   25226 /************** Continuing where we left off in os_common.h ******************/
   25227 
   25228 static sqlite_uint64 g_start;
   25229 static sqlite_uint64 g_elapsed;
   25230 #define TIMER_START       g_start=sqlite3Hwtime()
   25231 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   25232 #define TIMER_ELAPSED     g_elapsed
   25233 #else
   25234 #define TIMER_START
   25235 #define TIMER_END
   25236 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   25237 #endif
   25238 
   25239 /*
   25240 ** If we compile with the SQLITE_TEST macro set, then the following block
   25241 ** of code will give us the ability to simulate a disk I/O error.  This
   25242 ** is used for testing the I/O recovery logic.
   25243 */
   25244 #ifdef SQLITE_TEST
   25245 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   25246 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   25247 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   25248 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   25249 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   25250 SQLITE_API int sqlite3_diskfull_pending = 0;
   25251 SQLITE_API int sqlite3_diskfull = 0;
   25252 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   25253 #define SimulateIOError(CODE)  \
   25254   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   25255        || sqlite3_io_error_pending-- == 1 )  \
   25256               { local_ioerr(); CODE; }
   25257 static void local_ioerr(){
   25258   IOTRACE(("IOERR\n"));
   25259   sqlite3_io_error_hit++;
   25260   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   25261 }
   25262 #define SimulateDiskfullError(CODE) \
   25263    if( sqlite3_diskfull_pending ){ \
   25264      if( sqlite3_diskfull_pending == 1 ){ \
   25265        local_ioerr(); \
   25266        sqlite3_diskfull = 1; \
   25267        sqlite3_io_error_hit = 1; \
   25268        CODE; \
   25269      }else{ \
   25270        sqlite3_diskfull_pending--; \
   25271      } \
   25272    }
   25273 #else
   25274 #define SimulateIOErrorBenign(X)
   25275 #define SimulateIOError(A)
   25276 #define SimulateDiskfullError(A)
   25277 #endif
   25278 
   25279 /*
   25280 ** When testing, keep a count of the number of open files.
   25281 */
   25282 #ifdef SQLITE_TEST
   25283 SQLITE_API int sqlite3_open_file_count = 0;
   25284 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   25285 #else
   25286 #define OpenCounter(X)
   25287 #endif
   25288 
   25289 #endif /* !defined(_OS_COMMON_H_) */
   25290 
   25291 /************** End of os_common.h *******************************************/
   25292 /************** Continuing where we left off in os_unix.c ********************/
   25293 
   25294 /*
   25295 ** Define various macros that are missing from some systems.
   25296 */
   25297 #ifndef O_LARGEFILE
   25298 # define O_LARGEFILE 0
   25299 #endif
   25300 #ifdef SQLITE_DISABLE_LFS
   25301 # undef O_LARGEFILE
   25302 # define O_LARGEFILE 0
   25303 #endif
   25304 #ifndef O_NOFOLLOW
   25305 # define O_NOFOLLOW 0
   25306 #endif
   25307 #ifndef O_BINARY
   25308 # define O_BINARY 0
   25309 #endif
   25310 
   25311 /*
   25312 ** The threadid macro resolves to the thread-id or to 0.  Used for
   25313 ** testing and debugging only.
   25314 */
   25315 #if SQLITE_THREADSAFE
   25316 #define threadid pthread_self()
   25317 #else
   25318 #define threadid 0
   25319 #endif
   25320 
   25321 /*
   25322 ** Different Unix systems declare open() in different ways.  Same use
   25323 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
   25324 ** The difference is important when using a pointer to the function.
   25325 **
   25326 ** The safest way to deal with the problem is to always use this wrapper
   25327 ** which always has the same well-defined interface.
   25328 */
   25329 static int posixOpen(const char *zFile, int flags, int mode){
   25330   return open(zFile, flags, mode);
   25331 }
   25332 
   25333 /* Forward reference */
   25334 static int openDirectory(const char*, int*);
   25335 
   25336 /*
   25337 ** Many system calls are accessed through pointer-to-functions so that
   25338 ** they may be overridden at runtime to facilitate fault injection during
   25339 ** testing and sandboxing.  The following array holds the names and pointers
   25340 ** to all overrideable system calls.
   25341 */
   25342 static struct unix_syscall {
   25343   const char *zName;            /* Name of the sytem call */
   25344   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   25345   sqlite3_syscall_ptr pDefault; /* Default value */
   25346 } aSyscall[] = {
   25347   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
   25348 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
   25349 
   25350   { "close",        (sqlite3_syscall_ptr)close,      0  },
   25351 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
   25352 
   25353   { "access",       (sqlite3_syscall_ptr)access,     0  },
   25354 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
   25355 
   25356   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
   25357 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
   25358 
   25359   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
   25360 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
   25361 
   25362 /*
   25363 ** The DJGPP compiler environment looks mostly like Unix, but it
   25364 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   25365 ** that always succeeds.  This means that locking does not occur under
   25366 ** DJGPP.  But it is DOS - what did you expect?
   25367 */
   25368 #ifdef __DJGPP__
   25369   { "fstat",        0,                 0  },
   25370 #define osFstat(a,b,c)    0
   25371 #else
   25372   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
   25373 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
   25374 #endif
   25375 
   25376   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
   25377 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
   25378 
   25379   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   25380 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   25381 
   25382   { "read",         (sqlite3_syscall_ptr)read,       0  },
   25383 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   25384 
   25385 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   25386   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   25387 #else
   25388   { "pread",        (sqlite3_syscall_ptr)0,          0  },
   25389 #endif
   25390 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   25391 
   25392 #if defined(USE_PREAD64)
   25393   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
   25394 #else
   25395   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   25396 #endif
   25397 #ifdef ANDROID
   25398 // Bionic defines pread64 using off64_t rather than off_t.
   25399 #define osPread64   ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
   25400 #else
   25401 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
   25402 #endif
   25403 
   25404   { "write",        (sqlite3_syscall_ptr)write,      0  },
   25405 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   25406 
   25407 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   25408   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   25409 #else
   25410   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   25411 #endif
   25412 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   25413                     aSyscall[12].pCurrent)
   25414 
   25415 #if defined(USE_PREAD64)
   25416   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
   25417 #else
   25418   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
   25419 #endif
   25420 #ifdef ANDROID
   25421 // Bionic defines pwrite64 using off64_t rather than off_t.
   25422 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
   25423                     aSyscall[13].pCurrent)
   25424 #else
   25425 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
   25426                     aSyscall[13].pCurrent)
   25427 #endif
   25428 
   25429 #if SQLITE_ENABLE_LOCKING_STYLE
   25430   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
   25431 #else
   25432   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
   25433 #endif
   25434 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
   25435 
   25436 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   25437   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
   25438 #else
   25439   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
   25440 #endif
   25441 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
   25442 
   25443   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   25444 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   25445 
   25446   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   25447 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   25448 
   25449   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
   25450 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
   25451 
   25452   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
   25453 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
   25454 
   25455   { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
   25456 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
   25457 
   25458   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
   25459 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
   25460 
   25461 }; /* End of the overrideable system calls */
   25462 
   25463 /*
   25464 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   25465 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   25466 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   25467 ** system call named zName.
   25468 */
   25469 static int unixSetSystemCall(
   25470   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   25471   const char *zName,            /* Name of system call to override */
   25472   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   25473 ){
   25474   unsigned int i;
   25475   int rc = SQLITE_NOTFOUND;
   25476 
   25477   UNUSED_PARAMETER(pNotUsed);
   25478   if( zName==0 ){
   25479     /* If no zName is given, restore all system calls to their default
   25480     ** settings and return NULL
   25481     */
   25482     rc = SQLITE_OK;
   25483     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25484       if( aSyscall[i].pDefault ){
   25485         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   25486       }
   25487     }
   25488   }else{
   25489     /* If zName is specified, operate on only the one system call
   25490     ** specified.
   25491     */
   25492     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25493       if( strcmp(zName, aSyscall[i].zName)==0 ){
   25494         if( aSyscall[i].pDefault==0 ){
   25495           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   25496         }
   25497         rc = SQLITE_OK;
   25498         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   25499         aSyscall[i].pCurrent = pNewFunc;
   25500         break;
   25501       }
   25502     }
   25503   }
   25504   return rc;
   25505 }
   25506 
   25507 /*
   25508 ** Return the value of a system call.  Return NULL if zName is not a
   25509 ** recognized system call name.  NULL is also returned if the system call
   25510 ** is currently undefined.
   25511 */
   25512 static sqlite3_syscall_ptr unixGetSystemCall(
   25513   sqlite3_vfs *pNotUsed,
   25514   const char *zName
   25515 ){
   25516   unsigned int i;
   25517 
   25518   UNUSED_PARAMETER(pNotUsed);
   25519   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25520     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   25521   }
   25522   return 0;
   25523 }
   25524 
   25525 /*
   25526 ** Return the name of the first system call after zName.  If zName==NULL
   25527 ** then return the name of the first system call.  Return NULL if zName
   25528 ** is the last system call or if zName is not the name of a valid
   25529 ** system call.
   25530 */
   25531 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
   25532   int i = -1;
   25533 
   25534   UNUSED_PARAMETER(p);
   25535   if( zName ){
   25536     for(i=0; i<ArraySize(aSyscall)-1; i++){
   25537       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   25538     }
   25539   }
   25540   for(i++; i<ArraySize(aSyscall); i++){
   25541     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   25542   }
   25543   return 0;
   25544 }
   25545 
   25546 /*
   25547 ** Invoke open().  Do so multiple times, until it either succeeds or
   25548 ** files for some reason other than EINTR.
   25549 **
   25550 ** If the file creation mode "m" is 0 then set it to the default for
   25551 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
   25552 ** 0644) as modified by the system umask.  If m is not 0, then
   25553 ** make the file creation mode be exactly m ignoring the umask.
   25554 **
   25555 ** The m parameter will be non-zero only when creating -wal, -journal,
   25556 ** and -shm files.  We want those files to have *exactly* the same
   25557 ** permissions as their original database, unadulterated by the umask.
   25558 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
   25559 ** transaction crashes and leaves behind hot journals, then any
   25560 ** process that is able to write to the database will also be able to
   25561 ** recover the hot journals.
   25562 */
   25563 static int robust_open(const char *z, int f, mode_t m){
   25564   int rc;
   25565   mode_t m2;
   25566   mode_t origM = 0;
   25567   if( m==0 ){
   25568     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
   25569   }else{
   25570     m2 = m;
   25571     origM = osUmask(0);
   25572   }
   25573   do{ rc = osOpen(z,f,m2); }while( rc<0 && errno==EINTR );
   25574   if( m ){
   25575     osUmask(origM);
   25576   }
   25577   return rc;
   25578 }
   25579 
   25580 /*
   25581 ** Helper functions to obtain and relinquish the global mutex. The
   25582 ** global mutex is used to protect the unixInodeInfo and
   25583 ** vxworksFileId objects used by this file, all of which may be
   25584 ** shared by multiple threads.
   25585 **
   25586 ** Function unixMutexHeld() is used to assert() that the global mutex
   25587 ** is held when required. This function is only used as part of assert()
   25588 ** statements. e.g.
   25589 **
   25590 **   unixEnterMutex()
   25591 **     assert( unixMutexHeld() );
   25592 **   unixEnterLeave()
   25593 */
   25594 static void unixEnterMutex(void){
   25595   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25596 }
   25597 static void unixLeaveMutex(void){
   25598   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25599 }
   25600 #ifdef SQLITE_DEBUG
   25601 static int unixMutexHeld(void) {
   25602   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25603 }
   25604 #endif
   25605 
   25606 
   25607 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   25608 /*
   25609 ** Helper function for printing out trace information from debugging
   25610 ** binaries. This returns the string represetation of the supplied
   25611 ** integer lock-type.
   25612 */
   25613 static const char *azFileLock(int eFileLock){
   25614   switch( eFileLock ){
   25615     case NO_LOCK: return "NONE";
   25616     case SHARED_LOCK: return "SHARED";
   25617     case RESERVED_LOCK: return "RESERVED";
   25618     case PENDING_LOCK: return "PENDING";
   25619     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   25620   }
   25621   return "ERROR";
   25622 }
   25623 #endif
   25624 
   25625 #ifdef SQLITE_LOCK_TRACE
   25626 /*
   25627 ** Print out information about all locking operations.
   25628 **
   25629 ** This routine is used for troubleshooting locks on multithreaded
   25630 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   25631 ** command-line option on the compiler.  This code is normally
   25632 ** turned off.
   25633 */
   25634 static int lockTrace(int fd, int op, struct flock *p){
   25635   char *zOpName, *zType;
   25636   int s;
   25637   int savedErrno;
   25638   if( op==F_GETLK ){
   25639     zOpName = "GETLK";
   25640   }else if( op==F_SETLK ){
   25641     zOpName = "SETLK";
   25642   }else{
   25643     s = osFcntl(fd, op, p);
   25644     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   25645     return s;
   25646   }
   25647   if( p->l_type==F_RDLCK ){
   25648     zType = "RDLCK";
   25649   }else if( p->l_type==F_WRLCK ){
   25650     zType = "WRLCK";
   25651   }else if( p->l_type==F_UNLCK ){
   25652     zType = "UNLCK";
   25653   }else{
   25654     assert( 0 );
   25655   }
   25656   assert( p->l_whence==SEEK_SET );
   25657   s = osFcntl(fd, op, p);
   25658   savedErrno = errno;
   25659   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   25660      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   25661      (int)p->l_pid, s);
   25662   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   25663     struct flock l2;
   25664     l2 = *p;
   25665     osFcntl(fd, F_GETLK, &l2);
   25666     if( l2.l_type==F_RDLCK ){
   25667       zType = "RDLCK";
   25668     }else if( l2.l_type==F_WRLCK ){
   25669       zType = "WRLCK";
   25670     }else if( l2.l_type==F_UNLCK ){
   25671       zType = "UNLCK";
   25672     }else{
   25673       assert( 0 );
   25674     }
   25675     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   25676        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   25677   }
   25678   errno = savedErrno;
   25679   return s;
   25680 }
   25681 #undef osFcntl
   25682 #define osFcntl lockTrace
   25683 #endif /* SQLITE_LOCK_TRACE */
   25684 
   25685 /*
   25686 ** Retry ftruncate() calls that fail due to EINTR
   25687 */
   25688 static int robust_ftruncate(int h, sqlite3_int64 sz){
   25689   int rc;
   25690   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
   25691   return rc;
   25692 }
   25693 
   25694 /*
   25695 ** This routine translates a standard POSIX errno code into something
   25696 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   25697 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   25698 ** and a variety of "please close the file descriptor NOW" errors into
   25699 ** SQLITE_IOERR
   25700 **
   25701 ** Errors during initialization of locks, or file system support for locks,
   25702 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   25703 */
   25704 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   25705   switch (posixError) {
   25706 #if 0
   25707   /* At one point this code was not commented out. In theory, this branch
   25708   ** should never be hit, as this function should only be called after
   25709   ** a locking-related function (i.e. fcntl()) has returned non-zero with
   25710   ** the value of errno as the first argument. Since a system call has failed,
   25711   ** errno should be non-zero.
   25712   **
   25713   ** Despite this, if errno really is zero, we still don't want to return
   25714   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
   25715   ** propagated back to the caller. Commenting this branch out means errno==0
   25716   ** will be handled by the "default:" case below.
   25717   */
   25718   case 0:
   25719     return SQLITE_OK;
   25720 #endif
   25721 
   25722   case EAGAIN:
   25723   case ETIMEDOUT:
   25724   case EBUSY:
   25725   case EINTR:
   25726   case ENOLCK:
   25727     /* random NFS retry error, unless during file system support
   25728      * introspection, in which it actually means what it says */
   25729     return SQLITE_BUSY;
   25730 
   25731   case EACCES:
   25732     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   25733     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   25734 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   25735 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   25736 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   25737       return SQLITE_BUSY;
   25738     }
   25739     /* else fall through */
   25740   case EPERM:
   25741     return SQLITE_PERM;
   25742 
   25743   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
   25744   ** this module never makes such a call. And the code in SQLite itself
   25745   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
   25746   ** this case is also commented out. If the system does set errno to EDEADLK,
   25747   ** the default SQLITE_IOERR_XXX code will be returned. */
   25748 #if 0
   25749   case EDEADLK:
   25750     return SQLITE_IOERR_BLOCKED;
   25751 #endif
   25752 
   25753 #if EOPNOTSUPP!=ENOTSUP
   25754   case EOPNOTSUPP:
   25755     /* something went terribly awry, unless during file system support
   25756      * introspection, in which it actually means what it says */
   25757 #endif
   25758 #ifdef ENOTSUP
   25759   case ENOTSUP:
   25760     /* invalid fd, unless during file system support introspection, in which
   25761      * it actually means what it says */
   25762 #endif
   25763   case EIO:
   25764   case EBADF:
   25765   case EINVAL:
   25766   case ENOTCONN:
   25767   case ENODEV:
   25768   case ENXIO:
   25769   case ENOENT:
   25770 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
   25771   case ESTALE:
   25772 #endif
   25773   case ENOSYS:
   25774     /* these should force the client to close the file and reconnect */
   25775 
   25776   default:
   25777     return sqliteIOErr;
   25778   }
   25779 }
   25780 
   25781 
   25782 
   25783 /******************************************************************************
   25784 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   25785 **
   25786 ** On most versions of unix, we can get a unique ID for a file by concatenating
   25787 ** the device number and the inode number.  But this does not work on VxWorks.
   25788 ** On VxWorks, a unique file id must be based on the canonical filename.
   25789 **
   25790 ** A pointer to an instance of the following structure can be used as a
   25791 ** unique file ID in VxWorks.  Each instance of this structure contains
   25792 ** a copy of the canonical filename.  There is also a reference count.
   25793 ** The structure is reclaimed when the number of pointers to it drops to
   25794 ** zero.
   25795 **
   25796 ** There are never very many files open at one time and lookups are not
   25797 ** a performance-critical path, so it is sufficient to put these
   25798 ** structures on a linked list.
   25799 */
   25800 struct vxworksFileId {
   25801   struct vxworksFileId *pNext;  /* Next in a list of them all */
   25802   int nRef;                     /* Number of references to this one */
   25803   int nName;                    /* Length of the zCanonicalName[] string */
   25804   char *zCanonicalName;         /* Canonical filename */
   25805 };
   25806 
   25807 #if OS_VXWORKS
   25808 /*
   25809 ** All unique filenames are held on a linked list headed by this
   25810 ** variable:
   25811 */
   25812 static struct vxworksFileId *vxworksFileList = 0;
   25813 
   25814 /*
   25815 ** Simplify a filename into its canonical form
   25816 ** by making the following changes:
   25817 **
   25818 **  * removing any trailing and duplicate /
   25819 **  * convert /./ into just /
   25820 **  * convert /A/../ where A is any simple name into just /
   25821 **
   25822 ** Changes are made in-place.  Return the new name length.
   25823 **
   25824 ** The original filename is in z[0..n-1].  Return the number of
   25825 ** characters in the simplified name.
   25826 */
   25827 static int vxworksSimplifyName(char *z, int n){
   25828   int i, j;
   25829   while( n>1 && z[n-1]=='/' ){ n--; }
   25830   for(i=j=0; i<n; i++){
   25831     if( z[i]=='/' ){
   25832       if( z[i+1]=='/' ) continue;
   25833       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   25834         i += 1;
   25835         continue;
   25836       }
   25837       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   25838         while( j>0 && z[j-1]!='/' ){ j--; }
   25839         if( j>0 ){ j--; }
   25840         i += 2;
   25841         continue;
   25842       }
   25843     }
   25844     z[j++] = z[i];
   25845   }
   25846   z[j] = 0;
   25847   return j;
   25848 }
   25849 
   25850 /*
   25851 ** Find a unique file ID for the given absolute pathname.  Return
   25852 ** a pointer to the vxworksFileId object.  This pointer is the unique
   25853 ** file ID.
   25854 **
   25855 ** The nRef field of the vxworksFileId object is incremented before
   25856 ** the object is returned.  A new vxworksFileId object is created
   25857 ** and added to the global list if necessary.
   25858 **
   25859 ** If a memory allocation error occurs, return NULL.
   25860 */
   25861 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   25862   struct vxworksFileId *pNew;         /* search key and new file ID */
   25863   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   25864   int n;                              /* Length of zAbsoluteName string */
   25865 
   25866   assert( zAbsoluteName[0]=='/' );
   25867   n = (int)strlen(zAbsoluteName);
   25868   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   25869   if( pNew==0 ) return 0;
   25870   pNew->zCanonicalName = (char*)&pNew[1];
   25871   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   25872   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   25873 
   25874   /* Search for an existing entry that matching the canonical name.
   25875   ** If found, increment the reference count and return a pointer to
   25876   ** the existing file ID.
   25877   */
   25878   unixEnterMutex();
   25879   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   25880     if( pCandidate->nName==n
   25881      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   25882     ){
   25883        sqlite3_free(pNew);
   25884        pCandidate->nRef++;
   25885        unixLeaveMutex();
   25886        return pCandidate;
   25887     }
   25888   }
   25889 
   25890   /* No match was found.  We will make a new file ID */
   25891   pNew->nRef = 1;
   25892   pNew->nName = n;
   25893   pNew->pNext = vxworksFileList;
   25894   vxworksFileList = pNew;
   25895   unixLeaveMutex();
   25896   return pNew;
   25897 }
   25898 
   25899 /*
   25900 ** Decrement the reference count on a vxworksFileId object.  Free
   25901 ** the object when the reference count reaches zero.
   25902 */
   25903 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   25904   unixEnterMutex();
   25905   assert( pId->nRef>0 );
   25906   pId->nRef--;
   25907   if( pId->nRef==0 ){
   25908     struct vxworksFileId **pp;
   25909     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   25910     assert( *pp==pId );
   25911     *pp = pId->pNext;
   25912     sqlite3_free(pId);
   25913   }
   25914   unixLeaveMutex();
   25915 }
   25916 #endif /* OS_VXWORKS */
   25917 /*************** End of Unique File ID Utility Used By VxWorks ****************
   25918 ******************************************************************************/
   25919 
   25920 
   25921 /******************************************************************************
   25922 *************************** Posix Advisory Locking ****************************
   25923 **
   25924 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   25925 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   25926 ** sets or clears a lock, that operation overrides any prior locks set
   25927 ** by the same process.  It does not explicitly say so, but this implies
   25928 ** that it overrides locks set by the same process using a different
   25929 ** file descriptor.  Consider this test case:
   25930 **
   25931 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   25932 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   25933 **
   25934 ** Suppose ./file1 and ./file2 are really the same file (because
   25935 ** one is a hard or symbolic link to the other) then if you set
   25936 ** an exclusive lock on fd1, then try to get an exclusive lock
   25937 ** on fd2, it works.  I would have expected the second lock to
   25938 ** fail since there was already a lock on the file due to fd1.
   25939 ** But not so.  Since both locks came from the same process, the
   25940 ** second overrides the first, even though they were on different
   25941 ** file descriptors opened on different file names.
   25942 **
   25943 ** This means that we cannot use POSIX locks to synchronize file access
   25944 ** among competing threads of the same process.  POSIX locks will work fine
   25945 ** to synchronize access for threads in separate processes, but not
   25946 ** threads within the same process.
   25947 **
   25948 ** To work around the problem, SQLite has to manage file locks internally
   25949 ** on its own.  Whenever a new database is opened, we have to find the
   25950 ** specific inode of the database file (the inode is determined by the
   25951 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   25952 ** and check for locks already existing on that inode.  When locks are
   25953 ** created or removed, we have to look at our own internal record of the
   25954 ** locks to see if another thread has previously set a lock on that same
   25955 ** inode.
   25956 **
   25957 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   25958 ** For VxWorks, we have to use the alternative unique ID system based on
   25959 ** canonical filename and implemented in the previous division.)
   25960 **
   25961 ** The sqlite3_file structure for POSIX is no longer just an integer file
   25962 ** descriptor.  It is now a structure that holds the integer file
   25963 ** descriptor and a pointer to a structure that describes the internal
   25964 ** locks on the corresponding inode.  There is one locking structure
   25965 ** per inode, so if the same inode is opened twice, both unixFile structures
   25966 ** point to the same locking structure.  The locking structure keeps
   25967 ** a reference count (so we will know when to delete it) and a "cnt"
   25968 ** field that tells us its internal lock status.  cnt==0 means the
   25969 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   25970 ** cnt>0 means there are cnt shared locks on the file.
   25971 **
   25972 ** Any attempt to lock or unlock a file first checks the locking
   25973 ** structure.  The fcntl() system call is only invoked to set a
   25974 ** POSIX lock if the internal lock structure transitions between
   25975 ** a locked and an unlocked state.
   25976 **
   25977 ** But wait:  there are yet more problems with POSIX advisory locks.
   25978 **
   25979 ** If you close a file descriptor that points to a file that has locks,
   25980 ** all locks on that file that are owned by the current process are
   25981 ** released.  To work around this problem, each unixInodeInfo object
   25982 ** maintains a count of the number of pending locks on tha inode.
   25983 ** When an attempt is made to close an unixFile, if there are
   25984 ** other unixFile open on the same inode that are holding locks, the call
   25985 ** to close() the file descriptor is deferred until all of the locks clear.
   25986 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   25987 ** be closed and that list is walked (and cleared) when the last lock
   25988 ** clears.
   25989 **
   25990 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   25991 **
   25992 ** Many older versions of linux use the LinuxThreads library which is
   25993 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   25994 ** A cannot be modified or overridden by a different thread B.
   25995 ** Only thread A can modify the lock.  Locking behavior is correct
   25996 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   25997 ** on linux - with NPTL a lock created by thread A can override locks
   25998 ** in thread B.  But there is no way to know at compile-time which
   25999 ** threading library is being used.  So there is no way to know at
   26000 ** compile-time whether or not thread A can override locks on thread B.
   26001 ** One has to do a run-time check to discover the behavior of the
   26002 ** current process.
   26003 **
   26004 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   26005 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   26006 ** LinuxThreads provided that (1) there is no more than one connection
   26007 ** per database file in the same process and (2) database connections
   26008 ** do not move across threads.
   26009 */
   26010 
   26011 /*
   26012 ** An instance of the following structure serves as the key used
   26013 ** to locate a particular unixInodeInfo object.
   26014 */
   26015 struct unixFileId {
   26016   dev_t dev;                  /* Device number */
   26017 #if OS_VXWORKS
   26018   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   26019 #else
   26020   ino_t ino;                  /* Inode number */
   26021 #endif
   26022 };
   26023 
   26024 /*
   26025 ** An instance of the following structure is allocated for each open
   26026 ** inode.  Or, on LinuxThreads, there is one of these structures for
   26027 ** each inode opened by each thread.
   26028 **
   26029 ** A single inode can have multiple file descriptors, so each unixFile
   26030 ** structure contains a pointer to an instance of this object and this
   26031 ** object keeps a count of the number of unixFile pointing to it.
   26032 */
   26033 struct unixInodeInfo {
   26034   struct unixFileId fileId;       /* The lookup key */
   26035   int nShared;                    /* Number of SHARED locks held */
   26036   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   26037   unsigned char bProcessLock;     /* An exclusive process lock is held */
   26038   int nRef;                       /* Number of pointers to this structure */
   26039   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   26040   int nLock;                      /* Number of outstanding file locks */
   26041   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   26042   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   26043   unixInodeInfo *pPrev;           /*    .... doubly linked */
   26044 #if SQLITE_ENABLE_LOCKING_STYLE
   26045   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   26046 #endif
   26047 #if OS_VXWORKS
   26048   sem_t *pSem;                    /* Named POSIX semaphore */
   26049   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   26050 #endif
   26051 };
   26052 
   26053 /*
   26054 ** A lists of all unixInodeInfo objects.
   26055 */
   26056 static unixInodeInfo *inodeList = 0;
   26057 
   26058 /*
   26059 **
   26060 ** This function - unixLogError_x(), is only ever called via the macro
   26061 ** unixLogError().
   26062 **
   26063 ** It is invoked after an error occurs in an OS function and errno has been
   26064 ** set. It logs a message using sqlite3_log() containing the current value of
   26065 ** errno and, if possible, the human-readable equivalent from strerror() or
   26066 ** strerror_r().
   26067 **
   26068 ** The first argument passed to the macro should be the error code that
   26069 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   26070 ** The two subsequent arguments should be the name of the OS function that
   26071 ** failed (e.g. "unlink", "open") and the the associated file-system path,
   26072 ** if any.
   26073 */
   26074 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
   26075 static int unixLogErrorAtLine(
   26076   int errcode,                    /* SQLite error code */
   26077   const char *zFunc,              /* Name of OS function that failed */
   26078   const char *zPath,              /* File path associated with error */
   26079   int iLine                       /* Source line number where error occurred */
   26080 ){
   26081   char *zErr;                     /* Message from strerror() or equivalent */
   26082   int iErrno = errno;             /* Saved syscall error number */
   26083 
   26084   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   26085   ** the strerror() function to obtain the human-readable error message
   26086   ** equivalent to errno. Otherwise, use strerror_r().
   26087   */
   26088 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   26089   char aErr[80];
   26090   memset(aErr, 0, sizeof(aErr));
   26091   zErr = aErr;
   26092 
   26093   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   26094   ** assume that the system provides the the GNU version of strerror_r() that
   26095   ** returns a pointer to a buffer containing the error message. That pointer
   26096   ** may point to aErr[], or it may point to some static storage somewhere.
   26097   ** Otherwise, assume that the system provides the POSIX version of
   26098   ** strerror_r(), which always writes an error message into aErr[].
   26099   **
   26100   ** If the code incorrectly assumes that it is the POSIX version that is
   26101   ** available, the error message will often be an empty string. Not a
   26102   ** huge problem. Incorrectly concluding that the GNU version is available
   26103   ** could lead to a segfault though.
   26104   */
   26105 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   26106   zErr =
   26107 # endif
   26108   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   26109 
   26110 #elif SQLITE_THREADSAFE
   26111   /* This is a threadsafe build, but strerror_r() is not available. */
   26112   zErr = "";
   26113 #else
   26114   /* Non-threadsafe build, use strerror(). */
   26115   zErr = strerror(iErrno);
   26116 #endif
   26117 
   26118   assert( errcode!=SQLITE_OK );
   26119   if( zPath==0 ) zPath = "";
   26120   sqlite3_log(errcode,
   26121       "os_unix.c:%d: (%d) %s(%s) - %s",
   26122       iLine, iErrno, zFunc, zPath, zErr
   26123   );
   26124 
   26125   return errcode;
   26126 }
   26127 
   26128 /*
   26129 ** Close a file descriptor.
   26130 **
   26131 ** We assume that close() almost always works, since it is only in a
   26132 ** very sick application or on a very sick platform that it might fail.
   26133 ** If it does fail, simply leak the file descriptor, but do log the
   26134 ** error.
   26135 **
   26136 ** Note that it is not safe to retry close() after EINTR since the
   26137 ** file descriptor might have already been reused by another thread.
   26138 ** So we don't even try to recover from an EINTR.  Just log the error
   26139 ** and move on.
   26140 */
   26141 static void robust_close(unixFile *pFile, int h, int lineno){
   26142   if( osClose(h) ){
   26143     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   26144                        pFile ? pFile->zPath : 0, lineno);
   26145   }
   26146 }
   26147 
   26148 /*
   26149 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   26150 */
   26151 static void closePendingFds(unixFile *pFile){
   26152   unixInodeInfo *pInode = pFile->pInode;
   26153   UnixUnusedFd *p;
   26154   UnixUnusedFd *pNext;
   26155   for(p=pInode->pUnused; p; p=pNext){
   26156     pNext = p->pNext;
   26157     robust_close(pFile, p->fd, __LINE__);
   26158     sqlite3_free(p);
   26159   }
   26160   pInode->pUnused = 0;
   26161 }
   26162 
   26163 /*
   26164 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   26165 **
   26166 ** The mutex entered using the unixEnterMutex() function must be held
   26167 ** when this function is called.
   26168 */
   26169 static void releaseInodeInfo(unixFile *pFile){
   26170   unixInodeInfo *pInode = pFile->pInode;
   26171   assert( unixMutexHeld() );
   26172   if( ALWAYS(pInode) ){
   26173     pInode->nRef--;
   26174     if( pInode->nRef==0 ){
   26175       assert( pInode->pShmNode==0 );
   26176       closePendingFds(pFile);
   26177       if( pInode->pPrev ){
   26178         assert( pInode->pPrev->pNext==pInode );
   26179         pInode->pPrev->pNext = pInode->pNext;
   26180       }else{
   26181         assert( inodeList==pInode );
   26182         inodeList = pInode->pNext;
   26183       }
   26184       if( pInode->pNext ){
   26185         assert( pInode->pNext->pPrev==pInode );
   26186         pInode->pNext->pPrev = pInode->pPrev;
   26187       }
   26188       sqlite3_free(pInode);
   26189     }
   26190   }
   26191 }
   26192 
   26193 /*
   26194 ** Given a file descriptor, locate the unixInodeInfo object that
   26195 ** describes that file descriptor.  Create a new one if necessary.  The
   26196 ** return value might be uninitialized if an error occurs.
   26197 **
   26198 ** The mutex entered using the unixEnterMutex() function must be held
   26199 ** when this function is called.
   26200 **
   26201 ** Return an appropriate error code.
   26202 */
   26203 static int findInodeInfo(
   26204   unixFile *pFile,               /* Unix file with file desc used in the key */
   26205   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   26206 ){
   26207   int rc;                        /* System call return code */
   26208   int fd;                        /* The file descriptor for pFile */
   26209   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   26210   struct stat statbuf;           /* Low-level file information */
   26211   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   26212 
   26213   assert( unixMutexHeld() );
   26214 
   26215   /* Get low-level information about the file that we can used to
   26216   ** create a unique name for the file.
   26217   */
   26218   fd = pFile->h;
   26219   rc = osFstat(fd, &statbuf);
   26220   if( rc!=0 ){
   26221     pFile->lastErrno = errno;
   26222 #ifdef EOVERFLOW
   26223     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   26224 #endif
   26225     return SQLITE_IOERR;
   26226   }
   26227 
   26228 #ifdef __APPLE__
   26229   /* On OS X on an msdos filesystem, the inode number is reported
   26230   ** incorrectly for zero-size files.  See ticket #3260.  To work
   26231   ** around this problem (we consider it a bug in OS X, not SQLite)
   26232   ** we always increase the file size to 1 by writing a single byte
   26233   ** prior to accessing the inode number.  The one byte written is
   26234   ** an ASCII 'S' character which also happens to be the first byte
   26235   ** in the header of every SQLite database.  In this way, if there
   26236   ** is a race condition such that another thread has already populated
   26237   ** the first page of the database, no damage is done.
   26238   */
   26239   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   26240     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   26241     if( rc!=1 ){
   26242       pFile->lastErrno = errno;
   26243       return SQLITE_IOERR;
   26244     }
   26245     rc = osFstat(fd, &statbuf);
   26246     if( rc!=0 ){
   26247       pFile->lastErrno = errno;
   26248       return SQLITE_IOERR;
   26249     }
   26250   }
   26251 #endif
   26252 
   26253   memset(&fileId, 0, sizeof(fileId));
   26254   fileId.dev = statbuf.st_dev;
   26255 #if OS_VXWORKS
   26256   fileId.pId = pFile->pId;
   26257 #else
   26258   fileId.ino = statbuf.st_ino;
   26259 #endif
   26260   pInode = inodeList;
   26261   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   26262     pInode = pInode->pNext;
   26263   }
   26264   if( pInode==0 ){
   26265     pInode = sqlite3_malloc( sizeof(*pInode) );
   26266     if( pInode==0 ){
   26267       return SQLITE_NOMEM;
   26268     }
   26269     memset(pInode, 0, sizeof(*pInode));
   26270     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   26271     pInode->nRef = 1;
   26272     pInode->pNext = inodeList;
   26273     pInode->pPrev = 0;
   26274     if( inodeList ) inodeList->pPrev = pInode;
   26275     inodeList = pInode;
   26276   }else{
   26277     pInode->nRef++;
   26278   }
   26279   *ppInode = pInode;
   26280   return SQLITE_OK;
   26281 }
   26282 
   26283 
   26284 /*
   26285 ** This routine checks if there is a RESERVED lock held on the specified
   26286 ** file by this or any other process. If such a lock is held, set *pResOut
   26287 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26288 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26289 */
   26290 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   26291   int rc = SQLITE_OK;
   26292   int reserved = 0;
   26293   unixFile *pFile = (unixFile*)id;
   26294 
   26295   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26296 
   26297   assert( pFile );
   26298   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   26299 
   26300   /* Check if a thread in this process holds such a lock */
   26301   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   26302     reserved = 1;
   26303   }
   26304 
   26305   /* Otherwise see if some other process holds it.
   26306   */
   26307 #ifndef __DJGPP__
   26308   if( !reserved && !pFile->pInode->bProcessLock ){
   26309     struct flock lock;
   26310     lock.l_whence = SEEK_SET;
   26311     lock.l_start = RESERVED_BYTE;
   26312     lock.l_len = 1;
   26313     lock.l_type = F_WRLCK;
   26314     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   26315       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   26316       pFile->lastErrno = errno;
   26317     } else if( lock.l_type!=F_UNLCK ){
   26318       reserved = 1;
   26319     }
   26320   }
   26321 #endif
   26322 
   26323   unixLeaveMutex();
   26324   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   26325 
   26326   *pResOut = reserved;
   26327   return rc;
   26328 }
   26329 
   26330 /*
   26331 ** Attempt to set a system-lock on the file pFile.  The lock is
   26332 ** described by pLock.
   26333 **
   26334 ** If the pFile was opened read/write from unix-excl, then the only lock
   26335 ** ever obtained is an exclusive lock, and it is obtained exactly once
   26336 ** the first time any lock is attempted.  All subsequent system locking
   26337 ** operations become no-ops.  Locking operations still happen internally,
   26338 ** in order to coordinate access between separate database connections
   26339 ** within this process, but all of that is handled in memory and the
   26340 ** operating system does not participate.
   26341 **
   26342 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   26343 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   26344 ** and is read-only.
   26345 **
   26346 ** Zero is returned if the call completes successfully, or -1 if a call
   26347 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   26348 */
   26349 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   26350   int rc;
   26351   unixInodeInfo *pInode = pFile->pInode;
   26352   assert( unixMutexHeld() );
   26353   assert( pInode!=0 );
   26354   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
   26355    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
   26356   ){
   26357     if( pInode->bProcessLock==0 ){
   26358       struct flock lock;
   26359       assert( pInode->nLock==0 );
   26360       lock.l_whence = SEEK_SET;
   26361       lock.l_start = SHARED_FIRST;
   26362       lock.l_len = SHARED_SIZE;
   26363       lock.l_type = F_WRLCK;
   26364       rc = osFcntl(pFile->h, F_SETLK, &lock);
   26365       if( rc<0 ) return rc;
   26366       pInode->bProcessLock = 1;
   26367       pInode->nLock++;
   26368     }else{
   26369       rc = 0;
   26370     }
   26371   }else{
   26372     rc = osFcntl(pFile->h, F_SETLK, pLock);
   26373   }
   26374   return rc;
   26375 }
   26376 
   26377 /*
   26378 ** Lock the file with the lock specified by parameter eFileLock - one
   26379 ** of the following:
   26380 **
   26381 **     (1) SHARED_LOCK
   26382 **     (2) RESERVED_LOCK
   26383 **     (3) PENDING_LOCK
   26384 **     (4) EXCLUSIVE_LOCK
   26385 **
   26386 ** Sometimes when requesting one lock state, additional lock states
   26387 ** are inserted in between.  The locking might fail on one of the later
   26388 ** transitions leaving the lock state different from what it started but
   26389 ** still short of its goal.  The following chart shows the allowed
   26390 ** transitions and the inserted intermediate states:
   26391 **
   26392 **    UNLOCKED -> SHARED
   26393 **    SHARED -> RESERVED
   26394 **    SHARED -> (PENDING) -> EXCLUSIVE
   26395 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26396 **    PENDING -> EXCLUSIVE
   26397 **
   26398 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26399 ** routine to lower a locking level.
   26400 */
   26401 static int unixLock(sqlite3_file *id, int eFileLock){
   26402   /* The following describes the implementation of the various locks and
   26403   ** lock transitions in terms of the POSIX advisory shared and exclusive
   26404   ** lock primitives (called read-locks and write-locks below, to avoid
   26405   ** confusion with SQLite lock names). The algorithms are complicated
   26406   ** slightly in order to be compatible with windows systems simultaneously
   26407   ** accessing the same database file, in case that is ever required.
   26408   **
   26409   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   26410   ** byte', each single bytes at well known offsets, and the 'shared byte
   26411   ** range', a range of 510 bytes at a well known offset.
   26412   **
   26413   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   26414   ** byte'.  If this is successful, a random byte from the 'shared byte
   26415   ** range' is read-locked and the lock on the 'pending byte' released.
   26416   **
   26417   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   26418   ** A RESERVED lock is implemented by grabbing a write-lock on the
   26419   ** 'reserved byte'.
   26420   **
   26421   ** A process may only obtain a PENDING lock after it has obtained a
   26422   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   26423   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   26424   ** obtained, but existing SHARED locks are allowed to persist. A process
   26425   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   26426   ** This property is used by the algorithm for rolling back a journal file
   26427   ** after a crash.
   26428   **
   26429   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   26430   ** implemented by obtaining a write-lock on the entire 'shared byte
   26431   ** range'. Since all other locks require a read-lock on one of the bytes
   26432   ** within this range, this ensures that no other locks are held on the
   26433   ** database.
   26434   **
   26435   ** The reason a single byte cannot be used instead of the 'shared byte
   26436   ** range' is that some versions of windows do not support read-locks. By
   26437   ** locking a random byte from a range, concurrent SHARED locks may exist
   26438   ** even if the locking primitive used is always a write-lock.
   26439   */
   26440   int rc = SQLITE_OK;
   26441   unixFile *pFile = (unixFile*)id;
   26442   unixInodeInfo *pInode;
   26443   struct flock lock;
   26444   int tErrno = 0;
   26445 
   26446   assert( pFile );
   26447   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   26448       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   26449       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
   26450 
   26451   /* If there is already a lock of this type or more restrictive on the
   26452   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   26453   ** unixEnterMutex() hasn't been called yet.
   26454   */
   26455   if( pFile->eFileLock>=eFileLock ){
   26456     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   26457             azFileLock(eFileLock)));
   26458     return SQLITE_OK;
   26459   }
   26460 
   26461   /* Make sure the locking sequence is correct.
   26462   **  (1) We never move from unlocked to anything higher than shared lock.
   26463   **  (2) SQLite never explicitly requests a pendig lock.
   26464   **  (3) A shared lock is always held when a reserve lock is requested.
   26465   */
   26466   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   26467   assert( eFileLock!=PENDING_LOCK );
   26468   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   26469 
   26470   /* This mutex is needed because pFile->pInode is shared across threads
   26471   */
   26472   unixEnterMutex();
   26473   pInode = pFile->pInode;
   26474 
   26475   /* If some thread using this PID has a lock via a different unixFile*
   26476   ** handle that precludes the requested lock, return BUSY.
   26477   */
   26478   if( (pFile->eFileLock!=pInode->eFileLock &&
   26479           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   26480   ){
   26481     rc = SQLITE_BUSY;
   26482     goto end_lock;
   26483   }
   26484 
   26485   /* If a SHARED lock is requested, and some thread using this PID already
   26486   ** has a SHARED or RESERVED lock, then increment reference counts and
   26487   ** return SQLITE_OK.
   26488   */
   26489   if( eFileLock==SHARED_LOCK &&
   26490       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   26491     assert( eFileLock==SHARED_LOCK );
   26492     assert( pFile->eFileLock==0 );
   26493     assert( pInode->nShared>0 );
   26494     pFile->eFileLock = SHARED_LOCK;
   26495     pInode->nShared++;
   26496     pInode->nLock++;
   26497     goto end_lock;
   26498   }
   26499 
   26500 
   26501   /* A PENDING lock is needed before acquiring a SHARED lock and before
   26502   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   26503   ** be released.
   26504   */
   26505   lock.l_len = 1L;
   26506   lock.l_whence = SEEK_SET;
   26507   if( eFileLock==SHARED_LOCK
   26508       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   26509   ){
   26510     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   26511     lock.l_start = PENDING_BYTE;
   26512     if( unixFileLock(pFile, &lock) ){
   26513       tErrno = errno;
   26514       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26515       if( rc!=SQLITE_BUSY ){
   26516         pFile->lastErrno = tErrno;
   26517       }
   26518       goto end_lock;
   26519     }
   26520   }
   26521 
   26522 
   26523   /* If control gets to this point, then actually go ahead and make
   26524   ** operating system calls for the specified lock.
   26525   */
   26526   if( eFileLock==SHARED_LOCK ){
   26527     assert( pInode->nShared==0 );
   26528     assert( pInode->eFileLock==0 );
   26529     assert( rc==SQLITE_OK );
   26530 
   26531     /* Now get the read-lock */
   26532     lock.l_start = SHARED_FIRST;
   26533     lock.l_len = SHARED_SIZE;
   26534     if( unixFileLock(pFile, &lock) ){
   26535       tErrno = errno;
   26536       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26537     }
   26538 
   26539     /* Drop the temporary PENDING lock */
   26540     lock.l_start = PENDING_BYTE;
   26541     lock.l_len = 1L;
   26542     lock.l_type = F_UNLCK;
   26543     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   26544       /* This could happen with a network mount */
   26545       tErrno = errno;
   26546       rc = SQLITE_IOERR_UNLOCK;
   26547     }
   26548 
   26549     if( rc ){
   26550       if( rc!=SQLITE_BUSY ){
   26551         pFile->lastErrno = tErrno;
   26552       }
   26553       goto end_lock;
   26554     }else{
   26555       pFile->eFileLock = SHARED_LOCK;
   26556       pInode->nLock++;
   26557       pInode->nShared = 1;
   26558     }
   26559   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   26560     /* We are trying for an exclusive lock but another thread in this
   26561     ** same process is still holding a shared lock. */
   26562     rc = SQLITE_BUSY;
   26563   }else{
   26564     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   26565     ** assumed that there is a SHARED or greater lock on the file
   26566     ** already.
   26567     */
   26568     assert( 0!=pFile->eFileLock );
   26569     lock.l_type = F_WRLCK;
   26570 
   26571     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   26572     if( eFileLock==RESERVED_LOCK ){
   26573       lock.l_start = RESERVED_BYTE;
   26574       lock.l_len = 1L;
   26575     }else{
   26576       lock.l_start = SHARED_FIRST;
   26577       lock.l_len = SHARED_SIZE;
   26578     }
   26579 
   26580     if( unixFileLock(pFile, &lock) ){
   26581       tErrno = errno;
   26582       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26583       if( rc!=SQLITE_BUSY ){
   26584         pFile->lastErrno = tErrno;
   26585       }
   26586     }
   26587   }
   26588 
   26589 
   26590 #ifndef NDEBUG
   26591   /* Set up the transaction-counter change checking flags when
   26592   ** transitioning from a SHARED to a RESERVED lock.  The change
   26593   ** from SHARED to RESERVED marks the beginning of a normal
   26594   ** write operation (not a hot journal rollback).
   26595   */
   26596   if( rc==SQLITE_OK
   26597    && pFile->eFileLock<=SHARED_LOCK
   26598    && eFileLock==RESERVED_LOCK
   26599   ){
   26600     pFile->transCntrChng = 0;
   26601     pFile->dbUpdate = 0;
   26602     pFile->inNormalWrite = 1;
   26603   }
   26604 #endif
   26605 
   26606 
   26607   if( rc==SQLITE_OK ){
   26608     pFile->eFileLock = eFileLock;
   26609     pInode->eFileLock = eFileLock;
   26610   }else if( eFileLock==EXCLUSIVE_LOCK ){
   26611     pFile->eFileLock = PENDING_LOCK;
   26612     pInode->eFileLock = PENDING_LOCK;
   26613   }
   26614 
   26615 end_lock:
   26616   unixLeaveMutex();
   26617   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   26618       rc==SQLITE_OK ? "ok" : "failed"));
   26619   return rc;
   26620 }
   26621 
   26622 /*
   26623 ** Add the file descriptor used by file handle pFile to the corresponding
   26624 ** pUnused list.
   26625 */
   26626 static void setPendingFd(unixFile *pFile){
   26627   unixInodeInfo *pInode = pFile->pInode;
   26628   UnixUnusedFd *p = pFile->pUnused;
   26629   p->pNext = pInode->pUnused;
   26630   pInode->pUnused = p;
   26631   pFile->h = -1;
   26632   pFile->pUnused = 0;
   26633 }
   26634 
   26635 /*
   26636 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26637 ** must be either NO_LOCK or SHARED_LOCK.
   26638 **
   26639 ** If the locking level of the file descriptor is already at or below
   26640 ** the requested locking level, this routine is a no-op.
   26641 **
   26642 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   26643 ** the byte range is divided into 2 parts and the first part is unlocked then
   26644 ** set to a read lock, then the other part is simply unlocked.  This works
   26645 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   26646 ** remove the write lock on a region when a read lock is set.
   26647 */
   26648 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   26649   unixFile *pFile = (unixFile*)id;
   26650   unixInodeInfo *pInode;
   26651   struct flock lock;
   26652   int rc = SQLITE_OK;
   26653 
   26654   assert( pFile );
   26655   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   26656       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   26657       getpid()));
   26658 
   26659   assert( eFileLock<=SHARED_LOCK );
   26660   if( pFile->eFileLock<=eFileLock ){
   26661     return SQLITE_OK;
   26662   }
   26663   unixEnterMutex();
   26664   pInode = pFile->pInode;
   26665   assert( pInode->nShared!=0 );
   26666   if( pFile->eFileLock>SHARED_LOCK ){
   26667     assert( pInode->eFileLock==pFile->eFileLock );
   26668 
   26669 #ifndef NDEBUG
   26670     /* When reducing a lock such that other processes can start
   26671     ** reading the database file again, make sure that the
   26672     ** transaction counter was updated if any part of the database
   26673     ** file changed.  If the transaction counter is not updated,
   26674     ** other connections to the same file might not realize that
   26675     ** the file has changed and hence might not know to flush their
   26676     ** cache.  The use of a stale cache can lead to database corruption.
   26677     */
   26678     pFile->inNormalWrite = 0;
   26679 #endif
   26680 
   26681     /* downgrading to a shared lock on NFS involves clearing the write lock
   26682     ** before establishing the readlock - to avoid a race condition we downgrade
   26683     ** the lock in 2 blocks, so that part of the range will be covered by a
   26684     ** write lock until the rest is covered by a read lock:
   26685     **  1:   [WWWWW]
   26686     **  2:   [....W]
   26687     **  3:   [RRRRW]
   26688     **  4:   [RRRR.]
   26689     */
   26690     if( eFileLock==SHARED_LOCK ){
   26691 
   26692 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   26693       (void)handleNFSUnlock;
   26694       assert( handleNFSUnlock==0 );
   26695 #endif
   26696 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26697       if( handleNFSUnlock ){
   26698         int tErrno;               /* Error code from system call errors */
   26699         off_t divSize = SHARED_SIZE - 1;
   26700 
   26701         lock.l_type = F_UNLCK;
   26702         lock.l_whence = SEEK_SET;
   26703         lock.l_start = SHARED_FIRST;
   26704         lock.l_len = divSize;
   26705         if( unixFileLock(pFile, &lock)==(-1) ){
   26706           tErrno = errno;
   26707           rc = SQLITE_IOERR_UNLOCK;
   26708           if( IS_LOCK_ERROR(rc) ){
   26709             pFile->lastErrno = tErrno;
   26710           }
   26711           goto end_unlock;
   26712         }
   26713         lock.l_type = F_RDLCK;
   26714         lock.l_whence = SEEK_SET;
   26715         lock.l_start = SHARED_FIRST;
   26716         lock.l_len = divSize;
   26717         if( unixFileLock(pFile, &lock)==(-1) ){
   26718           tErrno = errno;
   26719           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   26720           if( IS_LOCK_ERROR(rc) ){
   26721             pFile->lastErrno = tErrno;
   26722           }
   26723           goto end_unlock;
   26724         }
   26725         lock.l_type = F_UNLCK;
   26726         lock.l_whence = SEEK_SET;
   26727         lock.l_start = SHARED_FIRST+divSize;
   26728         lock.l_len = SHARED_SIZE-divSize;
   26729         if( unixFileLock(pFile, &lock)==(-1) ){
   26730           tErrno = errno;
   26731           rc = SQLITE_IOERR_UNLOCK;
   26732           if( IS_LOCK_ERROR(rc) ){
   26733             pFile->lastErrno = tErrno;
   26734           }
   26735           goto end_unlock;
   26736         }
   26737       }else
   26738 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   26739       {
   26740         lock.l_type = F_RDLCK;
   26741         lock.l_whence = SEEK_SET;
   26742         lock.l_start = SHARED_FIRST;
   26743         lock.l_len = SHARED_SIZE;
   26744         if( unixFileLock(pFile, &lock) ){
   26745           /* In theory, the call to unixFileLock() cannot fail because another
   26746           ** process is holding an incompatible lock. If it does, this
   26747           ** indicates that the other process is not following the locking
   26748           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   26749           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   26750           ** an assert to fail). */
   26751           rc = SQLITE_IOERR_RDLOCK;
   26752           pFile->lastErrno = errno;
   26753           goto end_unlock;
   26754         }
   26755       }
   26756     }
   26757     lock.l_type = F_UNLCK;
   26758     lock.l_whence = SEEK_SET;
   26759     lock.l_start = PENDING_BYTE;
   26760     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   26761     if( unixFileLock(pFile, &lock)==0 ){
   26762       pInode->eFileLock = SHARED_LOCK;
   26763     }else{
   26764       rc = SQLITE_IOERR_UNLOCK;
   26765       pFile->lastErrno = errno;
   26766       goto end_unlock;
   26767     }
   26768   }
   26769   if( eFileLock==NO_LOCK ){
   26770     /* Decrement the shared lock counter.  Release the lock using an
   26771     ** OS call only when all threads in this same process have released
   26772     ** the lock.
   26773     */
   26774     pInode->nShared--;
   26775     if( pInode->nShared==0 ){
   26776       lock.l_type = F_UNLCK;
   26777       lock.l_whence = SEEK_SET;
   26778       lock.l_start = lock.l_len = 0L;
   26779       if( unixFileLock(pFile, &lock)==0 ){
   26780         pInode->eFileLock = NO_LOCK;
   26781       }else{
   26782         rc = SQLITE_IOERR_UNLOCK;
   26783 	pFile->lastErrno = errno;
   26784         pInode->eFileLock = NO_LOCK;
   26785         pFile->eFileLock = NO_LOCK;
   26786       }
   26787     }
   26788 
   26789     /* Decrement the count of locks against this same file.  When the
   26790     ** count reaches zero, close any other file descriptors whose close
   26791     ** was deferred because of outstanding locks.
   26792     */
   26793     pInode->nLock--;
   26794     assert( pInode->nLock>=0 );
   26795     if( pInode->nLock==0 ){
   26796       closePendingFds(pFile);
   26797     }
   26798   }
   26799 
   26800 end_unlock:
   26801   unixLeaveMutex();
   26802   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   26803   return rc;
   26804 }
   26805 
   26806 /*
   26807 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26808 ** must be either NO_LOCK or SHARED_LOCK.
   26809 **
   26810 ** If the locking level of the file descriptor is already at or below
   26811 ** the requested locking level, this routine is a no-op.
   26812 */
   26813 static int unixUnlock(sqlite3_file *id, int eFileLock){
   26814   return posixUnlock(id, eFileLock, 0);
   26815 }
   26816 
   26817 /*
   26818 ** This function performs the parts of the "close file" operation
   26819 ** common to all locking schemes. It closes the directory and file
   26820 ** handles, if they are valid, and sets all fields of the unixFile
   26821 ** structure to 0.
   26822 **
   26823 ** It is *not* necessary to hold the mutex when this routine is called,
   26824 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   26825 ** vxworksReleaseFileId() routine.
   26826 */
   26827 static int closeUnixFile(sqlite3_file *id){
   26828   unixFile *pFile = (unixFile*)id;
   26829   if( pFile->h>=0 ){
   26830     robust_close(pFile, pFile->h, __LINE__);
   26831     pFile->h = -1;
   26832   }
   26833 #if OS_VXWORKS
   26834   if( pFile->pId ){
   26835     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26836       osUnlink(pFile->pId->zCanonicalName);
   26837     }
   26838     vxworksReleaseFileId(pFile->pId);
   26839     pFile->pId = 0;
   26840   }
   26841 #endif
   26842   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   26843   OpenCounter(-1);
   26844   sqlite3_free(pFile->pUnused);
   26845   memset(pFile, 0, sizeof(unixFile));
   26846   return SQLITE_OK;
   26847 }
   26848 
   26849 /*
   26850 ** Close a file.
   26851 */
   26852 static int unixClose(sqlite3_file *id){
   26853   int rc = SQLITE_OK;
   26854   unixFile *pFile = (unixFile *)id;
   26855   unixUnlock(id, NO_LOCK);
   26856   unixEnterMutex();
   26857 
   26858   /* unixFile.pInode is always valid here. Otherwise, a different close
   26859   ** routine (e.g. nolockClose()) would be called instead.
   26860   */
   26861   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   26862   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   26863     /* If there are outstanding locks, do not actually close the file just
   26864     ** yet because that would clear those locks.  Instead, add the file
   26865     ** descriptor to pInode->pUnused list.  It will be automatically closed
   26866     ** when the last lock is cleared.
   26867     */
   26868     setPendingFd(pFile);
   26869   }
   26870   releaseInodeInfo(pFile);
   26871   rc = closeUnixFile(id);
   26872   unixLeaveMutex();
   26873   return rc;
   26874 }
   26875 
   26876 /************** End of the posix advisory lock implementation *****************
   26877 ******************************************************************************/
   26878 
   26879 /******************************************************************************
   26880 ****************************** No-op Locking **********************************
   26881 **
   26882 ** Of the various locking implementations available, this is by far the
   26883 ** simplest:  locking is ignored.  No attempt is made to lock the database
   26884 ** file for reading or writing.
   26885 **
   26886 ** This locking mode is appropriate for use on read-only databases
   26887 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   26888 ** also be used if the application employs some external mechanism to
   26889 ** prevent simultaneous access of the same database by two or more
   26890 ** database connections.  But there is a serious risk of database
   26891 ** corruption if this locking mode is used in situations where multiple
   26892 ** database connections are accessing the same database file at the same
   26893 ** time and one or more of those connections are writing.
   26894 */
   26895 
   26896 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   26897   UNUSED_PARAMETER(NotUsed);
   26898   *pResOut = 0;
   26899   return SQLITE_OK;
   26900 }
   26901 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   26902   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26903   return SQLITE_OK;
   26904 }
   26905 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   26906   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26907   return SQLITE_OK;
   26908 }
   26909 
   26910 /*
   26911 ** Close the file.
   26912 */
   26913 static int nolockClose(sqlite3_file *id) {
   26914   return closeUnixFile(id);
   26915 }
   26916 
   26917 /******************* End of the no-op lock implementation *********************
   26918 ******************************************************************************/
   26919 
   26920 /******************************************************************************
   26921 ************************* Begin dot-file Locking ******************************
   26922 **
   26923 ** The dotfile locking implementation uses the existance of separate lock
   26924 ** files (really a directory) to control access to the database.  This works
   26925 ** on just about every filesystem imaginable.  But there are serious downsides:
   26926 **
   26927 **    (1)  There is zero concurrency.  A single reader blocks all other
   26928 **         connections from reading or writing the database.
   26929 **
   26930 **    (2)  An application crash or power loss can leave stale lock files
   26931 **         sitting around that need to be cleared manually.
   26932 **
   26933 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   26934 ** other locking strategy is available.
   26935 **
   26936 ** Dotfile locking works by creating a subdirectory in the same directory as
   26937 ** the database and with the same name but with a ".lock" extension added.
   26938 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
   26939 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   26940 */
   26941 
   26942 /*
   26943 ** The file suffix added to the data base filename in order to create the
   26944 ** lock directory.
   26945 */
   26946 #define DOTLOCK_SUFFIX ".lock"
   26947 
   26948 /*
   26949 ** This routine checks if there is a RESERVED lock held on the specified
   26950 ** file by this or any other process. If such a lock is held, set *pResOut
   26951 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26952 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26953 **
   26954 ** In dotfile locking, either a lock exists or it does not.  So in this
   26955 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   26956 ** is held on the file and false if the file is unlocked.
   26957 */
   26958 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26959   int rc = SQLITE_OK;
   26960   int reserved = 0;
   26961   unixFile *pFile = (unixFile*)id;
   26962 
   26963   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26964 
   26965   assert( pFile );
   26966 
   26967   /* Check if a thread in this process holds such a lock */
   26968   if( pFile->eFileLock>SHARED_LOCK ){
   26969     /* Either this connection or some other connection in the same process
   26970     ** holds a lock on the file.  No need to check further. */
   26971     reserved = 1;
   26972   }else{
   26973     /* The lock is held if and only if the lockfile exists */
   26974     const char *zLockFile = (const char*)pFile->lockingContext;
   26975     reserved = osAccess(zLockFile, 0)==0;
   26976   }
   26977   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   26978   *pResOut = reserved;
   26979   return rc;
   26980 }
   26981 
   26982 /*
   26983 ** Lock the file with the lock specified by parameter eFileLock - one
   26984 ** of the following:
   26985 **
   26986 **     (1) SHARED_LOCK
   26987 **     (2) RESERVED_LOCK
   26988 **     (3) PENDING_LOCK
   26989 **     (4) EXCLUSIVE_LOCK
   26990 **
   26991 ** Sometimes when requesting one lock state, additional lock states
   26992 ** are inserted in between.  The locking might fail on one of the later
   26993 ** transitions leaving the lock state different from what it started but
   26994 ** still short of its goal.  The following chart shows the allowed
   26995 ** transitions and the inserted intermediate states:
   26996 **
   26997 **    UNLOCKED -> SHARED
   26998 **    SHARED -> RESERVED
   26999 **    SHARED -> (PENDING) -> EXCLUSIVE
   27000 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27001 **    PENDING -> EXCLUSIVE
   27002 **
   27003 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27004 ** routine to lower a locking level.
   27005 **
   27006 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   27007 ** But we track the other locking levels internally.
   27008 */
   27009 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   27010   unixFile *pFile = (unixFile*)id;
   27011   char *zLockFile = (char *)pFile->lockingContext;
   27012   int rc = SQLITE_OK;
   27013 
   27014 
   27015   /* If we have any lock, then the lock file already exists.  All we have
   27016   ** to do is adjust our internal record of the lock level.
   27017   */
   27018   if( pFile->eFileLock > NO_LOCK ){
   27019     pFile->eFileLock = eFileLock;
   27020     /* Always update the timestamp on the old file */
   27021 #ifdef HAVE_UTIME
   27022     utime(zLockFile, NULL);
   27023 #else
   27024     utimes(zLockFile, NULL);
   27025 #endif
   27026     return SQLITE_OK;
   27027   }
   27028 
   27029   /* grab an exclusive lock */
   27030   rc = osMkdir(zLockFile, 0777);
   27031   if( rc<0 ){
   27032     /* failed to open/create the lock directory */
   27033     int tErrno = errno;
   27034     if( EEXIST == tErrno ){
   27035       rc = SQLITE_BUSY;
   27036     } else {
   27037       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27038       if( IS_LOCK_ERROR(rc) ){
   27039         pFile->lastErrno = tErrno;
   27040       }
   27041     }
   27042     return rc;
   27043   }
   27044 
   27045   /* got it, set the type and return ok */
   27046   pFile->eFileLock = eFileLock;
   27047   return rc;
   27048 }
   27049 
   27050 /*
   27051 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27052 ** must be either NO_LOCK or SHARED_LOCK.
   27053 **
   27054 ** If the locking level of the file descriptor is already at or below
   27055 ** the requested locking level, this routine is a no-op.
   27056 **
   27057 ** When the locking level reaches NO_LOCK, delete the lock file.
   27058 */
   27059 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   27060   unixFile *pFile = (unixFile*)id;
   27061   char *zLockFile = (char *)pFile->lockingContext;
   27062   int rc;
   27063 
   27064   assert( pFile );
   27065   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   27066 	   pFile->eFileLock, getpid()));
   27067   assert( eFileLock<=SHARED_LOCK );
   27068 
   27069   /* no-op if possible */
   27070   if( pFile->eFileLock==eFileLock ){
   27071     return SQLITE_OK;
   27072   }
   27073 
   27074   /* To downgrade to shared, simply update our internal notion of the
   27075   ** lock state.  No need to mess with the file on disk.
   27076   */
   27077   if( eFileLock==SHARED_LOCK ){
   27078     pFile->eFileLock = SHARED_LOCK;
   27079     return SQLITE_OK;
   27080   }
   27081 
   27082   /* To fully unlock the database, delete the lock file */
   27083   assert( eFileLock==NO_LOCK );
   27084   rc = osRmdir(zLockFile);
   27085   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
   27086   if( rc<0 ){
   27087     int tErrno = errno;
   27088     rc = 0;
   27089     if( ENOENT != tErrno ){
   27090       rc = SQLITE_IOERR_UNLOCK;
   27091     }
   27092     if( IS_LOCK_ERROR(rc) ){
   27093       pFile->lastErrno = tErrno;
   27094     }
   27095     return rc;
   27096   }
   27097   pFile->eFileLock = NO_LOCK;
   27098   return SQLITE_OK;
   27099 }
   27100 
   27101 /*
   27102 ** Close a file.  Make sure the lock has been released before closing.
   27103 */
   27104 static int dotlockClose(sqlite3_file *id) {
   27105   int rc;
   27106   if( id ){
   27107     unixFile *pFile = (unixFile*)id;
   27108     dotlockUnlock(id, NO_LOCK);
   27109     sqlite3_free(pFile->lockingContext);
   27110   }
   27111   rc = closeUnixFile(id);
   27112   return rc;
   27113 }
   27114 /****************** End of the dot-file lock implementation *******************
   27115 ******************************************************************************/
   27116 
   27117 /******************************************************************************
   27118 ************************** Begin flock Locking ********************************
   27119 **
   27120 ** Use the flock() system call to do file locking.
   27121 **
   27122 ** flock() locking is like dot-file locking in that the various
   27123 ** fine-grain locking levels supported by SQLite are collapsed into
   27124 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   27125 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   27126 ** still works when you do this, but concurrency is reduced since
   27127 ** only a single process can be reading the database at a time.
   27128 **
   27129 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   27130 ** compiling for VXWORKS.
   27131 */
   27132 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   27133 
   27134 /*
   27135 ** Retry flock() calls that fail with EINTR
   27136 */
   27137 #ifdef EINTR
   27138 static int robust_flock(int fd, int op){
   27139   int rc;
   27140   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   27141   return rc;
   27142 }
   27143 #else
   27144 # define robust_flock(a,b) flock(a,b)
   27145 #endif
   27146 
   27147 
   27148 /*
   27149 ** This routine checks if there is a RESERVED lock held on the specified
   27150 ** file by this or any other process. If such a lock is held, set *pResOut
   27151 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27152 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27153 */
   27154 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   27155   int rc = SQLITE_OK;
   27156   int reserved = 0;
   27157   unixFile *pFile = (unixFile*)id;
   27158 
   27159   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27160 
   27161   assert( pFile );
   27162 
   27163   /* Check if a thread in this process holds such a lock */
   27164   if( pFile->eFileLock>SHARED_LOCK ){
   27165     reserved = 1;
   27166   }
   27167 
   27168   /* Otherwise see if some other process holds it. */
   27169   if( !reserved ){
   27170     /* attempt to get the lock */
   27171     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   27172     if( !lrc ){
   27173       /* got the lock, unlock it */
   27174       lrc = robust_flock(pFile->h, LOCK_UN);
   27175       if ( lrc ) {
   27176         int tErrno = errno;
   27177         /* unlock failed with an error */
   27178         lrc = SQLITE_IOERR_UNLOCK;
   27179         if( IS_LOCK_ERROR(lrc) ){
   27180           pFile->lastErrno = tErrno;
   27181           rc = lrc;
   27182         }
   27183       }
   27184     } else {
   27185       int tErrno = errno;
   27186       reserved = 1;
   27187       /* someone else might have it reserved */
   27188       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27189       if( IS_LOCK_ERROR(lrc) ){
   27190         pFile->lastErrno = tErrno;
   27191         rc = lrc;
   27192       }
   27193     }
   27194   }
   27195   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   27196 
   27197 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27198   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   27199     rc = SQLITE_OK;
   27200     reserved=1;
   27201   }
   27202 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27203   *pResOut = reserved;
   27204   return rc;
   27205 }
   27206 
   27207 /*
   27208 ** Lock the file with the lock specified by parameter eFileLock - one
   27209 ** of the following:
   27210 **
   27211 **     (1) SHARED_LOCK
   27212 **     (2) RESERVED_LOCK
   27213 **     (3) PENDING_LOCK
   27214 **     (4) EXCLUSIVE_LOCK
   27215 **
   27216 ** Sometimes when requesting one lock state, additional lock states
   27217 ** are inserted in between.  The locking might fail on one of the later
   27218 ** transitions leaving the lock state different from what it started but
   27219 ** still short of its goal.  The following chart shows the allowed
   27220 ** transitions and the inserted intermediate states:
   27221 **
   27222 **    UNLOCKED -> SHARED
   27223 **    SHARED -> RESERVED
   27224 **    SHARED -> (PENDING) -> EXCLUSIVE
   27225 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27226 **    PENDING -> EXCLUSIVE
   27227 **
   27228 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   27229 ** lock states in the sqlite3_file structure, but all locks SHARED or
   27230 ** above are really EXCLUSIVE locks and exclude all other processes from
   27231 ** access the file.
   27232 **
   27233 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27234 ** routine to lower a locking level.
   27235 */
   27236 static int flockLock(sqlite3_file *id, int eFileLock) {
   27237   int rc = SQLITE_OK;
   27238   unixFile *pFile = (unixFile*)id;
   27239 
   27240   assert( pFile );
   27241 
   27242   /* if we already have a lock, it is exclusive.
   27243   ** Just adjust level and punt on outta here. */
   27244   if (pFile->eFileLock > NO_LOCK) {
   27245     pFile->eFileLock = eFileLock;
   27246     return SQLITE_OK;
   27247   }
   27248 
   27249   /* grab an exclusive lock */
   27250 
   27251   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   27252     int tErrno = errno;
   27253     /* didn't get, must be busy */
   27254     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27255     if( IS_LOCK_ERROR(rc) ){
   27256       pFile->lastErrno = tErrno;
   27257     }
   27258   } else {
   27259     /* got it, set the type and return ok */
   27260     pFile->eFileLock = eFileLock;
   27261   }
   27262   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   27263            rc==SQLITE_OK ? "ok" : "failed"));
   27264 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27265   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   27266     rc = SQLITE_BUSY;
   27267   }
   27268 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27269   return rc;
   27270 }
   27271 
   27272 
   27273 /*
   27274 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27275 ** must be either NO_LOCK or SHARED_LOCK.
   27276 **
   27277 ** If the locking level of the file descriptor is already at or below
   27278 ** the requested locking level, this routine is a no-op.
   27279 */
   27280 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   27281   unixFile *pFile = (unixFile*)id;
   27282 
   27283   assert( pFile );
   27284   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   27285            pFile->eFileLock, getpid()));
   27286   assert( eFileLock<=SHARED_LOCK );
   27287 
   27288   /* no-op if possible */
   27289   if( pFile->eFileLock==eFileLock ){
   27290     return SQLITE_OK;
   27291   }
   27292 
   27293   /* shared can just be set because we always have an exclusive */
   27294   if (eFileLock==SHARED_LOCK) {
   27295     pFile->eFileLock = eFileLock;
   27296     return SQLITE_OK;
   27297   }
   27298 
   27299   /* no, really, unlock. */
   27300   if( robust_flock(pFile->h, LOCK_UN) ){
   27301 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27302     return SQLITE_OK;
   27303 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27304     return SQLITE_IOERR_UNLOCK;
   27305   }else{
   27306     pFile->eFileLock = NO_LOCK;
   27307     return SQLITE_OK;
   27308   }
   27309 }
   27310 
   27311 /*
   27312 ** Close a file.
   27313 */
   27314 static int flockClose(sqlite3_file *id) {
   27315   if( id ){
   27316     flockUnlock(id, NO_LOCK);
   27317   }
   27318   return closeUnixFile(id);
   27319 }
   27320 
   27321 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   27322 
   27323 /******************* End of the flock lock implementation *********************
   27324 ******************************************************************************/
   27325 
   27326 /******************************************************************************
   27327 ************************ Begin Named Semaphore Locking ************************
   27328 **
   27329 ** Named semaphore locking is only supported on VxWorks.
   27330 **
   27331 ** Semaphore locking is like dot-lock and flock in that it really only
   27332 ** supports EXCLUSIVE locking.  Only a single process can read or write
   27333 ** the database file at a time.  This reduces potential concurrency, but
   27334 ** makes the lock implementation much easier.
   27335 */
   27336 #if OS_VXWORKS
   27337 
   27338 /*
   27339 ** This routine checks if there is a RESERVED lock held on the specified
   27340 ** file by this or any other process. If such a lock is held, set *pResOut
   27341 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27342 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27343 */
   27344 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   27345   int rc = SQLITE_OK;
   27346   int reserved = 0;
   27347   unixFile *pFile = (unixFile*)id;
   27348 
   27349   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27350 
   27351   assert( pFile );
   27352 
   27353   /* Check if a thread in this process holds such a lock */
   27354   if( pFile->eFileLock>SHARED_LOCK ){
   27355     reserved = 1;
   27356   }
   27357 
   27358   /* Otherwise see if some other process holds it. */
   27359   if( !reserved ){
   27360     sem_t *pSem = pFile->pInode->pSem;
   27361     struct stat statBuf;
   27362 
   27363     if( sem_trywait(pSem)==-1 ){
   27364       int tErrno = errno;
   27365       if( EAGAIN != tErrno ){
   27366         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   27367         pFile->lastErrno = tErrno;
   27368       } else {
   27369         /* someone else has the lock when we are in NO_LOCK */
   27370         reserved = (pFile->eFileLock < SHARED_LOCK);
   27371       }
   27372     }else{
   27373       /* we could have it if we want it */
   27374       sem_post(pSem);
   27375     }
   27376   }
   27377   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   27378 
   27379   *pResOut = reserved;
   27380   return rc;
   27381 }
   27382 
   27383 /*
   27384 ** Lock the file with the lock specified by parameter eFileLock - one
   27385 ** of the following:
   27386 **
   27387 **     (1) SHARED_LOCK
   27388 **     (2) RESERVED_LOCK
   27389 **     (3) PENDING_LOCK
   27390 **     (4) EXCLUSIVE_LOCK
   27391 **
   27392 ** Sometimes when requesting one lock state, additional lock states
   27393 ** are inserted in between.  The locking might fail on one of the later
   27394 ** transitions leaving the lock state different from what it started but
   27395 ** still short of its goal.  The following chart shows the allowed
   27396 ** transitions and the inserted intermediate states:
   27397 **
   27398 **    UNLOCKED -> SHARED
   27399 **    SHARED -> RESERVED
   27400 **    SHARED -> (PENDING) -> EXCLUSIVE
   27401 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27402 **    PENDING -> EXCLUSIVE
   27403 **
   27404 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   27405 ** lock states in the sqlite3_file structure, but all locks SHARED or
   27406 ** above are really EXCLUSIVE locks and exclude all other processes from
   27407 ** access the file.
   27408 **
   27409 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27410 ** routine to lower a locking level.
   27411 */
   27412 static int semLock(sqlite3_file *id, int eFileLock) {
   27413   unixFile *pFile = (unixFile*)id;
   27414   int fd;
   27415   sem_t *pSem = pFile->pInode->pSem;
   27416   int rc = SQLITE_OK;
   27417 
   27418   /* if we already have a lock, it is exclusive.
   27419   ** Just adjust level and punt on outta here. */
   27420   if (pFile->eFileLock > NO_LOCK) {
   27421     pFile->eFileLock = eFileLock;
   27422     rc = SQLITE_OK;
   27423     goto sem_end_lock;
   27424   }
   27425 
   27426   /* lock semaphore now but bail out when already locked. */
   27427   if( sem_trywait(pSem)==-1 ){
   27428     rc = SQLITE_BUSY;
   27429     goto sem_end_lock;
   27430   }
   27431 
   27432   /* got it, set the type and return ok */
   27433   pFile->eFileLock = eFileLock;
   27434 
   27435  sem_end_lock:
   27436   return rc;
   27437 }
   27438 
   27439 /*
   27440 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27441 ** must be either NO_LOCK or SHARED_LOCK.
   27442 **
   27443 ** If the locking level of the file descriptor is already at or below
   27444 ** the requested locking level, this routine is a no-op.
   27445 */
   27446 static int semUnlock(sqlite3_file *id, int eFileLock) {
   27447   unixFile *pFile = (unixFile*)id;
   27448   sem_t *pSem = pFile->pInode->pSem;
   27449 
   27450   assert( pFile );
   27451   assert( pSem );
   27452   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   27453 	   pFile->eFileLock, getpid()));
   27454   assert( eFileLock<=SHARED_LOCK );
   27455 
   27456   /* no-op if possible */
   27457   if( pFile->eFileLock==eFileLock ){
   27458     return SQLITE_OK;
   27459   }
   27460 
   27461   /* shared can just be set because we always have an exclusive */
   27462   if (eFileLock==SHARED_LOCK) {
   27463     pFile->eFileLock = eFileLock;
   27464     return SQLITE_OK;
   27465   }
   27466 
   27467   /* no, really unlock. */
   27468   if ( sem_post(pSem)==-1 ) {
   27469     int rc, tErrno = errno;
   27470     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   27471     if( IS_LOCK_ERROR(rc) ){
   27472       pFile->lastErrno = tErrno;
   27473     }
   27474     return rc;
   27475   }
   27476   pFile->eFileLock = NO_LOCK;
   27477   return SQLITE_OK;
   27478 }
   27479 
   27480 /*
   27481  ** Close a file.
   27482  */
   27483 static int semClose(sqlite3_file *id) {
   27484   if( id ){
   27485     unixFile *pFile = (unixFile*)id;
   27486     semUnlock(id, NO_LOCK);
   27487     assert( pFile );
   27488     unixEnterMutex();
   27489     releaseInodeInfo(pFile);
   27490     unixLeaveMutex();
   27491     closeUnixFile(id);
   27492   }
   27493   return SQLITE_OK;
   27494 }
   27495 
   27496 #endif /* OS_VXWORKS */
   27497 /*
   27498 ** Named semaphore locking is only available on VxWorks.
   27499 **
   27500 *************** End of the named semaphore lock implementation ****************
   27501 ******************************************************************************/
   27502 
   27503 
   27504 /******************************************************************************
   27505 *************************** Begin AFP Locking *********************************
   27506 **
   27507 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   27508 ** on Apple Macintosh computers - both OS9 and OSX.
   27509 **
   27510 ** Third-party implementations of AFP are available.  But this code here
   27511 ** only works on OSX.
   27512 */
   27513 
   27514 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27515 /*
   27516 ** The afpLockingContext structure contains all afp lock specific state
   27517 */
   27518 typedef struct afpLockingContext afpLockingContext;
   27519 struct afpLockingContext {
   27520   int reserved;
   27521   const char *dbPath;             /* Name of the open file */
   27522 };
   27523 
   27524 struct ByteRangeLockPB2
   27525 {
   27526   unsigned long long offset;        /* offset to first byte to lock */
   27527   unsigned long long length;        /* nbr of bytes to lock */
   27528   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   27529   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   27530   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   27531   int fd;                           /* file desc to assoc this lock with */
   27532 };
   27533 
   27534 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   27535 
   27536 /*
   27537 ** This is a utility for setting or clearing a bit-range lock on an
   27538 ** AFP filesystem.
   27539 **
   27540 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   27541 */
   27542 static int afpSetLock(
   27543   const char *path,              /* Name of the file to be locked or unlocked */
   27544   unixFile *pFile,               /* Open file descriptor on path */
   27545   unsigned long long offset,     /* First byte to be locked */
   27546   unsigned long long length,     /* Number of bytes to lock */
   27547   int setLockFlag                /* True to set lock.  False to clear lock */
   27548 ){
   27549   struct ByteRangeLockPB2 pb;
   27550   int err;
   27551 
   27552   pb.unLockFlag = setLockFlag ? 0 : 1;
   27553   pb.startEndFlag = 0;
   27554   pb.offset = offset;
   27555   pb.length = length;
   27556   pb.fd = pFile->h;
   27557 
   27558   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   27559     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   27560     offset, length));
   27561   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   27562   if ( err==-1 ) {
   27563     int rc;
   27564     int tErrno = errno;
   27565     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   27566              path, tErrno, strerror(tErrno)));
   27567 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   27568     rc = SQLITE_BUSY;
   27569 #else
   27570     rc = sqliteErrorFromPosixError(tErrno,
   27571                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   27572 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   27573     if( IS_LOCK_ERROR(rc) ){
   27574       pFile->lastErrno = tErrno;
   27575     }
   27576     return rc;
   27577   } else {
   27578     return SQLITE_OK;
   27579   }
   27580 }
   27581 
   27582 /*
   27583 ** This routine checks if there is a RESERVED lock held on the specified
   27584 ** file by this or any other process. If such a lock is held, set *pResOut
   27585 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27586 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27587 */
   27588 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   27589   int rc = SQLITE_OK;
   27590   int reserved = 0;
   27591   unixFile *pFile = (unixFile*)id;
   27592   afpLockingContext *context;
   27593 
   27594   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27595 
   27596   assert( pFile );
   27597   context = (afpLockingContext *) pFile->lockingContext;
   27598   if( context->reserved ){
   27599     *pResOut = 1;
   27600     return SQLITE_OK;
   27601   }
   27602   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   27603 
   27604   /* Check if a thread in this process holds such a lock */
   27605   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   27606     reserved = 1;
   27607   }
   27608 
   27609   /* Otherwise see if some other process holds it.
   27610    */
   27611   if( !reserved ){
   27612     /* lock the RESERVED byte */
   27613     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27614     if( SQLITE_OK==lrc ){
   27615       /* if we succeeded in taking the reserved lock, unlock it to restore
   27616       ** the original state */
   27617       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27618     } else {
   27619       /* if we failed to get the lock then someone else must have it */
   27620       reserved = 1;
   27621     }
   27622     if( IS_LOCK_ERROR(lrc) ){
   27623       rc=lrc;
   27624     }
   27625   }
   27626 
   27627   unixLeaveMutex();
   27628   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   27629 
   27630   *pResOut = reserved;
   27631   return rc;
   27632 }
   27633 
   27634 /*
   27635 ** Lock the file with the lock specified by parameter eFileLock - one
   27636 ** of the following:
   27637 **
   27638 **     (1) SHARED_LOCK
   27639 **     (2) RESERVED_LOCK
   27640 **     (3) PENDING_LOCK
   27641 **     (4) EXCLUSIVE_LOCK
   27642 **
   27643 ** Sometimes when requesting one lock state, additional lock states
   27644 ** are inserted in between.  The locking might fail on one of the later
   27645 ** transitions leaving the lock state different from what it started but
   27646 ** still short of its goal.  The following chart shows the allowed
   27647 ** transitions and the inserted intermediate states:
   27648 **
   27649 **    UNLOCKED -> SHARED
   27650 **    SHARED -> RESERVED
   27651 **    SHARED -> (PENDING) -> EXCLUSIVE
   27652 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27653 **    PENDING -> EXCLUSIVE
   27654 **
   27655 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27656 ** routine to lower a locking level.
   27657 */
   27658 static int afpLock(sqlite3_file *id, int eFileLock){
   27659   int rc = SQLITE_OK;
   27660   unixFile *pFile = (unixFile*)id;
   27661   unixInodeInfo *pInode = pFile->pInode;
   27662   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27663 
   27664   assert( pFile );
   27665   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   27666            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   27667            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   27668 
   27669   /* If there is already a lock of this type or more restrictive on the
   27670   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   27671   ** unixEnterMutex() hasn't been called yet.
   27672   */
   27673   if( pFile->eFileLock>=eFileLock ){
   27674     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   27675            azFileLock(eFileLock)));
   27676     return SQLITE_OK;
   27677   }
   27678 
   27679   /* Make sure the locking sequence is correct
   27680   **  (1) We never move from unlocked to anything higher than shared lock.
   27681   **  (2) SQLite never explicitly requests a pendig lock.
   27682   **  (3) A shared lock is always held when a reserve lock is requested.
   27683   */
   27684   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   27685   assert( eFileLock!=PENDING_LOCK );
   27686   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   27687 
   27688   /* This mutex is needed because pFile->pInode is shared across threads
   27689   */
   27690   unixEnterMutex();
   27691   pInode = pFile->pInode;
   27692 
   27693   /* If some thread using this PID has a lock via a different unixFile*
   27694   ** handle that precludes the requested lock, return BUSY.
   27695   */
   27696   if( (pFile->eFileLock!=pInode->eFileLock &&
   27697        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   27698      ){
   27699     rc = SQLITE_BUSY;
   27700     goto afp_end_lock;
   27701   }
   27702 
   27703   /* If a SHARED lock is requested, and some thread using this PID already
   27704   ** has a SHARED or RESERVED lock, then increment reference counts and
   27705   ** return SQLITE_OK.
   27706   */
   27707   if( eFileLock==SHARED_LOCK &&
   27708      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   27709     assert( eFileLock==SHARED_LOCK );
   27710     assert( pFile->eFileLock==0 );
   27711     assert( pInode->nShared>0 );
   27712     pFile->eFileLock = SHARED_LOCK;
   27713     pInode->nShared++;
   27714     pInode->nLock++;
   27715     goto afp_end_lock;
   27716   }
   27717 
   27718   /* A PENDING lock is needed before acquiring a SHARED lock and before
   27719   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   27720   ** be released.
   27721   */
   27722   if( eFileLock==SHARED_LOCK
   27723       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   27724   ){
   27725     int failed;
   27726     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   27727     if (failed) {
   27728       rc = failed;
   27729       goto afp_end_lock;
   27730     }
   27731   }
   27732 
   27733   /* If control gets to this point, then actually go ahead and make
   27734   ** operating system calls for the specified lock.
   27735   */
   27736   if( eFileLock==SHARED_LOCK ){
   27737     int lrc1, lrc2, lrc1Errno = 0;
   27738     long lk, mask;
   27739 
   27740     assert( pInode->nShared==0 );
   27741     assert( pInode->eFileLock==0 );
   27742 
   27743     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   27744     /* Now get the read-lock SHARED_LOCK */
   27745     /* note that the quality of the randomness doesn't matter that much */
   27746     lk = random();
   27747     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   27748     lrc1 = afpSetLock(context->dbPath, pFile,
   27749           SHARED_FIRST+pInode->sharedByte, 1, 1);
   27750     if( IS_LOCK_ERROR(lrc1) ){
   27751       lrc1Errno = pFile->lastErrno;
   27752     }
   27753     /* Drop the temporary PENDING lock */
   27754     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27755 
   27756     if( IS_LOCK_ERROR(lrc1) ) {
   27757       pFile->lastErrno = lrc1Errno;
   27758       rc = lrc1;
   27759       goto afp_end_lock;
   27760     } else if( IS_LOCK_ERROR(lrc2) ){
   27761       rc = lrc2;
   27762       goto afp_end_lock;
   27763     } else if( lrc1 != SQLITE_OK ) {
   27764       rc = lrc1;
   27765     } else {
   27766       pFile->eFileLock = SHARED_LOCK;
   27767       pInode->nLock++;
   27768       pInode->nShared = 1;
   27769     }
   27770   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   27771     /* We are trying for an exclusive lock but another thread in this
   27772      ** same process is still holding a shared lock. */
   27773     rc = SQLITE_BUSY;
   27774   }else{
   27775     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   27776     ** assumed that there is a SHARED or greater lock on the file
   27777     ** already.
   27778     */
   27779     int failed = 0;
   27780     assert( 0!=pFile->eFileLock );
   27781     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   27782         /* Acquire a RESERVED lock */
   27783         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27784       if( !failed ){
   27785         context->reserved = 1;
   27786       }
   27787     }
   27788     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   27789       /* Acquire an EXCLUSIVE lock */
   27790 
   27791       /* Remove the shared lock before trying the range.  we'll need to
   27792       ** reestablish the shared lock if we can't get the  afpUnlock
   27793       */
   27794       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   27795                          pInode->sharedByte, 1, 0)) ){
   27796         int failed2 = SQLITE_OK;
   27797         /* now attemmpt to get the exclusive lock range */
   27798         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   27799                                SHARED_SIZE, 1);
   27800         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   27801                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   27802           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   27803           ** a critical I/O error
   27804           */
   27805           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   27806                SQLITE_IOERR_LOCK;
   27807           goto afp_end_lock;
   27808         }
   27809       }else{
   27810         rc = failed;
   27811       }
   27812     }
   27813     if( failed ){
   27814       rc = failed;
   27815     }
   27816   }
   27817 
   27818   if( rc==SQLITE_OK ){
   27819     pFile->eFileLock = eFileLock;
   27820     pInode->eFileLock = eFileLock;
   27821   }else if( eFileLock==EXCLUSIVE_LOCK ){
   27822     pFile->eFileLock = PENDING_LOCK;
   27823     pInode->eFileLock = PENDING_LOCK;
   27824   }
   27825 
   27826 afp_end_lock:
   27827   unixLeaveMutex();
   27828   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   27829          rc==SQLITE_OK ? "ok" : "failed"));
   27830   return rc;
   27831 }
   27832 
   27833 /*
   27834 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27835 ** must be either NO_LOCK or SHARED_LOCK.
   27836 **
   27837 ** If the locking level of the file descriptor is already at or below
   27838 ** the requested locking level, this routine is a no-op.
   27839 */
   27840 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   27841   int rc = SQLITE_OK;
   27842   unixFile *pFile = (unixFile*)id;
   27843   unixInodeInfo *pInode;
   27844   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27845   int skipShared = 0;
   27846 #ifdef SQLITE_TEST
   27847   int h = pFile->h;
   27848 #endif
   27849 
   27850   assert( pFile );
   27851   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   27852            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   27853            getpid()));
   27854 
   27855   assert( eFileLock<=SHARED_LOCK );
   27856   if( pFile->eFileLock<=eFileLock ){
   27857     return SQLITE_OK;
   27858   }
   27859   unixEnterMutex();
   27860   pInode = pFile->pInode;
   27861   assert( pInode->nShared!=0 );
   27862   if( pFile->eFileLock>SHARED_LOCK ){
   27863     assert( pInode->eFileLock==pFile->eFileLock );
   27864     SimulateIOErrorBenign(1);
   27865     SimulateIOError( h=(-1) )
   27866     SimulateIOErrorBenign(0);
   27867 
   27868 #ifndef NDEBUG
   27869     /* When reducing a lock such that other processes can start
   27870     ** reading the database file again, make sure that the
   27871     ** transaction counter was updated if any part of the database
   27872     ** file changed.  If the transaction counter is not updated,
   27873     ** other connections to the same file might not realize that
   27874     ** the file has changed and hence might not know to flush their
   27875     ** cache.  The use of a stale cache can lead to database corruption.
   27876     */
   27877     assert( pFile->inNormalWrite==0
   27878            || pFile->dbUpdate==0
   27879            || pFile->transCntrChng==1 );
   27880     pFile->inNormalWrite = 0;
   27881 #endif
   27882 
   27883     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   27884       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   27885       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   27886         /* only re-establish the shared lock if necessary */
   27887         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27888         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   27889       } else {
   27890         skipShared = 1;
   27891       }
   27892     }
   27893     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   27894       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27895     }
   27896     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   27897       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27898       if( !rc ){
   27899         context->reserved = 0;
   27900       }
   27901     }
   27902     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   27903       pInode->eFileLock = SHARED_LOCK;
   27904     }
   27905   }
   27906   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   27907 
   27908     /* Decrement the shared lock counter.  Release the lock using an
   27909     ** OS call only when all threads in this same process have released
   27910     ** the lock.
   27911     */
   27912     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27913     pInode->nShared--;
   27914     if( pInode->nShared==0 ){
   27915       SimulateIOErrorBenign(1);
   27916       SimulateIOError( h=(-1) )
   27917       SimulateIOErrorBenign(0);
   27918       if( !skipShared ){
   27919         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   27920       }
   27921       if( !rc ){
   27922         pInode->eFileLock = NO_LOCK;
   27923         pFile->eFileLock = NO_LOCK;
   27924       }
   27925     }
   27926     if( rc==SQLITE_OK ){
   27927       pInode->nLock--;
   27928       assert( pInode->nLock>=0 );
   27929       if( pInode->nLock==0 ){
   27930         closePendingFds(pFile);
   27931       }
   27932     }
   27933   }
   27934 
   27935   unixLeaveMutex();
   27936   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   27937   return rc;
   27938 }
   27939 
   27940 /*
   27941 ** Close a file & cleanup AFP specific locking context
   27942 */
   27943 static int afpClose(sqlite3_file *id) {
   27944   int rc = SQLITE_OK;
   27945   if( id ){
   27946     unixFile *pFile = (unixFile*)id;
   27947     afpUnlock(id, NO_LOCK);
   27948     unixEnterMutex();
   27949     if( pFile->pInode && pFile->pInode->nLock ){
   27950       /* If there are outstanding locks, do not actually close the file just
   27951       ** yet because that would clear those locks.  Instead, add the file
   27952       ** descriptor to pInode->aPending.  It will be automatically closed when
   27953       ** the last lock is cleared.
   27954       */
   27955       setPendingFd(pFile);
   27956     }
   27957     releaseInodeInfo(pFile);
   27958     sqlite3_free(pFile->lockingContext);
   27959     rc = closeUnixFile(id);
   27960     unixLeaveMutex();
   27961   }
   27962   return rc;
   27963 }
   27964 
   27965 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27966 /*
   27967 ** The code above is the AFP lock implementation.  The code is specific
   27968 ** to MacOSX and does not work on other unix platforms.  No alternative
   27969 ** is available.  If you don't compile for a mac, then the "unix-afp"
   27970 ** VFS is not available.
   27971 **
   27972 ********************* End of the AFP lock implementation **********************
   27973 ******************************************************************************/
   27974 
   27975 /******************************************************************************
   27976 *************************** Begin NFS Locking ********************************/
   27977 
   27978 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27979 /*
   27980  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27981  ** must be either NO_LOCK or SHARED_LOCK.
   27982  **
   27983  ** If the locking level of the file descriptor is already at or below
   27984  ** the requested locking level, this routine is a no-op.
   27985  */
   27986 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   27987   return posixUnlock(id, eFileLock, 1);
   27988 }
   27989 
   27990 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27991 /*
   27992 ** The code above is the NFS lock implementation.  The code is specific
   27993 ** to MacOSX and does not work on other unix platforms.  No alternative
   27994 ** is available.
   27995 **
   27996 ********************* End of the NFS lock implementation **********************
   27997 ******************************************************************************/
   27998 
   27999 /******************************************************************************
   28000 **************** Non-locking sqlite3_file methods *****************************
   28001 **
   28002 ** The next division contains implementations for all methods of the
   28003 ** sqlite3_file object other than the locking methods.  The locking
   28004 ** methods were defined in divisions above (one locking method per
   28005 ** division).  Those methods that are common to all locking modes
   28006 ** are gather together into this division.
   28007 */
   28008 
   28009 /*
   28010 ** Seek to the offset passed as the second argument, then read cnt
   28011 ** bytes into pBuf. Return the number of bytes actually read.
   28012 **
   28013 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   28014 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   28015 ** one system to another.  Since SQLite does not define USE_PREAD
   28016 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   28017 ** See tickets #2741 and #2681.
   28018 **
   28019 ** To avoid stomping the errno value on a failed read the lastErrno value
   28020 ** is set before returning.
   28021 */
   28022 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   28023   int got;
   28024   int prior = 0;
   28025 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   28026   i64 newOffset;
   28027 #endif
   28028   TIMER_START;
   28029   do{
   28030 #if defined(USE_PREAD)
   28031     got = osPread(id->h, pBuf, cnt, offset);
   28032     SimulateIOError( got = -1 );
   28033 #elif defined(USE_PREAD64)
   28034     got = osPread64(id->h, pBuf, cnt, offset);
   28035     SimulateIOError( got = -1 );
   28036 #else
   28037     newOffset = lseek(id->h, offset, SEEK_SET);
   28038     SimulateIOError( newOffset-- );
   28039     if( newOffset!=offset ){
   28040       if( newOffset == -1 ){
   28041         ((unixFile*)id)->lastErrno = errno;
   28042       }else{
   28043         ((unixFile*)id)->lastErrno = 0;
   28044       }
   28045       return -1;
   28046     }
   28047     got = osRead(id->h, pBuf, cnt);
   28048 #endif
   28049     if( got==cnt ) break;
   28050     if( got<0 ){
   28051       if( errno==EINTR ){ got = 1; continue; }
   28052       prior = 0;
   28053       ((unixFile*)id)->lastErrno = errno;
   28054       break;
   28055     }else if( got>0 ){
   28056       cnt -= got;
   28057       offset += got;
   28058       prior += got;
   28059       pBuf = (void*)(got + (char*)pBuf);
   28060     }
   28061   }while( got>0 );
   28062   TIMER_END;
   28063   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
   28064             id->h, got+prior, offset-prior, TIMER_ELAPSED));
   28065   return got+prior;
   28066 }
   28067 
   28068 /*
   28069 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   28070 ** bytes were read successfully and SQLITE_IOERR if anything goes
   28071 ** wrong.
   28072 */
   28073 static int unixRead(
   28074   sqlite3_file *id,
   28075   void *pBuf,
   28076   int amt,
   28077   sqlite3_int64 offset
   28078 ){
   28079   unixFile *pFile = (unixFile *)id;
   28080   int got;
   28081   assert( id );
   28082 
   28083   /* If this is a database file (not a journal, master-journal or temp
   28084   ** file), the bytes in the locking range should never be read or written. */
   28085 #if 0
   28086   assert( pFile->pUnused==0
   28087        || offset>=PENDING_BYTE+512
   28088        || offset+amt<=PENDING_BYTE
   28089   );
   28090 #endif
   28091 
   28092   got = seekAndRead(pFile, offset, pBuf, amt);
   28093   if( got==amt ){
   28094     return SQLITE_OK;
   28095   }else if( got<0 ){
   28096     /* lastErrno set by seekAndRead */
   28097     return SQLITE_IOERR_READ;
   28098   }else{
   28099     pFile->lastErrno = 0; /* not a system error */
   28100     /* Unread parts of the buffer must be zero-filled */
   28101     memset(&((char*)pBuf)[got], 0, amt-got);
   28102     return SQLITE_IOERR_SHORT_READ;
   28103   }
   28104 }
   28105 
   28106 /*
   28107 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   28108 ** Return the number of bytes actually read.  Update the offset.
   28109 **
   28110 ** To avoid stomping the errno value on a failed write the lastErrno value
   28111 ** is set before returning.
   28112 */
   28113 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   28114   int got;
   28115 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   28116   i64 newOffset;
   28117 #endif
   28118   TIMER_START;
   28119 #if defined(USE_PREAD)
   28120   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   28121 #elif defined(USE_PREAD64)
   28122   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
   28123 #else
   28124   do{
   28125     newOffset = lseek(id->h, offset, SEEK_SET);
   28126     SimulateIOError( newOffset-- );
   28127     if( newOffset!=offset ){
   28128       if( newOffset == -1 ){
   28129         ((unixFile*)id)->lastErrno = errno;
   28130       }else{
   28131         ((unixFile*)id)->lastErrno = 0;
   28132       }
   28133       return -1;
   28134     }
   28135     got = osWrite(id->h, pBuf, cnt);
   28136   }while( got<0 && errno==EINTR );
   28137 #endif
   28138   TIMER_END;
   28139   if( got<0 ){
   28140     ((unixFile*)id)->lastErrno = errno;
   28141   }
   28142 
   28143   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   28144   return got;
   28145 }
   28146 
   28147 
   28148 /*
   28149 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   28150 ** or some other error code on failure.
   28151 */
   28152 static int unixWrite(
   28153   sqlite3_file *id,
   28154   const void *pBuf,
   28155   int amt,
   28156   sqlite3_int64 offset
   28157 ){
   28158   unixFile *pFile = (unixFile*)id;
   28159   int wrote = 0;
   28160   assert( id );
   28161   assert( amt>0 );
   28162 
   28163   /* If this is a database file (not a journal, master-journal or temp
   28164   ** file), the bytes in the locking range should never be read or written. */
   28165 #if 0
   28166   assert( pFile->pUnused==0
   28167        || offset>=PENDING_BYTE+512
   28168        || offset+amt<=PENDING_BYTE
   28169   );
   28170 #endif
   28171 
   28172 #ifndef NDEBUG
   28173   /* If we are doing a normal write to a database file (as opposed to
   28174   ** doing a hot-journal rollback or a write to some file other than a
   28175   ** normal database file) then record the fact that the database
   28176   ** has changed.  If the transaction counter is modified, record that
   28177   ** fact too.
   28178   */
   28179   if( pFile->inNormalWrite ){
   28180     pFile->dbUpdate = 1;  /* The database has been modified */
   28181     if( offset<=24 && offset+amt>=27 ){
   28182       int rc;
   28183       char oldCntr[4];
   28184       SimulateIOErrorBenign(1);
   28185       rc = seekAndRead(pFile, 24, oldCntr, 4);
   28186       SimulateIOErrorBenign(0);
   28187       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   28188         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   28189       }
   28190     }
   28191   }
   28192 #endif
   28193 
   28194   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   28195     amt -= wrote;
   28196     offset += wrote;
   28197     pBuf = &((char*)pBuf)[wrote];
   28198   }
   28199   SimulateIOError(( wrote=(-1), amt=1 ));
   28200   SimulateDiskfullError(( wrote=0, amt=1 ));
   28201 
   28202   if( amt>0 ){
   28203     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
   28204       /* lastErrno set by seekAndWrite */
   28205       return SQLITE_IOERR_WRITE;
   28206     }else{
   28207       pFile->lastErrno = 0; /* not a system error */
   28208       return SQLITE_FULL;
   28209     }
   28210   }
   28211 
   28212   return SQLITE_OK;
   28213 }
   28214 
   28215 #ifdef SQLITE_TEST
   28216 /*
   28217 ** Count the number of fullsyncs and normal syncs.  This is used to test
   28218 ** that syncs and fullsyncs are occurring at the right times.
   28219 */
   28220 SQLITE_API int sqlite3_sync_count = 0;
   28221 SQLITE_API int sqlite3_fullsync_count = 0;
   28222 #endif
   28223 
   28224 /*
   28225 ** We do not trust systems to provide a working fdatasync().  Some do.
   28226 ** Others do no.  To be safe, we will stick with the (slightly slower)
   28227 ** fsync(). If you know that your system does support fdatasync() correctly,
   28228 ** then simply compile with -Dfdatasync=fdatasync
   28229 */
   28230 #if !defined(fdatasync)
   28231 # define fdatasync fsync
   28232 #endif
   28233 
   28234 /*
   28235 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   28236 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   28237 ** only available on Mac OS X.  But that could change.
   28238 */
   28239 #ifdef F_FULLFSYNC
   28240 # define HAVE_FULLFSYNC 1
   28241 #else
   28242 # define HAVE_FULLFSYNC 0
   28243 #endif
   28244 
   28245 
   28246 /*
   28247 ** The fsync() system call does not work as advertised on many
   28248 ** unix systems.  The following procedure is an attempt to make
   28249 ** it work better.
   28250 **
   28251 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   28252 ** for testing when we want to run through the test suite quickly.
   28253 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   28254 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   28255 ** or power failure will likely corrupt the database file.
   28256 **
   28257 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   28258 ** The idea behind dataOnly is that it should only write the file content
   28259 ** to disk, not the inode.  We only set dataOnly if the file size is
   28260 ** unchanged since the file size is part of the inode.  However,
   28261 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   28262 ** file size has changed.  The only real difference between fdatasync()
   28263 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   28264 ** inode if the mtime or owner or other inode attributes have changed.
   28265 ** We only care about the file size, not the other file attributes, so
   28266 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   28267 ** So, we always use fdatasync() if it is available, regardless of
   28268 ** the value of the dataOnly flag.
   28269 */
   28270 static int full_fsync(int fd, int fullSync, int dataOnly){
   28271   int rc;
   28272 
   28273   /* The following "ifdef/elif/else/" block has the same structure as
   28274   ** the one below. It is replicated here solely to avoid cluttering
   28275   ** up the real code with the UNUSED_PARAMETER() macros.
   28276   */
   28277 #ifdef SQLITE_NO_SYNC
   28278   UNUSED_PARAMETER(fd);
   28279   UNUSED_PARAMETER(fullSync);
   28280   UNUSED_PARAMETER(dataOnly);
   28281 #elif HAVE_FULLFSYNC
   28282   UNUSED_PARAMETER(dataOnly);
   28283 #else
   28284   UNUSED_PARAMETER(fullSync);
   28285   UNUSED_PARAMETER(dataOnly);
   28286 #endif
   28287 
   28288   /* Record the number of times that we do a normal fsync() and
   28289   ** FULLSYNC.  This is used during testing to verify that this procedure
   28290   ** gets called with the correct arguments.
   28291   */
   28292 #ifdef SQLITE_TEST
   28293   if( fullSync ) sqlite3_fullsync_count++;
   28294   sqlite3_sync_count++;
   28295 #endif
   28296 
   28297   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   28298   ** no-op
   28299   */
   28300 #ifdef SQLITE_NO_SYNC
   28301   rc = SQLITE_OK;
   28302 #elif HAVE_FULLFSYNC
   28303   if( fullSync ){
   28304     rc = osFcntl(fd, F_FULLFSYNC, 0);
   28305   }else{
   28306     rc = 1;
   28307   }
   28308   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   28309   ** It shouldn't be possible for fullfsync to fail on the local
   28310   ** file system (on OSX), so failure indicates that FULLFSYNC
   28311   ** isn't supported for this file system. So, attempt an fsync
   28312   ** and (for now) ignore the overhead of a superfluous fcntl call.
   28313   ** It'd be better to detect fullfsync support once and avoid
   28314   ** the fcntl call every time sync is called.
   28315   */
   28316   if( rc ) rc = fsync(fd);
   28317 
   28318 #elif defined(__APPLE__)
   28319   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   28320   ** so currently we default to the macro that redefines fdatasync to fsync
   28321   */
   28322   rc = fsync(fd);
   28323 #else
   28324   rc = fdatasync(fd);
   28325 #if OS_VXWORKS
   28326   if( rc==-1 && errno==ENOTSUP ){
   28327     rc = fsync(fd);
   28328   }
   28329 #endif /* OS_VXWORKS */
   28330 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   28331 
   28332   if( OS_VXWORKS && rc!= -1 ){
   28333     rc = 0;
   28334   }
   28335   return rc;
   28336 }
   28337 
   28338 /*
   28339 ** Open a file descriptor to the directory containing file zFilename.
   28340 ** If successful, *pFd is set to the opened file descriptor and
   28341 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   28342 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   28343 ** value.
   28344 **
   28345 ** The directory file descriptor is used for only one thing - to
   28346 ** fsync() a directory to make sure file creation and deletion events
   28347 ** are flushed to disk.  Such fsyncs are not needed on newer
   28348 ** journaling filesystems, but are required on older filesystems.
   28349 **
   28350 ** This routine can be overridden using the xSetSysCall interface.
   28351 ** The ability to override this routine was added in support of the
   28352 ** chromium sandbox.  Opening a directory is a security risk (we are
   28353 ** told) so making it overrideable allows the chromium sandbox to
   28354 ** replace this routine with a harmless no-op.  To make this routine
   28355 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   28356 ** *pFd set to a negative number.
   28357 **
   28358 ** If SQLITE_OK is returned, the caller is responsible for closing
   28359 ** the file descriptor *pFd using close().
   28360 */
   28361 static int openDirectory(const char *zFilename, int *pFd){
   28362   int ii;
   28363   int fd = -1;
   28364   char zDirname[MAX_PATHNAME+1];
   28365 
   28366   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   28367   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   28368   if( ii>0 ){
   28369     zDirname[ii] = '\0';
   28370     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   28371     if( fd>=0 ){
   28372 #ifdef FD_CLOEXEC
   28373       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   28374 #endif
   28375       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   28376     }
   28377   }
   28378   *pFd = fd;
   28379   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   28380 }
   28381 
   28382 /*
   28383 ** Make sure all writes to a particular file are committed to disk.
   28384 **
   28385 ** If dataOnly==0 then both the file itself and its metadata (file
   28386 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   28387 ** file data is synced.
   28388 **
   28389 ** Under Unix, also make sure that the directory entry for the file
   28390 ** has been created by fsync-ing the directory that contains the file.
   28391 ** If we do not do this and we encounter a power failure, the directory
   28392 ** entry for the journal might not exist after we reboot.  The next
   28393 ** SQLite to access the file will not know that the journal exists (because
   28394 ** the directory entry for the journal was never created) and the transaction
   28395 ** will not roll back - possibly leading to database corruption.
   28396 */
   28397 static int unixSync(sqlite3_file *id, int flags){
   28398   int rc;
   28399   unixFile *pFile = (unixFile*)id;
   28400 
   28401   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   28402   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   28403 
   28404   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   28405   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   28406       || (flags&0x0F)==SQLITE_SYNC_FULL
   28407   );
   28408 
   28409   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   28410   ** line is to test that doing so does not cause any problems.
   28411   */
   28412   SimulateDiskfullError( return SQLITE_FULL );
   28413 
   28414   assert( pFile );
   28415   OSTRACE(("SYNC    %-3d\n", pFile->h));
   28416   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   28417   SimulateIOError( rc=1 );
   28418   if( rc ){
   28419     pFile->lastErrno = errno;
   28420     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   28421   }
   28422 
   28423   /* Also fsync the directory containing the file if the DIRSYNC flag
   28424   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
   28425   ** are unable to fsync a directory, so ignore errors on the fsync.
   28426   */
   28427   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   28428     int dirfd;
   28429     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   28430             HAVE_FULLFSYNC, isFullsync));
   28431     rc = osOpenDirectory(pFile->zPath, &dirfd);
   28432     if( rc==SQLITE_OK && dirfd>=0 ){
   28433       full_fsync(dirfd, 0, 0);
   28434       robust_close(pFile, dirfd, __LINE__);
   28435     }else if( rc==SQLITE_CANTOPEN ){
   28436       rc = SQLITE_OK;
   28437     }
   28438     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   28439   }
   28440   return rc;
   28441 }
   28442 
   28443 /*
   28444 ** Truncate an open file to a specified size
   28445 */
   28446 static int unixTruncate(sqlite3_file *id, i64 nByte){
   28447   unixFile *pFile = (unixFile *)id;
   28448   int rc;
   28449   assert( pFile );
   28450   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   28451 
   28452   /* If the user has configured a chunk-size for this file, truncate the
   28453   ** file so that it consists of an integer number of chunks (i.e. the
   28454   ** actual file size after the operation may be larger than the requested
   28455   ** size).
   28456   */
   28457   if( pFile->szChunk ){
   28458     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   28459   }
   28460 
   28461   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   28462   if( rc ){
   28463     pFile->lastErrno = errno;
   28464     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   28465   }else{
   28466 #ifndef NDEBUG
   28467     /* If we are doing a normal write to a database file (as opposed to
   28468     ** doing a hot-journal rollback or a write to some file other than a
   28469     ** normal database file) and we truncate the file to zero length,
   28470     ** that effectively updates the change counter.  This might happen
   28471     ** when restoring a database using the backup API from a zero-length
   28472     ** source.
   28473     */
   28474     if( pFile->inNormalWrite && nByte==0 ){
   28475       pFile->transCntrChng = 1;
   28476     }
   28477 #endif
   28478 
   28479     return SQLITE_OK;
   28480   }
   28481 }
   28482 
   28483 /*
   28484 ** Determine the current size of a file in bytes
   28485 */
   28486 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   28487   int rc;
   28488   struct stat buf;
   28489   assert( id );
   28490   rc = osFstat(((unixFile*)id)->h, &buf);
   28491   SimulateIOError( rc=1 );
   28492   if( rc!=0 ){
   28493     ((unixFile*)id)->lastErrno = errno;
   28494     return unixLogError(SQLITE_IOERR_FSTAT, "fstat", ((unixFile*)id)->zPath);
   28495   }
   28496   *pSize = buf.st_size;
   28497 
   28498   /* When opening a zero-size database, the findInodeInfo() procedure
   28499   ** writes a single byte into that file in order to work around a bug
   28500   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   28501   ** layers, we need to report this file size as zero even though it is
   28502   ** really 1.   Ticket #3260.
   28503   */
   28504   if( *pSize==1 ) *pSize = 0;
   28505 
   28506 
   28507   return SQLITE_OK;
   28508 }
   28509 
   28510 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28511 /*
   28512 ** Handler for proxy-locking file-control verbs.  Defined below in the
   28513 ** proxying locking division.
   28514 */
   28515 static int proxyFileControl(sqlite3_file*,int,void*);
   28516 #endif
   28517 
   28518 /*
   28519 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   28520 ** file-control operation.  Enlarge the database to nBytes in size
   28521 ** (rounded up to the next chunk-size).  If the database is already
   28522 ** nBytes or larger, this routine is a no-op.
   28523 */
   28524 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   28525   if( pFile->szChunk>0 ){
   28526     i64 nSize;                    /* Required file size */
   28527     struct stat buf;              /* Used to hold return values of fstat() */
   28528 
   28529     if( osFstat(pFile->h, &buf) ) {
   28530       return unixLogError(SQLITE_IOERR_FSTAT, "fstat", pFile->zPath);
   28531     }
   28532 
   28533     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   28534     if( nSize>(i64)buf.st_size ){
   28535 
   28536 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   28537       /* The code below is handling the return value of osFallocate()
   28538       ** correctly. posix_fallocate() is defined to "returns zero on success,
   28539       ** or an error number on  failure". See the manpage for details. */
   28540       int err;
   28541       do{
   28542         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   28543       }while( err==EINTR );
   28544       if( err ) return SQLITE_IOERR_WRITE;
   28545 #else
   28546       /* If the OS does not have posix_fallocate(), fake it. First use
   28547       ** ftruncate() to set the file size, then write a single byte to
   28548       ** the last byte in each block within the extended region. This
   28549       ** is the same technique used by glibc to implement posix_fallocate()
   28550       ** on systems that do not have a real fallocate() system call.
   28551       */
   28552       int nBlk = buf.st_blksize;  /* File-system block size */
   28553       i64 iWrite;                 /* Next offset to write to */
   28554 
   28555       if( robust_ftruncate(pFile->h, nSize) ){
   28556         pFile->lastErrno = errno;
   28557         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   28558       }
   28559       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   28560       while( iWrite<nSize ){
   28561         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
   28562         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   28563         iWrite += nBlk;
   28564       }
   28565 #endif
   28566     }
   28567   }
   28568 
   28569   return SQLITE_OK;
   28570 }
   28571 
   28572 /*
   28573 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   28574 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   28575 **
   28576 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   28577 */
   28578 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
   28579   if( *pArg<0 ){
   28580     *pArg = (pFile->ctrlFlags & mask)!=0;
   28581   }else if( (*pArg)==0 ){
   28582     pFile->ctrlFlags &= ~mask;
   28583   }else{
   28584     pFile->ctrlFlags |= mask;
   28585   }
   28586 }
   28587 
   28588 /*
   28589 ** Information and control of an open file handle.
   28590 */
   28591 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   28592   unixFile *pFile = (unixFile*)id;
   28593   switch( op ){
   28594     case SQLITE_FCNTL_LOCKSTATE: {
   28595       *(int*)pArg = pFile->eFileLock;
   28596       return SQLITE_OK;
   28597     }
   28598     case SQLITE_LAST_ERRNO: {
   28599       *(int*)pArg = pFile->lastErrno;
   28600       return SQLITE_OK;
   28601     }
   28602     case SQLITE_FCNTL_CHUNK_SIZE: {
   28603       pFile->szChunk = *(int *)pArg;
   28604       return SQLITE_OK;
   28605     }
   28606     case SQLITE_FCNTL_SIZE_HINT: {
   28607       int rc;
   28608       SimulateIOErrorBenign(1);
   28609       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
   28610       SimulateIOErrorBenign(0);
   28611       return rc;
   28612     }
   28613     case SQLITE_FCNTL_PERSIST_WAL: {
   28614       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
   28615       return SQLITE_OK;
   28616     }
   28617     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   28618       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
   28619       return SQLITE_OK;
   28620     }
   28621     case SQLITE_FCNTL_VFSNAME: {
   28622       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   28623       return SQLITE_OK;
   28624     }
   28625 #ifndef NDEBUG
   28626     /* The pager calls this method to signal that it has done
   28627     ** a rollback and that the database is therefore unchanged and
   28628     ** it hence it is OK for the transaction change counter to be
   28629     ** unchanged.
   28630     */
   28631     case SQLITE_FCNTL_DB_UNCHANGED: {
   28632       ((unixFile*)id)->dbUpdate = 0;
   28633       return SQLITE_OK;
   28634     }
   28635 #endif
   28636 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28637     case SQLITE_SET_LOCKPROXYFILE:
   28638     case SQLITE_GET_LOCKPROXYFILE: {
   28639       return proxyFileControl(id,op,pArg);
   28640     }
   28641 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   28642   }
   28643   return SQLITE_NOTFOUND;
   28644 }
   28645 
   28646 /*
   28647 ** Return the sector size in bytes of the underlying block device for
   28648 ** the specified file. This is almost always 512 bytes, but may be
   28649 ** larger for some devices.
   28650 **
   28651 ** SQLite code assumes this function cannot fail. It also assumes that
   28652 ** if two files are created in the same file-system directory (i.e.
   28653 ** a database and its journal file) that the sector size will be the
   28654 ** same for both.
   28655 */
   28656 static int unixSectorSize(sqlite3_file *pFile){
   28657   (void)pFile;
   28658   return SQLITE_DEFAULT_SECTOR_SIZE;
   28659 }
   28660 
   28661 /*
   28662 ** Return the device characteristics for the file.
   28663 **
   28664 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
   28665 ** However, that choice is contraversial since technically the underlying
   28666 ** file system does not always provide powersafe overwrites.  (In other
   28667 ** words, after a power-loss event, parts of the file that were never
   28668 ** written might end up being altered.)  However, non-PSOW behavior is very,
   28669 ** very rare.  And asserting PSOW makes a large reduction in the amount
   28670 ** of required I/O for journaling, since a lot of padding is eliminated.
   28671 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
   28672 ** available to turn it off and URI query parameter available to turn it off.
   28673 */
   28674 static int unixDeviceCharacteristics(sqlite3_file *id){
   28675   unixFile *p = (unixFile*)id;
   28676   if( p->ctrlFlags & UNIXFILE_PSOW ){
   28677     return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
   28678   }else{
   28679     return 0;
   28680   }
   28681 }
   28682 
   28683 #ifndef SQLITE_OMIT_WAL
   28684 
   28685 
   28686 /*
   28687 ** Object used to represent an shared memory buffer.
   28688 **
   28689 ** When multiple threads all reference the same wal-index, each thread
   28690 ** has its own unixShm object, but they all point to a single instance
   28691 ** of this unixShmNode object.  In other words, each wal-index is opened
   28692 ** only once per process.
   28693 **
   28694 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   28695 ** We could coalesce this object into unixInodeInfo, but that would mean
   28696 ** every open file that does not use shared memory (in other words, most
   28697 ** open files) would have to carry around this extra information.  So
   28698 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   28699 ** and the unixShmNode object is created only when needed.
   28700 **
   28701 ** unixMutexHeld() must be true when creating or destroying
   28702 ** this object or while reading or writing the following fields:
   28703 **
   28704 **      nRef
   28705 **
   28706 ** The following fields are read-only after the object is created:
   28707 **
   28708 **      fid
   28709 **      zFilename
   28710 **
   28711 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   28712 ** unixMutexHeld() is true when reading or writing any other field
   28713 ** in this structure.
   28714 */
   28715 struct unixShmNode {
   28716   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   28717   sqlite3_mutex *mutex;      /* Mutex to access this object */
   28718   char *zFilename;           /* Name of the mmapped file */
   28719   int h;                     /* Open file descriptor */
   28720   int szRegion;              /* Size of shared-memory regions */
   28721   u16 nRegion;               /* Size of array apRegion */
   28722   u8 isReadonly;             /* True if read-only */
   28723   char **apRegion;           /* Array of mapped shared-memory regions */
   28724   int nRef;                  /* Number of unixShm objects pointing to this */
   28725   unixShm *pFirst;           /* All unixShm objects pointing to this */
   28726 #ifdef SQLITE_DEBUG
   28727   u8 exclMask;               /* Mask of exclusive locks held */
   28728   u8 sharedMask;             /* Mask of shared locks held */
   28729   u8 nextShmId;              /* Next available unixShm.id value */
   28730 #endif
   28731 };
   28732 
   28733 /*
   28734 ** Structure used internally by this VFS to record the state of an
   28735 ** open shared memory connection.
   28736 **
   28737 ** The following fields are initialized when this object is created and
   28738 ** are read-only thereafter:
   28739 **
   28740 **    unixShm.pFile
   28741 **    unixShm.id
   28742 **
   28743 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   28744 ** while accessing any read/write fields.
   28745 */
   28746 struct unixShm {
   28747   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   28748   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   28749   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   28750   u8 id;                     /* Id of this connection within its unixShmNode */
   28751   u16 sharedMask;            /* Mask of shared locks held */
   28752   u16 exclMask;              /* Mask of exclusive locks held */
   28753 };
   28754 
   28755 /*
   28756 ** Constants used for locking
   28757 */
   28758 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   28759 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   28760 
   28761 /*
   28762 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   28763 **
   28764 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   28765 ** otherwise.
   28766 */
   28767 static int unixShmSystemLock(
   28768   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   28769   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   28770   int ofst,              /* First byte of the locking range */
   28771   int n                  /* Number of bytes to lock */
   28772 ){
   28773   struct flock f;       /* The posix advisory locking structure */
   28774   int rc = SQLITE_OK;   /* Result code form fcntl() */
   28775 
   28776   /* Access to the unixShmNode object is serialized by the caller */
   28777   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   28778 
   28779   /* Shared locks never span more than one byte */
   28780   assert( n==1 || lockType!=F_RDLCK );
   28781 
   28782   /* Locks are within range */
   28783   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   28784 
   28785   if( pShmNode->h>=0 ){
   28786     /* Initialize the locking parameters */
   28787     memset(&f, 0, sizeof(f));
   28788     f.l_type = lockType;
   28789     f.l_whence = SEEK_SET;
   28790     f.l_start = ofst;
   28791     f.l_len = n;
   28792 
   28793     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   28794     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   28795   }
   28796 
   28797   /* Update the global lock state and do debug tracing */
   28798 #ifdef SQLITE_DEBUG
   28799   { u16 mask;
   28800   OSTRACE(("SHM-LOCK "));
   28801   mask = (1<<(ofst+n)) - (1<<ofst);
   28802   if( rc==SQLITE_OK ){
   28803     if( lockType==F_UNLCK ){
   28804       OSTRACE(("unlock %d ok", ofst));
   28805       pShmNode->exclMask &= ~mask;
   28806       pShmNode->sharedMask &= ~mask;
   28807     }else if( lockType==F_RDLCK ){
   28808       OSTRACE(("read-lock %d ok", ofst));
   28809       pShmNode->exclMask &= ~mask;
   28810       pShmNode->sharedMask |= mask;
   28811     }else{
   28812       assert( lockType==F_WRLCK );
   28813       OSTRACE(("write-lock %d ok", ofst));
   28814       pShmNode->exclMask |= mask;
   28815       pShmNode->sharedMask &= ~mask;
   28816     }
   28817   }else{
   28818     if( lockType==F_UNLCK ){
   28819       OSTRACE(("unlock %d failed", ofst));
   28820     }else if( lockType==F_RDLCK ){
   28821       OSTRACE(("read-lock failed"));
   28822     }else{
   28823       assert( lockType==F_WRLCK );
   28824       OSTRACE(("write-lock %d failed", ofst));
   28825     }
   28826   }
   28827   OSTRACE((" - afterwards %03x,%03x\n",
   28828            pShmNode->sharedMask, pShmNode->exclMask));
   28829   }
   28830 #endif
   28831 
   28832   return rc;
   28833 }
   28834 
   28835 
   28836 /*
   28837 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   28838 **
   28839 ** This is not a VFS shared-memory method; it is a utility function called
   28840 ** by VFS shared-memory methods.
   28841 */
   28842 static void unixShmPurge(unixFile *pFd){
   28843   unixShmNode *p = pFd->pInode->pShmNode;
   28844   assert( unixMutexHeld() );
   28845   if( p && p->nRef==0 ){
   28846     int i;
   28847     assert( p->pInode==pFd->pInode );
   28848     sqlite3_mutex_free(p->mutex);
   28849     for(i=0; i<p->nRegion; i++){
   28850       if( p->h>=0 ){
   28851         munmap(p->apRegion[i], p->szRegion);
   28852       }else{
   28853         sqlite3_free(p->apRegion[i]);
   28854       }
   28855     }
   28856     sqlite3_free(p->apRegion);
   28857     if( p->h>=0 ){
   28858       robust_close(pFd, p->h, __LINE__);
   28859       p->h = -1;
   28860     }
   28861     p->pInode->pShmNode = 0;
   28862     sqlite3_free(p);
   28863   }
   28864 }
   28865 
   28866 /*
   28867 ** Open a shared-memory area associated with open database file pDbFd.
   28868 ** This particular implementation uses mmapped files.
   28869 **
   28870 ** The file used to implement shared-memory is in the same directory
   28871 ** as the open database file and has the same name as the open database
   28872 ** file with the "-shm" suffix added.  For example, if the database file
   28873 ** is "/home/user1/config.db" then the file that is created and mmapped
   28874 ** for shared memory will be called "/home/user1/config.db-shm".
   28875 **
   28876 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   28877 ** some other tmpfs mount. But if a file in a different directory
   28878 ** from the database file is used, then differing access permissions
   28879 ** or a chroot() might cause two different processes on the same
   28880 ** database to end up using different files for shared memory -
   28881 ** meaning that their memory would not really be shared - resulting
   28882 ** in database corruption.  Nevertheless, this tmpfs file usage
   28883 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   28884 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   28885 ** option results in an incompatible build of SQLite;  builds of SQLite
   28886 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   28887 ** same database file at the same time, database corruption will likely
   28888 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   28889 ** "unsupported" and may go away in a future SQLite release.
   28890 **
   28891 ** When opening a new shared-memory file, if no other instances of that
   28892 ** file are currently open, in this process or in other processes, then
   28893 ** the file must be truncated to zero length or have its header cleared.
   28894 **
   28895 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   28896 ** that means that an exclusive lock is held on the database file and
   28897 ** that no other processes are able to read or write the database.  In
   28898 ** that case, we do not really need shared memory.  No shared memory
   28899 ** file is created.  The shared memory will be simulated with heap memory.
   28900 */
   28901 static int unixOpenSharedMemory(unixFile *pDbFd){
   28902   struct unixShm *p = 0;          /* The connection to be opened */
   28903   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   28904   int rc;                         /* Result code */
   28905   unixInodeInfo *pInode;          /* The inode of fd */
   28906   char *zShmFilename;             /* Name of the file used for SHM */
   28907   int nShmFilename;               /* Size of the SHM filename in bytes */
   28908 
   28909   /* Allocate space for the new unixShm object. */
   28910   p = sqlite3_malloc( sizeof(*p) );
   28911   if( p==0 ) return SQLITE_NOMEM;
   28912   memset(p, 0, sizeof(*p));
   28913   assert( pDbFd->pShm==0 );
   28914 
   28915   /* Check to see if a unixShmNode object already exists. Reuse an existing
   28916   ** one if present. Create a new one if necessary.
   28917   */
   28918   unixEnterMutex();
   28919   pInode = pDbFd->pInode;
   28920   pShmNode = pInode->pShmNode;
   28921   if( pShmNode==0 ){
   28922     struct stat sStat;                 /* fstat() info for database file */
   28923 
   28924     /* Call fstat() to figure out the permissions on the database file. If
   28925     ** a new *-shm file is created, an attempt will be made to create it
   28926     ** with the same permissions.
   28927     */
   28928     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
   28929       rc = unixLogError(SQLITE_IOERR_FSTAT, "fstat", pDbFd->zPath);
   28930       goto shm_open_err;
   28931     }
   28932 
   28933 #ifdef SQLITE_SHM_DIRECTORY
   28934     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
   28935 #else
   28936     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
   28937 #endif
   28938     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   28939     if( pShmNode==0 ){
   28940       rc = SQLITE_NOMEM;
   28941       goto shm_open_err;
   28942     }
   28943     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
   28944     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   28945 #ifdef SQLITE_SHM_DIRECTORY
   28946     sqlite3_snprintf(nShmFilename, zShmFilename,
   28947                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   28948                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   28949 #else
   28950     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   28951     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
   28952 #endif
   28953     pShmNode->h = -1;
   28954     pDbFd->pInode->pShmNode = pShmNode;
   28955     pShmNode->pInode = pDbFd->pInode;
   28956     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   28957     if( pShmNode->mutex==0 ){
   28958       rc = SQLITE_NOMEM;
   28959       goto shm_open_err;
   28960     }
   28961 
   28962     if( pInode->bProcessLock==0 ){
   28963       int openFlags = O_RDWR | O_CREAT;
   28964       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   28965         openFlags = O_RDONLY;
   28966         pShmNode->isReadonly = 1;
   28967       }
   28968       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
   28969       if( pShmNode->h<0 ){
   28970         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   28971         goto shm_open_err;
   28972       }
   28973 
   28974       /* If this process is running as root, make sure that the SHM file
   28975       ** is owned by the same user that owns the original database.  Otherwise,
   28976       ** the original owner will not be able to connect. If this process is
   28977       ** not root, the following fchown() will fail, but we don't care.  The
   28978       ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
   28979       ** warnings.
   28980       */
   28981       if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
   28982         pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
   28983       }
   28984 
   28985       /* Check to see if another process is holding the dead-man switch.
   28986       ** If not, truncate the file to zero length.
   28987       */
   28988       rc = SQLITE_OK;
   28989       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   28990         if( robust_ftruncate(pShmNode->h, 0) ){
   28991           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   28992         }
   28993       }
   28994       if( rc==SQLITE_OK ){
   28995         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   28996       }
   28997       if( rc ) goto shm_open_err;
   28998     }
   28999   }
   29000 
   29001   /* Make the new connection a child of the unixShmNode */
   29002   p->pShmNode = pShmNode;
   29003 #ifdef SQLITE_DEBUG
   29004   p->id = pShmNode->nextShmId++;
   29005 #endif
   29006   pShmNode->nRef++;
   29007   pDbFd->pShm = p;
   29008   unixLeaveMutex();
   29009 
   29010   /* The reference count on pShmNode has already been incremented under
   29011   ** the cover of the unixEnterMutex() mutex and the pointer from the
   29012   ** new (struct unixShm) object to the pShmNode has been set. All that is
   29013   ** left to do is to link the new object into the linked list starting
   29014   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   29015   ** mutex.
   29016   */
   29017   sqlite3_mutex_enter(pShmNode->mutex);
   29018   p->pNext = pShmNode->pFirst;
   29019   pShmNode->pFirst = p;
   29020   sqlite3_mutex_leave(pShmNode->mutex);
   29021   return SQLITE_OK;
   29022 
   29023   /* Jump here on any error */
   29024 shm_open_err:
   29025   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   29026   sqlite3_free(p);
   29027   unixLeaveMutex();
   29028   return rc;
   29029 }
   29030 
   29031 /*
   29032 ** This function is called to obtain a pointer to region iRegion of the
   29033 ** shared-memory associated with the database file fd. Shared-memory regions
   29034 ** are numbered starting from zero. Each shared-memory region is szRegion
   29035 ** bytes in size.
   29036 **
   29037 ** If an error occurs, an error code is returned and *pp is set to NULL.
   29038 **
   29039 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   29040 ** region has not been allocated (by any client, including one running in a
   29041 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   29042 ** bExtend is non-zero and the requested shared-memory region has not yet
   29043 ** been allocated, it is allocated by this function.
   29044 **
   29045 ** If the shared-memory region has already been allocated or is allocated by
   29046 ** this call as described above, then it is mapped into this processes
   29047 ** address space (if it is not already), *pp is set to point to the mapped
   29048 ** memory and SQLITE_OK returned.
   29049 */
   29050 static int unixShmMap(
   29051   sqlite3_file *fd,               /* Handle open on database file */
   29052   int iRegion,                    /* Region to retrieve */
   29053   int szRegion,                   /* Size of regions */
   29054   int bExtend,                    /* True to extend file if necessary */
   29055   void volatile **pp              /* OUT: Mapped memory */
   29056 ){
   29057   unixFile *pDbFd = (unixFile*)fd;
   29058   unixShm *p;
   29059   unixShmNode *pShmNode;
   29060   int rc = SQLITE_OK;
   29061 
   29062   /* If the shared-memory file has not yet been opened, open it now. */
   29063   if( pDbFd->pShm==0 ){
   29064     rc = unixOpenSharedMemory(pDbFd);
   29065     if( rc!=SQLITE_OK ) return rc;
   29066   }
   29067 
   29068   p = pDbFd->pShm;
   29069   pShmNode = p->pShmNode;
   29070   sqlite3_mutex_enter(pShmNode->mutex);
   29071   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   29072   assert( pShmNode->pInode==pDbFd->pInode );
   29073   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   29074   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   29075 
   29076   if( pShmNode->nRegion<=iRegion ){
   29077     char **apNew;                      /* New apRegion[] array */
   29078     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   29079     struct stat sStat;                 /* Used by fstat() */
   29080 
   29081     pShmNode->szRegion = szRegion;
   29082 
   29083     if( pShmNode->h>=0 ){
   29084       /* The requested region is not mapped into this processes address space.
   29085       ** Check to see if it has been allocated (i.e. if the wal-index file is
   29086       ** large enough to contain the requested region).
   29087       */
   29088       if( osFstat(pShmNode->h, &sStat) ){
   29089         rc = SQLITE_IOERR_SHMSIZE;
   29090         goto shmpage_out;
   29091       }
   29092 
   29093       if( sStat.st_size<nByte ){
   29094         /* The requested memory region does not exist. If bExtend is set to
   29095         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   29096         **
   29097         ** Alternatively, if bExtend is true, use ftruncate() to allocate
   29098         ** the requested memory region.
   29099         */
   29100         if( !bExtend ) goto shmpage_out;
   29101 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   29102         if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
   29103           rc = unixLogError(SQLITE_FULL, "fallocate",
   29104                             pShmNode->zFilename);
   29105           goto shmpage_out;
   29106         }
   29107 #else
   29108         if( robust_ftruncate(pShmNode->h, nByte) ){
   29109           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
   29110                             pShmNode->zFilename);
   29111           goto shmpage_out;
   29112         }
   29113 #endif
   29114       }
   29115     }
   29116 
   29117     /* Map the requested memory region into this processes address space. */
   29118     apNew = (char **)sqlite3_realloc(
   29119         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
   29120     );
   29121     if( !apNew ){
   29122       rc = SQLITE_IOERR_NOMEM;
   29123       goto shmpage_out;
   29124     }
   29125     pShmNode->apRegion = apNew;
   29126     while(pShmNode->nRegion<=iRegion){
   29127       void *pMem;
   29128       if( pShmNode->h>=0 ){
   29129         pMem = mmap(0, szRegion,
   29130             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
   29131             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
   29132         );
   29133         if( pMem==MAP_FAILED ){
   29134           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
   29135           goto shmpage_out;
   29136         }
   29137       }else{
   29138         pMem = sqlite3_malloc(szRegion);
   29139         if( pMem==0 ){
   29140           rc = SQLITE_NOMEM;
   29141           goto shmpage_out;
   29142         }
   29143         memset(pMem, 0, szRegion);
   29144       }
   29145       pShmNode->apRegion[pShmNode->nRegion] = pMem;
   29146       pShmNode->nRegion++;
   29147     }
   29148   }
   29149 
   29150 shmpage_out:
   29151   if( pShmNode->nRegion>iRegion ){
   29152     *pp = pShmNode->apRegion[iRegion];
   29153   }else{
   29154     *pp = 0;
   29155   }
   29156   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   29157   sqlite3_mutex_leave(pShmNode->mutex);
   29158   return rc;
   29159 }
   29160 
   29161 /*
   29162 ** Change the lock state for a shared-memory segment.
   29163 **
   29164 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   29165 ** different here than in posix.  In xShmLock(), one can go from unlocked
   29166 ** to shared and back or from unlocked to exclusive and back.  But one may
   29167 ** not go from shared to exclusive or from exclusive to shared.
   29168 */
   29169 static int unixShmLock(
   29170   sqlite3_file *fd,          /* Database file holding the shared memory */
   29171   int ofst,                  /* First lock to acquire or release */
   29172   int n,                     /* Number of locks to acquire or release */
   29173   int flags                  /* What to do with the lock */
   29174 ){
   29175   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   29176   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   29177   unixShm *pX;                          /* For looping over all siblings */
   29178   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   29179   int rc = SQLITE_OK;                   /* Result code */
   29180   u16 mask;                             /* Mask of locks to take or release */
   29181 
   29182   assert( pShmNode==pDbFd->pInode->pShmNode );
   29183   assert( pShmNode->pInode==pDbFd->pInode );
   29184   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   29185   assert( n>=1 );
   29186   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   29187        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   29188        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   29189        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   29190   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   29191   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   29192   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   29193 
   29194   mask = (1<<(ofst+n)) - (1<<ofst);
   29195   assert( n>1 || mask==(1<<ofst) );
   29196   sqlite3_mutex_enter(pShmNode->mutex);
   29197   if( flags & SQLITE_SHM_UNLOCK ){
   29198     u16 allMask = 0; /* Mask of locks held by siblings */
   29199 
   29200     /* See if any siblings hold this same lock */
   29201     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29202       if( pX==p ) continue;
   29203       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   29204       allMask |= pX->sharedMask;
   29205     }
   29206 
   29207     /* Unlock the system-level locks */
   29208     if( (mask & allMask)==0 ){
   29209       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   29210     }else{
   29211       rc = SQLITE_OK;
   29212     }
   29213 
   29214     /* Undo the local locks */
   29215     if( rc==SQLITE_OK ){
   29216       p->exclMask &= ~mask;
   29217       p->sharedMask &= ~mask;
   29218     }
   29219   }else if( flags & SQLITE_SHM_SHARED ){
   29220     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   29221 
   29222     /* Find out which shared locks are already held by sibling connections.
   29223     ** If any sibling already holds an exclusive lock, go ahead and return
   29224     ** SQLITE_BUSY.
   29225     */
   29226     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29227       if( (pX->exclMask & mask)!=0 ){
   29228         rc = SQLITE_BUSY;
   29229         break;
   29230       }
   29231       allShared |= pX->sharedMask;
   29232     }
   29233 
   29234     /* Get shared locks at the system level, if necessary */
   29235     if( rc==SQLITE_OK ){
   29236       if( (allShared & mask)==0 ){
   29237         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   29238       }else{
   29239         rc = SQLITE_OK;
   29240       }
   29241     }
   29242 
   29243     /* Get the local shared locks */
   29244     if( rc==SQLITE_OK ){
   29245       p->sharedMask |= mask;
   29246     }
   29247   }else{
   29248     /* Make sure no sibling connections hold locks that will block this
   29249     ** lock.  If any do, return SQLITE_BUSY right away.
   29250     */
   29251     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29252       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   29253         rc = SQLITE_BUSY;
   29254         break;
   29255       }
   29256     }
   29257 
   29258     /* Get the exclusive locks at the system level.  Then if successful
   29259     ** also mark the local connection as being locked.
   29260     */
   29261     if( rc==SQLITE_OK ){
   29262       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   29263       if( rc==SQLITE_OK ){
   29264         assert( (p->sharedMask & mask)==0 );
   29265         p->exclMask |= mask;
   29266       }
   29267     }
   29268   }
   29269   sqlite3_mutex_leave(pShmNode->mutex);
   29270   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   29271            p->id, getpid(), p->sharedMask, p->exclMask));
   29272   return rc;
   29273 }
   29274 
   29275 /*
   29276 ** Implement a memory barrier or memory fence on shared memory.
   29277 **
   29278 ** All loads and stores begun before the barrier must complete before
   29279 ** any load or store begun after the barrier.
   29280 */
   29281 static void unixShmBarrier(
   29282   sqlite3_file *fd                /* Database file holding the shared memory */
   29283 ){
   29284   UNUSED_PARAMETER(fd);
   29285   unixEnterMutex();
   29286   unixLeaveMutex();
   29287 }
   29288 
   29289 /*
   29290 ** Close a connection to shared-memory.  Delete the underlying
   29291 ** storage if deleteFlag is true.
   29292 **
   29293 ** If there is no shared memory associated with the connection then this
   29294 ** routine is a harmless no-op.
   29295 */
   29296 static int unixShmUnmap(
   29297   sqlite3_file *fd,               /* The underlying database file */
   29298   int deleteFlag                  /* Delete shared-memory if true */
   29299 ){
   29300   unixShm *p;                     /* The connection to be closed */
   29301   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   29302   unixShm **pp;                   /* For looping over sibling connections */
   29303   unixFile *pDbFd;                /* The underlying database file */
   29304 
   29305   pDbFd = (unixFile*)fd;
   29306   p = pDbFd->pShm;
   29307   if( p==0 ) return SQLITE_OK;
   29308   pShmNode = p->pShmNode;
   29309 
   29310   assert( pShmNode==pDbFd->pInode->pShmNode );
   29311   assert( pShmNode->pInode==pDbFd->pInode );
   29312 
   29313   /* Remove connection p from the set of connections associated
   29314   ** with pShmNode */
   29315   sqlite3_mutex_enter(pShmNode->mutex);
   29316   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   29317   *pp = p->pNext;
   29318 
   29319   /* Free the connection p */
   29320   sqlite3_free(p);
   29321   pDbFd->pShm = 0;
   29322   sqlite3_mutex_leave(pShmNode->mutex);
   29323 
   29324   /* If pShmNode->nRef has reached 0, then close the underlying
   29325   ** shared-memory file, too */
   29326   unixEnterMutex();
   29327   assert( pShmNode->nRef>0 );
   29328   pShmNode->nRef--;
   29329   if( pShmNode->nRef==0 ){
   29330     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
   29331     unixShmPurge(pDbFd);
   29332   }
   29333   unixLeaveMutex();
   29334 
   29335   return SQLITE_OK;
   29336 }
   29337 
   29338 
   29339 #else
   29340 # define unixShmMap     0
   29341 # define unixShmLock    0
   29342 # define unixShmBarrier 0
   29343 # define unixShmUnmap   0
   29344 #endif /* #ifndef SQLITE_OMIT_WAL */
   29345 
   29346 /*
   29347 ** Here ends the implementation of all sqlite3_file methods.
   29348 **
   29349 ********************** End sqlite3_file Methods *******************************
   29350 ******************************************************************************/
   29351 
   29352 /*
   29353 ** This division contains definitions of sqlite3_io_methods objects that
   29354 ** implement various file locking strategies.  It also contains definitions
   29355 ** of "finder" functions.  A finder-function is used to locate the appropriate
   29356 ** sqlite3_io_methods object for a particular database file.  The pAppData
   29357 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   29358 ** the correct finder-function for that VFS.
   29359 **
   29360 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   29361 ** object.  The only interesting finder-function is autolockIoFinder, which
   29362 ** looks at the filesystem type and tries to guess the best locking
   29363 ** strategy from that.
   29364 **
   29365 ** For finder-funtion F, two objects are created:
   29366 **
   29367 **    (1) The real finder-function named "FImpt()".
   29368 **
   29369 **    (2) A constant pointer to this function named just "F".
   29370 **
   29371 **
   29372 ** A pointer to the F pointer is used as the pAppData value for VFS
   29373 ** objects.  We have to do this instead of letting pAppData point
   29374 ** directly at the finder-function since C90 rules prevent a void*
   29375 ** from be cast into a function pointer.
   29376 **
   29377 **
   29378 ** Each instance of this macro generates two objects:
   29379 **
   29380 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   29381 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   29382 **
   29383 **   *  An I/O method finder function called FINDER that returns a pointer
   29384 **      to the METHOD object in the previous bullet.
   29385 */
   29386 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   29387 static const sqlite3_io_methods METHOD = {                                   \
   29388    VERSION,                    /* iVersion */                                \
   29389    CLOSE,                      /* xClose */                                  \
   29390    unixRead,                   /* xRead */                                   \
   29391    unixWrite,                  /* xWrite */                                  \
   29392    unixTruncate,               /* xTruncate */                               \
   29393    unixSync,                   /* xSync */                                   \
   29394    unixFileSize,               /* xFileSize */                               \
   29395    LOCK,                       /* xLock */                                   \
   29396    UNLOCK,                     /* xUnlock */                                 \
   29397    CKLOCK,                     /* xCheckReservedLock */                      \
   29398    unixFileControl,            /* xFileControl */                            \
   29399    unixSectorSize,             /* xSectorSize */                             \
   29400    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   29401    unixShmMap,                 /* xShmMap */                                 \
   29402    unixShmLock,                /* xShmLock */                                \
   29403    unixShmBarrier,             /* xShmBarrier */                             \
   29404    unixShmUnmap                /* xShmUnmap */                               \
   29405 };                                                                           \
   29406 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   29407   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   29408   return &METHOD;                                                            \
   29409 }                                                                            \
   29410 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   29411     = FINDER##Impl;
   29412 
   29413 /*
   29414 ** Here are all of the sqlite3_io_methods objects for each of the
   29415 ** locking strategies.  Functions that return pointers to these methods
   29416 ** are also created.
   29417 */
   29418 IOMETHODS(
   29419   posixIoFinder,            /* Finder function name */
   29420   posixIoMethods,           /* sqlite3_io_methods object name */
   29421   2,                        /* shared memory is enabled */
   29422   unixClose,                /* xClose method */
   29423   unixLock,                 /* xLock method */
   29424   unixUnlock,               /* xUnlock method */
   29425   unixCheckReservedLock     /* xCheckReservedLock method */
   29426 )
   29427 IOMETHODS(
   29428   nolockIoFinder,           /* Finder function name */
   29429   nolockIoMethods,          /* sqlite3_io_methods object name */
   29430   1,                        /* shared memory is disabled */
   29431   nolockClose,              /* xClose method */
   29432   nolockLock,               /* xLock method */
   29433   nolockUnlock,             /* xUnlock method */
   29434   nolockCheckReservedLock   /* xCheckReservedLock method */
   29435 )
   29436 IOMETHODS(
   29437   dotlockIoFinder,          /* Finder function name */
   29438   dotlockIoMethods,         /* sqlite3_io_methods object name */
   29439   1,                        /* shared memory is disabled */
   29440   dotlockClose,             /* xClose method */
   29441   dotlockLock,              /* xLock method */
   29442   dotlockUnlock,            /* xUnlock method */
   29443   dotlockCheckReservedLock  /* xCheckReservedLock method */
   29444 )
   29445 
   29446 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   29447 IOMETHODS(
   29448   flockIoFinder,            /* Finder function name */
   29449   flockIoMethods,           /* sqlite3_io_methods object name */
   29450   1,                        /* shared memory is disabled */
   29451   flockClose,               /* xClose method */
   29452   flockLock,                /* xLock method */
   29453   flockUnlock,              /* xUnlock method */
   29454   flockCheckReservedLock    /* xCheckReservedLock method */
   29455 )
   29456 #endif
   29457 
   29458 #if OS_VXWORKS
   29459 IOMETHODS(
   29460   semIoFinder,              /* Finder function name */
   29461   semIoMethods,             /* sqlite3_io_methods object name */
   29462   1,                        /* shared memory is disabled */
   29463   semClose,                 /* xClose method */
   29464   semLock,                  /* xLock method */
   29465   semUnlock,                /* xUnlock method */
   29466   semCheckReservedLock      /* xCheckReservedLock method */
   29467 )
   29468 #endif
   29469 
   29470 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29471 IOMETHODS(
   29472   afpIoFinder,              /* Finder function name */
   29473   afpIoMethods,             /* sqlite3_io_methods object name */
   29474   1,                        /* shared memory is disabled */
   29475   afpClose,                 /* xClose method */
   29476   afpLock,                  /* xLock method */
   29477   afpUnlock,                /* xUnlock method */
   29478   afpCheckReservedLock      /* xCheckReservedLock method */
   29479 )
   29480 #endif
   29481 
   29482 /*
   29483 ** The proxy locking method is a "super-method" in the sense that it
   29484 ** opens secondary file descriptors for the conch and lock files and
   29485 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   29486 ** secondary files.  For this reason, the division that implements
   29487 ** proxy locking is located much further down in the file.  But we need
   29488 ** to go ahead and define the sqlite3_io_methods and finder function
   29489 ** for proxy locking here.  So we forward declare the I/O methods.
   29490 */
   29491 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29492 static int proxyClose(sqlite3_file*);
   29493 static int proxyLock(sqlite3_file*, int);
   29494 static int proxyUnlock(sqlite3_file*, int);
   29495 static int proxyCheckReservedLock(sqlite3_file*, int*);
   29496 IOMETHODS(
   29497   proxyIoFinder,            /* Finder function name */
   29498   proxyIoMethods,           /* sqlite3_io_methods object name */
   29499   1,                        /* shared memory is disabled */
   29500   proxyClose,               /* xClose method */
   29501   proxyLock,                /* xLock method */
   29502   proxyUnlock,              /* xUnlock method */
   29503   proxyCheckReservedLock    /* xCheckReservedLock method */
   29504 )
   29505 #endif
   29506 
   29507 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   29508 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29509 IOMETHODS(
   29510   nfsIoFinder,               /* Finder function name */
   29511   nfsIoMethods,              /* sqlite3_io_methods object name */
   29512   1,                         /* shared memory is disabled */
   29513   unixClose,                 /* xClose method */
   29514   unixLock,                  /* xLock method */
   29515   nfsUnlock,                 /* xUnlock method */
   29516   unixCheckReservedLock      /* xCheckReservedLock method */
   29517 )
   29518 #endif
   29519 
   29520 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29521 /*
   29522 ** This "finder" function attempts to determine the best locking strategy
   29523 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29524 ** object that implements that strategy.
   29525 **
   29526 ** This is for MacOSX only.
   29527 */
   29528 static const sqlite3_io_methods *autolockIoFinderImpl(
   29529   const char *filePath,    /* name of the database file */
   29530   unixFile *pNew           /* open file object for the database file */
   29531 ){
   29532   static const struct Mapping {
   29533     const char *zFilesystem;              /* Filesystem type name */
   29534     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   29535   } aMap[] = {
   29536     { "hfs",    &posixIoMethods },
   29537     { "ufs",    &posixIoMethods },
   29538     { "afpfs",  &afpIoMethods },
   29539     { "smbfs",  &afpIoMethods },
   29540     { "webdav", &nolockIoMethods },
   29541     { 0, 0 }
   29542   };
   29543   int i;
   29544   struct statfs fsInfo;
   29545   struct flock lockInfo;
   29546 
   29547   if( !filePath ){
   29548     /* If filePath==NULL that means we are dealing with a transient file
   29549     ** that does not need to be locked. */
   29550     return &nolockIoMethods;
   29551   }
   29552   if( statfs(filePath, &fsInfo) != -1 ){
   29553     if( fsInfo.f_flags & MNT_RDONLY ){
   29554       return &nolockIoMethods;
   29555     }
   29556     for(i=0; aMap[i].zFilesystem; i++){
   29557       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   29558         return aMap[i].pMethods;
   29559       }
   29560     }
   29561   }
   29562 
   29563   /* Default case. Handles, amongst others, "nfs".
   29564   ** Test byte-range lock using fcntl(). If the call succeeds,
   29565   ** assume that the file-system supports POSIX style locks.
   29566   */
   29567   lockInfo.l_len = 1;
   29568   lockInfo.l_start = 0;
   29569   lockInfo.l_whence = SEEK_SET;
   29570   lockInfo.l_type = F_RDLCK;
   29571   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29572     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   29573       return &nfsIoMethods;
   29574     } else {
   29575       return &posixIoMethods;
   29576     }
   29577   }else{
   29578     return &dotlockIoMethods;
   29579   }
   29580 }
   29581 static const sqlite3_io_methods
   29582   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29583 
   29584 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   29585 
   29586 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   29587 /*
   29588 ** This "finder" function attempts to determine the best locking strategy
   29589 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29590 ** object that implements that strategy.
   29591 **
   29592 ** This is for VXWorks only.
   29593 */
   29594 static const sqlite3_io_methods *autolockIoFinderImpl(
   29595   const char *filePath,    /* name of the database file */
   29596   unixFile *pNew           /* the open file object */
   29597 ){
   29598   struct flock lockInfo;
   29599 
   29600   if( !filePath ){
   29601     /* If filePath==NULL that means we are dealing with a transient file
   29602     ** that does not need to be locked. */
   29603     return &nolockIoMethods;
   29604   }
   29605 
   29606   /* Test if fcntl() is supported and use POSIX style locks.
   29607   ** Otherwise fall back to the named semaphore method.
   29608   */
   29609   lockInfo.l_len = 1;
   29610   lockInfo.l_start = 0;
   29611   lockInfo.l_whence = SEEK_SET;
   29612   lockInfo.l_type = F_RDLCK;
   29613   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29614     return &posixIoMethods;
   29615   }else{
   29616     return &semIoMethods;
   29617   }
   29618 }
   29619 static const sqlite3_io_methods
   29620   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29621 
   29622 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   29623 
   29624 /*
   29625 ** An abstract type for a pointer to a IO method finder function:
   29626 */
   29627 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   29628 
   29629 
   29630 /****************************************************************************
   29631 **************************** sqlite3_vfs methods ****************************
   29632 **
   29633 ** This division contains the implementation of methods on the
   29634 ** sqlite3_vfs object.
   29635 */
   29636 
   29637 /*
   29638 ** Initialize the contents of the unixFile structure pointed to by pId.
   29639 */
   29640 static int fillInUnixFile(
   29641   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   29642   int h,                  /* Open file descriptor of file being opened */
   29643   sqlite3_file *pId,      /* Write to the unixFile structure here */
   29644   const char *zFilename,  /* Name of the file being opened */
   29645   int ctrlFlags           /* Zero or more UNIXFILE_* values */
   29646 ){
   29647   const sqlite3_io_methods *pLockingStyle;
   29648   unixFile *pNew = (unixFile *)pId;
   29649   int rc = SQLITE_OK;
   29650 
   29651   assert( pNew->pInode==NULL );
   29652 
   29653   /* Usually the path zFilename should not be a relative pathname. The
   29654   ** exception is when opening the proxy "conch" file in builds that
   29655   ** include the special Apple locking styles.
   29656   */
   29657 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29658   assert( zFilename==0 || zFilename[0]=='/'
   29659     || pVfs->pAppData==(void*)&autolockIoFinder );
   29660 #else
   29661   assert( zFilename==0 || zFilename[0]=='/' );
   29662 #endif
   29663 
   29664   /* No locking occurs in temporary files */
   29665   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
   29666 
   29667   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   29668   pNew->h = h;
   29669   pNew->pVfs = pVfs;
   29670   pNew->zPath = zFilename;
   29671   pNew->ctrlFlags = (u8)ctrlFlags;
   29672   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
   29673                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   29674     pNew->ctrlFlags |= UNIXFILE_PSOW;
   29675   }
   29676   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
   29677     pNew->ctrlFlags |= UNIXFILE_EXCL;
   29678   }
   29679 
   29680 #if OS_VXWORKS
   29681   pNew->pId = vxworksFindFileId(zFilename);
   29682   if( pNew->pId==0 ){
   29683     ctrlFlags |= UNIXFILE_NOLOCK;
   29684     rc = SQLITE_NOMEM;
   29685   }
   29686 #endif
   29687 
   29688   if( ctrlFlags & UNIXFILE_NOLOCK ){
   29689     pLockingStyle = &nolockIoMethods;
   29690   }else{
   29691     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   29692 #if SQLITE_ENABLE_LOCKING_STYLE
   29693     /* Cache zFilename in the locking context (AFP and dotlock override) for
   29694     ** proxyLock activation is possible (remote proxy is based on db name)
   29695     ** zFilename remains valid until file is closed, to support */
   29696     pNew->lockingContext = (void*)zFilename;
   29697 #endif
   29698   }
   29699 
   29700   if( pLockingStyle == &posixIoMethods
   29701 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29702     || pLockingStyle == &nfsIoMethods
   29703 #endif
   29704   ){
   29705     unixEnterMutex();
   29706     rc = findInodeInfo(pNew, &pNew->pInode);
   29707     if( rc!=SQLITE_OK ){
   29708       /* If an error occured in findInodeInfo(), close the file descriptor
   29709       ** immediately, before releasing the mutex. findInodeInfo() may fail
   29710       ** in two scenarios:
   29711       **
   29712       **   (a) A call to fstat() failed.
   29713       **   (b) A malloc failed.
   29714       **
   29715       ** Scenario (b) may only occur if the process is holding no other
   29716       ** file descriptors open on the same file. If there were other file
   29717       ** descriptors on this file, then no malloc would be required by
   29718       ** findInodeInfo(). If this is the case, it is quite safe to close
   29719       ** handle h - as it is guaranteed that no posix locks will be released
   29720       ** by doing so.
   29721       **
   29722       ** If scenario (a) caused the error then things are not so safe. The
   29723       ** implicit assumption here is that if fstat() fails, things are in
   29724       ** such bad shape that dropping a lock or two doesn't matter much.
   29725       */
   29726       robust_close(pNew, h, __LINE__);
   29727       h = -1;
   29728     }
   29729     unixLeaveMutex();
   29730   }
   29731 
   29732 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29733   else if( pLockingStyle == &afpIoMethods ){
   29734     /* AFP locking uses the file path so it needs to be included in
   29735     ** the afpLockingContext.
   29736     */
   29737     afpLockingContext *pCtx;
   29738     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   29739     if( pCtx==0 ){
   29740       rc = SQLITE_NOMEM;
   29741     }else{
   29742       /* NB: zFilename exists and remains valid until the file is closed
   29743       ** according to requirement F11141.  So we do not need to make a
   29744       ** copy of the filename. */
   29745       pCtx->dbPath = zFilename;
   29746       pCtx->reserved = 0;
   29747       srandomdev();
   29748       unixEnterMutex();
   29749       rc = findInodeInfo(pNew, &pNew->pInode);
   29750       if( rc!=SQLITE_OK ){
   29751         sqlite3_free(pNew->lockingContext);
   29752         robust_close(pNew, h, __LINE__);
   29753         h = -1;
   29754       }
   29755       unixLeaveMutex();
   29756     }
   29757   }
   29758 #endif
   29759 
   29760   else if( pLockingStyle == &dotlockIoMethods ){
   29761     /* Dotfile locking uses the file path so it needs to be included in
   29762     ** the dotlockLockingContext
   29763     */
   29764     char *zLockFile;
   29765     int nFilename;
   29766     assert( zFilename!=0 );
   29767     nFilename = (int)strlen(zFilename) + 6;
   29768     zLockFile = (char *)sqlite3_malloc(nFilename);
   29769     if( zLockFile==0 ){
   29770       rc = SQLITE_NOMEM;
   29771     }else{
   29772       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   29773     }
   29774     pNew->lockingContext = zLockFile;
   29775   }
   29776 
   29777 #if OS_VXWORKS
   29778   else if( pLockingStyle == &semIoMethods ){
   29779     /* Named semaphore locking uses the file path so it needs to be
   29780     ** included in the semLockingContext
   29781     */
   29782     unixEnterMutex();
   29783     rc = findInodeInfo(pNew, &pNew->pInode);
   29784     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   29785       char *zSemName = pNew->pInode->aSemName;
   29786       int n;
   29787       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   29788                        pNew->pId->zCanonicalName);
   29789       for( n=1; zSemName[n]; n++ )
   29790         if( zSemName[n]=='/' ) zSemName[n] = '_';
   29791       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   29792       if( pNew->pInode->pSem == SEM_FAILED ){
   29793         rc = SQLITE_NOMEM;
   29794         pNew->pInode->aSemName[0] = '\0';
   29795       }
   29796     }
   29797     unixLeaveMutex();
   29798   }
   29799 #endif
   29800 
   29801   pNew->lastErrno = 0;
   29802 #if OS_VXWORKS
   29803   if( rc!=SQLITE_OK ){
   29804     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29805     h = -1;
   29806     osUnlink(zFilename);
   29807     isDelete = 0;
   29808   }
   29809   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
   29810 #endif
   29811   if( rc!=SQLITE_OK ){
   29812     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29813   }else{
   29814     pNew->pMethod = pLockingStyle;
   29815     OpenCounter(+1);
   29816   }
   29817   return rc;
   29818 }
   29819 
   29820 /*
   29821 ** Return the name of a directory in which to put temporary files.
   29822 ** If no suitable temporary file directory can be found, return NULL.
   29823 */
   29824 static const char *unixTempFileDir(void){
   29825   static const char *azDirs[] = {
   29826      0,
   29827      0,
   29828      "/var/tmp",
   29829      "/usr/tmp",
   29830      "/tmp",
   29831      0        /* List terminator */
   29832   };
   29833   unsigned int i;
   29834   struct stat buf;
   29835   const char *zDir = 0;
   29836 
   29837   azDirs[0] = sqlite3_temp_directory;
   29838   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   29839   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   29840     if( zDir==0 ) continue;
   29841     if( osStat(zDir, &buf) ) continue;
   29842     if( !S_ISDIR(buf.st_mode) ) continue;
   29843     if( osAccess(zDir, 07) ) continue;
   29844     break;
   29845   }
   29846   return zDir;
   29847 }
   29848 
   29849 /*
   29850 ** Create a temporary file name in zBuf.  zBuf must be allocated
   29851 ** by the calling process and must be big enough to hold at least
   29852 ** pVfs->mxPathname bytes.
   29853 */
   29854 static int unixGetTempname(int nBuf, char *zBuf){
   29855   static const unsigned char zChars[] =
   29856     "abcdefghijklmnopqrstuvwxyz"
   29857     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   29858     "0123456789";
   29859   unsigned int i, j;
   29860   const char *zDir;
   29861 
   29862   /* It's odd to simulate an io-error here, but really this is just
   29863   ** using the io-error infrastructure to test that SQLite handles this
   29864   ** function failing.
   29865   */
   29866   SimulateIOError( return SQLITE_IOERR );
   29867 
   29868   zDir = unixTempFileDir();
   29869   if( zDir==0 ) zDir = ".";
   29870 
   29871   /* Check that the output buffer is large enough for the temporary file
   29872   ** name. If it is not, return SQLITE_ERROR.
   29873   */
   29874   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
   29875     return SQLITE_ERROR;
   29876   }
   29877 
   29878   do{
   29879     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   29880     j = (int)strlen(zBuf);
   29881     sqlite3_randomness(15, &zBuf[j]);
   29882     for(i=0; i<15; i++, j++){
   29883       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   29884     }
   29885     zBuf[j] = 0;
   29886     zBuf[j+1] = 0;
   29887   }while( osAccess(zBuf,0)==0 );
   29888   return SQLITE_OK;
   29889 }
   29890 
   29891 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29892 /*
   29893 ** Routine to transform a unixFile into a proxy-locking unixFile.
   29894 ** Implementation in the proxy-lock division, but used by unixOpen()
   29895 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   29896 */
   29897 static int proxyTransformUnixFile(unixFile*, const char*);
   29898 #endif
   29899 
   29900 /*
   29901 ** Search for an unused file descriptor that was opened on the database
   29902 ** file (not a journal or master-journal file) identified by pathname
   29903 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   29904 ** argument to this function.
   29905 **
   29906 ** Such a file descriptor may exist if a database connection was closed
   29907 ** but the associated file descriptor could not be closed because some
   29908 ** other file descriptor open on the same file is holding a file-lock.
   29909 ** Refer to comments in the unixClose() function and the lengthy comment
   29910 ** describing "Posix Advisory Locking" at the start of this file for
   29911 ** further details. Also, ticket #4018.
   29912 **
   29913 ** If a suitable file descriptor is found, then it is returned. If no
   29914 ** such file descriptor is located, -1 is returned.
   29915 */
   29916 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   29917   UnixUnusedFd *pUnused = 0;
   29918 
   29919   /* Do not search for an unused file descriptor on vxworks. Not because
   29920   ** vxworks would not benefit from the change (it might, we're not sure),
   29921   ** but because no way to test it is currently available. It is better
   29922   ** not to risk breaking vxworks support for the sake of such an obscure
   29923   ** feature.  */
   29924 #if !OS_VXWORKS
   29925   struct stat sStat;                   /* Results of stat() call */
   29926 
   29927   /* A stat() call may fail for various reasons. If this happens, it is
   29928   ** almost certain that an open() call on the same path will also fail.
   29929   ** For this reason, if an error occurs in the stat() call here, it is
   29930   ** ignored and -1 is returned. The caller will try to open a new file
   29931   ** descriptor on the same path, fail, and return an error to SQLite.
   29932   **
   29933   ** Even if a subsequent open() call does succeed, the consequences of
   29934   ** not searching for a resusable file descriptor are not dire.  */
   29935   if( 0==osStat(zPath, &sStat) ){
   29936     unixInodeInfo *pInode;
   29937 
   29938     unixEnterMutex();
   29939     pInode = inodeList;
   29940     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   29941                      || pInode->fileId.ino!=sStat.st_ino) ){
   29942        pInode = pInode->pNext;
   29943     }
   29944     if( pInode ){
   29945       UnixUnusedFd **pp;
   29946       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   29947       pUnused = *pp;
   29948       if( pUnused ){
   29949         *pp = pUnused->pNext;
   29950       }
   29951     }
   29952     unixLeaveMutex();
   29953   }
   29954 #endif    /* if !OS_VXWORKS */
   29955   return pUnused;
   29956 }
   29957 
   29958 /*
   29959 ** This function is called by unixOpen() to determine the unix permissions
   29960 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   29961 ** and a value suitable for passing as the third argument to open(2) is
   29962 ** written to *pMode. If an IO error occurs, an SQLite error code is
   29963 ** returned and the value of *pMode is not modified.
   29964 **
   29965 ** In most cases cases, this routine sets *pMode to 0, which will become
   29966 ** an indication to robust_open() to create the file using
   29967 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
   29968 ** But if the file being opened is a WAL or regular journal file, then
   29969 ** this function queries the file-system for the permissions on the
   29970 ** corresponding database file and sets *pMode to this value. Whenever
   29971 ** possible, WAL and journal files are created using the same permissions
   29972 ** as the associated database file.
   29973 **
   29974 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
   29975 ** original filename is unavailable.  But 8_3_NAMES is only used for
   29976 ** FAT filesystems and permissions do not matter there, so just use
   29977 ** the default permissions.
   29978 */
   29979 static int findCreateFileMode(
   29980   const char *zPath,              /* Path of file (possibly) being created */
   29981   int flags,                      /* Flags passed as 4th argument to xOpen() */
   29982   mode_t *pMode,                  /* OUT: Permissions to open file with */
   29983   uid_t *pUid,                    /* OUT: uid to set on the file */
   29984   gid_t *pGid                     /* OUT: gid to set on the file */
   29985 ){
   29986   int rc = SQLITE_OK;             /* Return Code */
   29987   *pMode = 0;
   29988   *pUid = 0;
   29989   *pGid = 0;
   29990   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   29991     char zDb[MAX_PATHNAME+1];     /* Database file path */
   29992     int nDb;                      /* Number of valid bytes in zDb */
   29993     struct stat sStat;            /* Output of stat() on database file */
   29994 
   29995     /* zPath is a path to a WAL or journal file. The following block derives
   29996     ** the path to the associated database file from zPath. This block handles
   29997     ** the following naming conventions:
   29998     **
   29999     **   "<path to db>-journal"
   30000     **   "<path to db>-wal"
   30001     **   "<path to db>-journalNN"
   30002     **   "<path to db>-walNN"
   30003     **
   30004     ** where NN is a decimal number. The NN naming schemes are
   30005     ** used by the test_multiplex.c module.
   30006     */
   30007     nDb = sqlite3Strlen30(zPath) - 1;
   30008 #ifdef SQLITE_ENABLE_8_3_NAMES
   30009     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
   30010     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
   30011 #else
   30012     while( zPath[nDb]!='-' ){
   30013       assert( nDb>0 );
   30014       assert( zPath[nDb]!='\n' );
   30015       nDb--;
   30016     }
   30017 #endif
   30018     memcpy(zDb, zPath, nDb);
   30019     zDb[nDb] = '\0';
   30020 
   30021     if( 0==osStat(zDb, &sStat) ){
   30022       *pMode = sStat.st_mode & 0777;
   30023       *pUid = sStat.st_uid;
   30024       *pGid = sStat.st_gid;
   30025     }else{
   30026       rc = unixLogError(SQLITE_IOERR_FSTAT, "stat", zDb);
   30027     }
   30028   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   30029     *pMode = 0600;
   30030   }
   30031   return rc;
   30032 }
   30033 
   30034 /*
   30035 ** Open the file zPath.
   30036 **
   30037 ** Previously, the SQLite OS layer used three functions in place of this
   30038 ** one:
   30039 **
   30040 **     sqlite3OsOpenReadWrite();
   30041 **     sqlite3OsOpenReadOnly();
   30042 **     sqlite3OsOpenExclusive();
   30043 **
   30044 ** These calls correspond to the following combinations of flags:
   30045 **
   30046 **     ReadWrite() ->     (READWRITE | CREATE)
   30047 **     ReadOnly()  ->     (READONLY)
   30048 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   30049 **
   30050 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   30051 ** true, the file was configured to be automatically deleted when the
   30052 ** file handle closed. To achieve the same effect using this new
   30053 ** interface, add the DELETEONCLOSE flag to those specified above for
   30054 ** OpenExclusive().
   30055 */
   30056 static int unixOpen(
   30057   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   30058   const char *zPath,           /* Pathname of file to be opened */
   30059   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   30060   int flags,                   /* Input flags to control the opening */
   30061   int *pOutFlags               /* Output flags returned to SQLite core */
   30062 ){
   30063   unixFile *p = (unixFile *)pFile;
   30064   int fd = -1;                   /* File descriptor returned by open() */
   30065   int openFlags = 0;             /* Flags to pass to open() */
   30066   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   30067   int noLock;                    /* True to omit locking primitives */
   30068   int rc = SQLITE_OK;            /* Function Return Code */
   30069   int ctrlFlags = 0;             /* UNIXFILE_* flags */
   30070 
   30071   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   30072   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   30073   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   30074   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   30075   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   30076 #if SQLITE_ENABLE_LOCKING_STYLE
   30077   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   30078 #endif
   30079 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30080   struct statfs fsInfo;
   30081 #endif
   30082 
   30083   /* If creating a master or main-file journal, this function will open
   30084   ** a file-descriptor on the directory too. The first time unixSync()
   30085   ** is called the directory file descriptor will be fsync()ed and close()d.
   30086   */
   30087   int syncDir = (isCreate && (
   30088         eType==SQLITE_OPEN_MASTER_JOURNAL
   30089      || eType==SQLITE_OPEN_MAIN_JOURNAL
   30090      || eType==SQLITE_OPEN_WAL
   30091   ));
   30092 
   30093   /* If argument zPath is a NULL pointer, this function is required to open
   30094   ** a temporary file. Use this buffer to store the file name in.
   30095   */
   30096   char zTmpname[MAX_PATHNAME+2];
   30097   const char *zName = zPath;
   30098 
   30099   /* Check the following statements are true:
   30100   **
   30101   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   30102   **   (b) if CREATE is set, then READWRITE must also be set, and
   30103   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   30104   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   30105   */
   30106   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   30107   assert(isCreate==0 || isReadWrite);
   30108   assert(isExclusive==0 || isCreate);
   30109   assert(isDelete==0 || isCreate);
   30110 
   30111   /* The main DB, main journal, WAL file and master journal are never
   30112   ** automatically deleted. Nor are they ever temporary files.  */
   30113   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   30114   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   30115   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   30116   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   30117 
   30118   /* Assert that the upper layer has set one of the "file-type" flags. */
   30119   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   30120        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   30121        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   30122        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   30123   );
   30124 
   30125   memset(p, 0, sizeof(unixFile));
   30126 
   30127   if( eType==SQLITE_OPEN_MAIN_DB ){
   30128     UnixUnusedFd *pUnused;
   30129     pUnused = findReusableFd(zName, flags);
   30130     if( pUnused ){
   30131       fd = pUnused->fd;
   30132     }else{
   30133       pUnused = sqlite3_malloc(sizeof(*pUnused));
   30134       if( !pUnused ){
   30135         return SQLITE_NOMEM;
   30136       }
   30137     }
   30138     p->pUnused = pUnused;
   30139 
   30140     /* Database filenames are double-zero terminated if they are not
   30141     ** URIs with parameters.  Hence, they can always be passed into
   30142     ** sqlite3_uri_parameter(). */
   30143     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
   30144 
   30145   }else if( !zName ){
   30146     /* If zName is NULL, the upper layer is requesting a temp file. */
   30147     assert(isDelete && !syncDir);
   30148     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
   30149     if( rc!=SQLITE_OK ){
   30150       return rc;
   30151     }
   30152     zName = zTmpname;
   30153 
   30154     /* Generated temporary filenames are always double-zero terminated
   30155     ** for use by sqlite3_uri_parameter(). */
   30156     assert( zName[strlen(zName)+1]==0 );
   30157   }
   30158 
   30159   /* Determine the value of the flags parameter passed to POSIX function
   30160   ** open(). These must be calculated even if open() is not called, as
   30161   ** they may be stored as part of the file handle and used by the
   30162   ** 'conch file' locking functions later on.  */
   30163   if( isReadonly )  openFlags |= O_RDONLY;
   30164   if( isReadWrite ) openFlags |= O_RDWR;
   30165   if( isCreate )    openFlags |= O_CREAT;
   30166   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   30167   openFlags |= (O_LARGEFILE|O_BINARY);
   30168 
   30169   if( fd<0 ){
   30170     mode_t openMode;              /* Permissions to create file with */
   30171     uid_t uid;                    /* Userid for the file */
   30172     gid_t gid;                    /* Groupid for the file */
   30173     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
   30174     if( rc!=SQLITE_OK ){
   30175       assert( !p->pUnused );
   30176       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   30177       return rc;
   30178     }
   30179     fd = robust_open(zName, openFlags, openMode);
   30180     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   30181     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   30182       /* Failed to open the file for read/write access. Try read-only. */
   30183       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   30184       openFlags &= ~(O_RDWR|O_CREAT);
   30185       flags |= SQLITE_OPEN_READONLY;
   30186       openFlags |= O_RDONLY;
   30187       isReadonly = 1;
   30188       fd = robust_open(zName, openFlags, openMode);
   30189     }
   30190     if( fd<0 ){
   30191       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   30192       goto open_finished;
   30193     }
   30194 
   30195     /* If this process is running as root and if creating a new rollback
   30196     ** journal or WAL file, set the ownership of the journal or WAL to be
   30197     ** the same as the original database.  If we are not running as root,
   30198     ** then the fchown() call will fail, but that's ok.  The "if(){}" and
   30199     ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
   30200     ** warnings from gcc.
   30201     */
   30202     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   30203       if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
   30204     }
   30205   }
   30206   assert( fd>=0 );
   30207   if( pOutFlags ){
   30208     *pOutFlags = flags;
   30209   }
   30210 
   30211   if( p->pUnused ){
   30212     p->pUnused->fd = fd;
   30213     p->pUnused->flags = flags;
   30214   }
   30215 
   30216   if( isDelete ){
   30217 #if OS_VXWORKS
   30218     zPath = zName;
   30219 #else
   30220     osUnlink(zName);
   30221 #endif
   30222   }
   30223 #if SQLITE_ENABLE_LOCKING_STYLE
   30224   else{
   30225     p->openFlags = openFlags;
   30226   }
   30227 #endif
   30228 
   30229 #ifdef FD_CLOEXEC
   30230   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   30231 #endif
   30232 
   30233   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   30234 
   30235 
   30236 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30237   if( fstatfs(fd, &fsInfo) == -1 ){
   30238     ((unixFile*)pFile)->lastErrno = errno;
   30239     robust_close(p, fd, __LINE__);
   30240     return SQLITE_IOERR_ACCESS;
   30241   }
   30242   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   30243     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   30244   }
   30245 #endif
   30246 
   30247   /* Set up appropriate ctrlFlags */
   30248   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
   30249   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
   30250   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
   30251   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
   30252   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
   30253 
   30254 #if SQLITE_ENABLE_LOCKING_STYLE
   30255 #if SQLITE_PREFER_PROXY_LOCKING
   30256   isAutoProxy = 1;
   30257 #endif
   30258   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   30259     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   30260     int useProxy = 0;
   30261 
   30262     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   30263     ** never use proxy, NULL means use proxy for non-local files only.  */
   30264     if( envforce!=NULL ){
   30265       useProxy = atoi(envforce)>0;
   30266     }else{
   30267       if( statfs(zPath, &fsInfo) == -1 ){
   30268         /* In theory, the close(fd) call is sub-optimal. If the file opened
   30269         ** with fd is a database file, and there are other connections open
   30270         ** on that file that are currently holding advisory locks on it,
   30271         ** then the call to close() will cancel those locks. In practice,
   30272         ** we're assuming that statfs() doesn't fail very often. At least
   30273         ** not while other file descriptors opened by the same process on
   30274         ** the same file are working.  */
   30275         p->lastErrno = errno;
   30276         robust_close(p, fd, __LINE__);
   30277         rc = SQLITE_IOERR_ACCESS;
   30278         goto open_finished;
   30279       }
   30280       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   30281     }
   30282     if( useProxy ){
   30283       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30284       if( rc==SQLITE_OK ){
   30285         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   30286         if( rc!=SQLITE_OK ){
   30287           /* Use unixClose to clean up the resources added in fillInUnixFile
   30288           ** and clear all the structure's references.  Specifically,
   30289           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   30290           */
   30291           unixClose(pFile);
   30292           return rc;
   30293         }
   30294       }
   30295       goto open_finished;
   30296     }
   30297   }
   30298 #endif
   30299 
   30300   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30301 
   30302 open_finished:
   30303   if( rc!=SQLITE_OK ){
   30304     sqlite3_free(p->pUnused);
   30305   }
   30306   return rc;
   30307 }
   30308 
   30309 
   30310 /*
   30311 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   30312 ** the directory after deleting the file.
   30313 */
   30314 static int unixDelete(
   30315   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   30316   const char *zPath,        /* Name of file to be deleted */
   30317   int dirSync               /* If true, fsync() directory after deleting file */
   30318 ){
   30319   int rc = SQLITE_OK;
   30320   UNUSED_PARAMETER(NotUsed);
   30321   SimulateIOError(return SQLITE_IOERR_DELETE);
   30322   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
   30323     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   30324   }
   30325 #ifndef SQLITE_DISABLE_DIRSYNC
   30326   if( (dirSync & 1)!=0 ){
   30327     int fd;
   30328     rc = osOpenDirectory(zPath, &fd);
   30329     if( rc==SQLITE_OK ){
   30330 #if OS_VXWORKS
   30331       if( fsync(fd)==-1 )
   30332 #else
   30333       if( fsync(fd) )
   30334 #endif
   30335       {
   30336         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   30337       }
   30338       robust_close(0, fd, __LINE__);
   30339     }else if( rc==SQLITE_CANTOPEN ){
   30340       rc = SQLITE_OK;
   30341     }
   30342   }
   30343 #endif
   30344   return rc;
   30345 }
   30346 
   30347 /*
   30348 ** Test the existance of or access permissions of file zPath. The
   30349 ** test performed depends on the value of flags:
   30350 **
   30351 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   30352 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   30353 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   30354 **
   30355 ** Otherwise return 0.
   30356 */
   30357 static int unixAccess(
   30358   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   30359   const char *zPath,      /* Path of the file to examine */
   30360   int flags,              /* What do we want to learn about the zPath file? */
   30361   int *pResOut            /* Write result boolean here */
   30362 ){
   30363   int amode = 0;
   30364   UNUSED_PARAMETER(NotUsed);
   30365   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   30366   switch( flags ){
   30367     case SQLITE_ACCESS_EXISTS:
   30368       amode = F_OK;
   30369       break;
   30370     case SQLITE_ACCESS_READWRITE:
   30371       amode = W_OK|R_OK;
   30372       break;
   30373     case SQLITE_ACCESS_READ:
   30374       amode = R_OK;
   30375       break;
   30376 
   30377     default:
   30378       assert(!"Invalid flags argument");
   30379   }
   30380   *pResOut = (osAccess(zPath, amode)==0);
   30381   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   30382     struct stat buf;
   30383     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
   30384       *pResOut = 0;
   30385     }
   30386   }
   30387   return SQLITE_OK;
   30388 }
   30389 
   30390 
   30391 /*
   30392 ** Turn a relative pathname into a full pathname. The relative path
   30393 ** is stored as a nul-terminated string in the buffer pointed to by
   30394 ** zPath.
   30395 **
   30396 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   30397 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   30398 ** this buffer before returning.
   30399 */
   30400 static int unixFullPathname(
   30401   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   30402   const char *zPath,            /* Possibly relative input path */
   30403   int nOut,                     /* Size of output buffer in bytes */
   30404   char *zOut                    /* Output buffer */
   30405 ){
   30406 
   30407   /* It's odd to simulate an io-error here, but really this is just
   30408   ** using the io-error infrastructure to test that SQLite handles this
   30409   ** function failing. This function could fail if, for example, the
   30410   ** current working directory has been unlinked.
   30411   */
   30412   SimulateIOError( return SQLITE_ERROR );
   30413 
   30414   assert( pVfs->mxPathname==MAX_PATHNAME );
   30415   UNUSED_PARAMETER(pVfs);
   30416 
   30417   zOut[nOut-1] = '\0';
   30418   if( zPath[0]=='/' ){
   30419     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   30420   }else{
   30421     int nCwd;
   30422     if( osGetcwd(zOut, nOut-1)==0 ){
   30423       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   30424     }
   30425     nCwd = (int)strlen(zOut);
   30426     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   30427   }
   30428   return SQLITE_OK;
   30429 }
   30430 
   30431 
   30432 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   30433 /*
   30434 ** Interfaces for opening a shared library, finding entry points
   30435 ** within the shared library, and closing the shared library.
   30436 */
   30437 #include <dlfcn.h>
   30438 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   30439   UNUSED_PARAMETER(NotUsed);
   30440   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   30441 }
   30442 
   30443 /*
   30444 ** SQLite calls this function immediately after a call to unixDlSym() or
   30445 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   30446 ** message is available, it is written to zBufOut. If no error message
   30447 ** is available, zBufOut is left unmodified and SQLite uses a default
   30448 ** error message.
   30449 */
   30450 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   30451   const char *zErr;
   30452   UNUSED_PARAMETER(NotUsed);
   30453   unixEnterMutex();
   30454   zErr = dlerror();
   30455   if( zErr ){
   30456     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   30457   }
   30458   unixLeaveMutex();
   30459 }
   30460 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   30461   /*
   30462   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   30463   ** cast into a pointer to a function.  And yet the library dlsym() routine
   30464   ** returns a void* which is really a pointer to a function.  So how do we
   30465   ** use dlsym() with -pedantic-errors?
   30466   **
   30467   ** Variable x below is defined to be a pointer to a function taking
   30468   ** parameters void* and const char* and returning a pointer to a function.
   30469   ** We initialize x by assigning it a pointer to the dlsym() function.
   30470   ** (That assignment requires a cast.)  Then we call the function that
   30471   ** x points to.
   30472   **
   30473   ** This work-around is unlikely to work correctly on any system where
   30474   ** you really cannot cast a function pointer into void*.  But then, on the
   30475   ** other hand, dlsym() will not work on such a system either, so we have
   30476   ** not really lost anything.
   30477   */
   30478   void (*(*x)(void*,const char*))(void);
   30479   UNUSED_PARAMETER(NotUsed);
   30480   x = (void(*(*)(void*,const char*))(void))dlsym;
   30481   return (*x)(p, zSym);
   30482 }
   30483 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   30484   UNUSED_PARAMETER(NotUsed);
   30485   dlclose(pHandle);
   30486 }
   30487 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   30488   #define unixDlOpen  0
   30489   #define unixDlError 0
   30490   #define unixDlSym   0
   30491   #define unixDlClose 0
   30492 #endif
   30493 
   30494 /*
   30495 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   30496 */
   30497 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   30498   UNUSED_PARAMETER(NotUsed);
   30499   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   30500 
   30501   /* We have to initialize zBuf to prevent valgrind from reporting
   30502   ** errors.  The reports issued by valgrind are incorrect - we would
   30503   ** prefer that the randomness be increased by making use of the
   30504   ** uninitialized space in zBuf - but valgrind errors tend to worry
   30505   ** some users.  Rather than argue, it seems easier just to initialize
   30506   ** the whole array and silence valgrind, even if that means less randomness
   30507   ** in the random seed.
   30508   **
   30509   ** When testing, initializing zBuf[] to zero is all we do.  That means
   30510   ** that we always use the same random number sequence.  This makes the
   30511   ** tests repeatable.
   30512   */
   30513   memset(zBuf, 0, nBuf);
   30514 #if !defined(SQLITE_TEST)
   30515   {
   30516     int pid, fd, got;
   30517     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   30518     if( fd<0 ){
   30519       time_t t;
   30520       time(&t);
   30521       memcpy(zBuf, &t, sizeof(t));
   30522       pid = getpid();
   30523       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
   30524       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
   30525       nBuf = sizeof(t) + sizeof(pid);
   30526     }else{
   30527       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
   30528       robust_close(0, fd, __LINE__);
   30529     }
   30530   }
   30531 #endif
   30532   return nBuf;
   30533 }
   30534 
   30535 
   30536 /*
   30537 ** Sleep for a little while.  Return the amount of time slept.
   30538 ** The argument is the number of microseconds we want to sleep.
   30539 ** The return value is the number of microseconds of sleep actually
   30540 ** requested from the underlying operating system, a number which
   30541 ** might be greater than or equal to the argument, but not less
   30542 ** than the argument.
   30543 */
   30544 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   30545 #if OS_VXWORKS
   30546   struct timespec sp;
   30547 
   30548   sp.tv_sec = microseconds / 1000000;
   30549   sp.tv_nsec = (microseconds % 1000000) * 1000;
   30550   nanosleep(&sp, NULL);
   30551   UNUSED_PARAMETER(NotUsed);
   30552   return microseconds;
   30553 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   30554   usleep(microseconds);
   30555   UNUSED_PARAMETER(NotUsed);
   30556   return microseconds;
   30557 #else
   30558   int seconds = (microseconds+999999)/1000000;
   30559   sleep(seconds);
   30560   UNUSED_PARAMETER(NotUsed);
   30561   return seconds*1000000;
   30562 #endif
   30563 }
   30564 
   30565 /*
   30566 ** The following variable, if set to a non-zero value, is interpreted as
   30567 ** the number of seconds since 1970 and is used to set the result of
   30568 ** sqlite3OsCurrentTime() during testing.
   30569 */
   30570 #ifdef SQLITE_TEST
   30571 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   30572 #endif
   30573 
   30574 /*
   30575 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   30576 ** the current time and date as a Julian Day number times 86_400_000.  In
   30577 ** other words, write into *piNow the number of milliseconds since the Julian
   30578 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   30579 ** proleptic Gregorian calendar.
   30580 **
   30581 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   30582 ** cannot be found.
   30583 */
   30584 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   30585   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   30586   int rc = SQLITE_OK;
   30587 #if defined(NO_GETTOD)
   30588   time_t t;
   30589   time(&t);
   30590   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   30591 #elif OS_VXWORKS
   30592   struct timespec sNow;
   30593   clock_gettime(CLOCK_REALTIME, &sNow);
   30594   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   30595 #else
   30596   struct timeval sNow;
   30597   if( gettimeofday(&sNow, 0)==0 ){
   30598     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   30599   }else{
   30600     rc = SQLITE_ERROR;
   30601   }
   30602 #endif
   30603 
   30604 #ifdef SQLITE_TEST
   30605   if( sqlite3_current_time ){
   30606     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   30607   }
   30608 #endif
   30609   UNUSED_PARAMETER(NotUsed);
   30610   return rc;
   30611 }
   30612 
   30613 /*
   30614 ** Find the current time (in Universal Coordinated Time).  Write the
   30615 ** current time and date as a Julian Day number into *prNow and
   30616 ** return 0.  Return 1 if the time and date cannot be found.
   30617 */
   30618 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   30619   sqlite3_int64 i = 0;
   30620   int rc;
   30621   UNUSED_PARAMETER(NotUsed);
   30622   rc = unixCurrentTimeInt64(0, &i);
   30623   *prNow = i/86400000.0;
   30624   return rc;
   30625 }
   30626 
   30627 /*
   30628 ** We added the xGetLastError() method with the intention of providing
   30629 ** better low-level error messages when operating-system problems come up
   30630 ** during SQLite operation.  But so far, none of that has been implemented
   30631 ** in the core.  So this routine is never called.  For now, it is merely
   30632 ** a place-holder.
   30633 */
   30634 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   30635   UNUSED_PARAMETER(NotUsed);
   30636   UNUSED_PARAMETER(NotUsed2);
   30637   UNUSED_PARAMETER(NotUsed3);
   30638   return 0;
   30639 }
   30640 
   30641 
   30642 /*
   30643 ************************ End of sqlite3_vfs methods ***************************
   30644 ******************************************************************************/
   30645 
   30646 /******************************************************************************
   30647 ************************** Begin Proxy Locking ********************************
   30648 **
   30649 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   30650 ** other locking methods on secondary lock files.  Proxy locking is a
   30651 ** meta-layer over top of the primitive locking implemented above.  For
   30652 ** this reason, the division that implements of proxy locking is deferred
   30653 ** until late in the file (here) after all of the other I/O methods have
   30654 ** been defined - so that the primitive locking methods are available
   30655 ** as services to help with the implementation of proxy locking.
   30656 **
   30657 ****
   30658 **
   30659 ** The default locking schemes in SQLite use byte-range locks on the
   30660 ** database file to coordinate safe, concurrent access by multiple readers
   30661 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   30662 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   30663 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   30664 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   30665 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   30666 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   30667 ** address in the shared range is taken for a SHARED lock, the entire
   30668 ** shared range is taken for an EXCLUSIVE lock):
   30669 **
   30670 **      PENDING_BYTE        0x40000000
   30671 **      RESERVED_BYTE       0x40000001
   30672 **      SHARED_RANGE        0x40000002 -> 0x40000200
   30673 **
   30674 ** This works well on the local file system, but shows a nearly 100x
   30675 ** slowdown in read performance on AFP because the AFP client disables
   30676 ** the read cache when byte-range locks are present.  Enabling the read
   30677 ** cache exposes a cache coherency problem that is present on all OS X
   30678 ** supported network file systems.  NFS and AFP both observe the
   30679 ** close-to-open semantics for ensuring cache coherency
   30680 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   30681 ** address the requirements for concurrent database access by multiple
   30682 ** readers and writers
   30683 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   30684 **
   30685 ** To address the performance and cache coherency issues, proxy file locking
   30686 ** changes the way database access is controlled by limiting access to a
   30687 ** single host at a time and moving file locks off of the database file
   30688 ** and onto a proxy file on the local file system.
   30689 **
   30690 **
   30691 ** Using proxy locks
   30692 ** -----------------
   30693 **
   30694 ** C APIs
   30695 **
   30696 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   30697 **                       <proxy_path> | ":auto:");
   30698 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   30699 **
   30700 **
   30701 ** SQL pragmas
   30702 **
   30703 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   30704 **  PRAGMA [database.]lock_proxy_file
   30705 **
   30706 ** Specifying ":auto:" means that if there is a conch file with a matching
   30707 ** host ID in it, the proxy path in the conch file will be used, otherwise
   30708 ** a proxy path based on the user's temp dir
   30709 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   30710 ** actual proxy file name is generated from the name and path of the
   30711 ** database file.  For example:
   30712 **
   30713 **       For database path "/Users/me/foo.db"
   30714 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   30715 **
   30716 ** Once a lock proxy is configured for a database connection, it can not
   30717 ** be removed, however it may be switched to a different proxy path via
   30718 ** the above APIs (assuming the conch file is not being held by another
   30719 ** connection or process).
   30720 **
   30721 **
   30722 ** How proxy locking works
   30723 ** -----------------------
   30724 **
   30725 ** Proxy file locking relies primarily on two new supporting files:
   30726 **
   30727 **   *  conch file to limit access to the database file to a single host
   30728 **      at a time
   30729 **
   30730 **   *  proxy file to act as a proxy for the advisory locks normally
   30731 **      taken on the database
   30732 **
   30733 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   30734 ** by taking an sqlite-style shared lock on the conch file, reading the
   30735 ** contents and comparing the host's unique host ID (see below) and lock
   30736 ** proxy path against the values stored in the conch.  The conch file is
   30737 ** stored in the same directory as the database file and the file name
   30738 ** is patterned after the database file name as ".<databasename>-conch".
   30739 ** If the conch file does not exist, or it's contents do not match the
   30740 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   30741 ** lock and the conch file contents is updated with the host ID and proxy
   30742 ** path and the lock is downgraded to a shared lock again.  If the conch
   30743 ** is held by another process (with a shared lock), the exclusive lock
   30744 ** will fail and SQLITE_BUSY is returned.
   30745 **
   30746 ** The proxy file - a single-byte file used for all advisory file locks
   30747 ** normally taken on the database file.   This allows for safe sharing
   30748 ** of the database file for multiple readers and writers on the same
   30749 ** host (the conch ensures that they all use the same local lock file).
   30750 **
   30751 ** Requesting the lock proxy does not immediately take the conch, it is
   30752 ** only taken when the first request to lock database file is made.
   30753 ** This matches the semantics of the traditional locking behavior, where
   30754 ** opening a connection to a database file does not take a lock on it.
   30755 ** The shared lock and an open file descriptor are maintained until
   30756 ** the connection to the database is closed.
   30757 **
   30758 ** The proxy file and the lock file are never deleted so they only need
   30759 ** to be created the first time they are used.
   30760 **
   30761 ** Configuration options
   30762 ** ---------------------
   30763 **
   30764 **  SQLITE_PREFER_PROXY_LOCKING
   30765 **
   30766 **       Database files accessed on non-local file systems are
   30767 **       automatically configured for proxy locking, lock files are
   30768 **       named automatically using the same logic as
   30769 **       PRAGMA lock_proxy_file=":auto:"
   30770 **
   30771 **  SQLITE_PROXY_DEBUG
   30772 **
   30773 **       Enables the logging of error messages during host id file
   30774 **       retrieval and creation
   30775 **
   30776 **  LOCKPROXYDIR
   30777 **
   30778 **       Overrides the default directory used for lock proxy files that
   30779 **       are named automatically via the ":auto:" setting
   30780 **
   30781 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   30782 **
   30783 **       Permissions to use when creating a directory for storing the
   30784 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   30785 **
   30786 **
   30787 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   30788 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   30789 ** force proxy locking to be used for every database file opened, and 0
   30790 ** will force automatic proxy locking to be disabled for all database
   30791 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   30792 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   30793 */
   30794 
   30795 /*
   30796 ** Proxy locking is only available on MacOSX
   30797 */
   30798 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   30799 
   30800 /*
   30801 ** The proxyLockingContext has the path and file structures for the remote
   30802 ** and local proxy files in it
   30803 */
   30804 typedef struct proxyLockingContext proxyLockingContext;
   30805 struct proxyLockingContext {
   30806   unixFile *conchFile;         /* Open conch file */
   30807   char *conchFilePath;         /* Name of the conch file */
   30808   unixFile *lockProxy;         /* Open proxy lock file */
   30809   char *lockProxyPath;         /* Name of the proxy lock file */
   30810   char *dbPath;                /* Name of the open file */
   30811   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   30812   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   30813   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   30814 };
   30815 
   30816 /*
   30817 ** The proxy lock file path for the database at dbPath is written into lPath,
   30818 ** which must point to valid, writable memory large enough for a maxLen length
   30819 ** file path.
   30820 */
   30821 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   30822   int len;
   30823   int dbLen;
   30824   int i;
   30825 
   30826 #ifdef LOCKPROXYDIR
   30827   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   30828 #else
   30829 # ifdef _CS_DARWIN_USER_TEMP_DIR
   30830   {
   30831     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   30832       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   30833                lPath, errno, getpid()));
   30834       return SQLITE_IOERR_LOCK;
   30835     }
   30836     len = strlcat(lPath, "sqliteplocks", maxLen);
   30837   }
   30838 # else
   30839   len = strlcpy(lPath, "/tmp/", maxLen);
   30840 # endif
   30841 #endif
   30842 
   30843   if( lPath[len-1]!='/' ){
   30844     len = strlcat(lPath, "/", maxLen);
   30845   }
   30846 
   30847   /* transform the db path to a unique cache name */
   30848   dbLen = (int)strlen(dbPath);
   30849   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   30850     char c = dbPath[i];
   30851     lPath[i+len] = (c=='/')?'_':c;
   30852   }
   30853   lPath[i+len]='\0';
   30854   strlcat(lPath, ":auto:", maxLen);
   30855   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   30856   return SQLITE_OK;
   30857 }
   30858 
   30859 /*
   30860  ** Creates the lock file and any missing directories in lockPath
   30861  */
   30862 static int proxyCreateLockPath(const char *lockPath){
   30863   int i, len;
   30864   char buf[MAXPATHLEN];
   30865   int start = 0;
   30866 
   30867   assert(lockPath!=NULL);
   30868   /* try to create all the intermediate directories */
   30869   len = (int)strlen(lockPath);
   30870   buf[0] = lockPath[0];
   30871   for( i=1; i<len; i++ ){
   30872     if( lockPath[i] == '/' && (i - start > 0) ){
   30873       /* only mkdir if leaf dir != "." or "/" or ".." */
   30874       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   30875          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   30876         buf[i]='\0';
   30877         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   30878           int err=errno;
   30879           if( err!=EEXIST ) {
   30880             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   30881                      "'%s' proxy lock path=%s pid=%d\n",
   30882                      buf, strerror(err), lockPath, getpid()));
   30883             return err;
   30884           }
   30885         }
   30886       }
   30887       start=i+1;
   30888     }
   30889     buf[i] = lockPath[i];
   30890   }
   30891   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   30892   return 0;
   30893 }
   30894 
   30895 /*
   30896 ** Create a new VFS file descriptor (stored in memory obtained from
   30897 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   30898 **
   30899 ** The caller is responsible not only for closing the file descriptor
   30900 ** but also for freeing the memory associated with the file descriptor.
   30901 */
   30902 static int proxyCreateUnixFile(
   30903     const char *path,        /* path for the new unixFile */
   30904     unixFile **ppFile,       /* unixFile created and returned by ref */
   30905     int islockfile           /* if non zero missing dirs will be created */
   30906 ) {
   30907   int fd = -1;
   30908   unixFile *pNew;
   30909   int rc = SQLITE_OK;
   30910   int openFlags = O_RDWR | O_CREAT;
   30911   sqlite3_vfs dummyVfs;
   30912   int terrno = 0;
   30913   UnixUnusedFd *pUnused = NULL;
   30914 
   30915   /* 1. first try to open/create the file
   30916   ** 2. if that fails, and this is a lock file (not-conch), try creating
   30917   ** the parent directories and then try again.
   30918   ** 3. if that fails, try to open the file read-only
   30919   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   30920   */
   30921   pUnused = findReusableFd(path, openFlags);
   30922   if( pUnused ){
   30923     fd = pUnused->fd;
   30924   }else{
   30925     pUnused = sqlite3_malloc(sizeof(*pUnused));
   30926     if( !pUnused ){
   30927       return SQLITE_NOMEM;
   30928     }
   30929   }
   30930   if( fd<0 ){
   30931     fd = robust_open(path, openFlags, 0);
   30932     terrno = errno;
   30933     if( fd<0 && errno==ENOENT && islockfile ){
   30934       if( proxyCreateLockPath(path) == SQLITE_OK ){
   30935         fd = robust_open(path, openFlags, 0);
   30936       }
   30937     }
   30938   }
   30939   if( fd<0 ){
   30940     openFlags = O_RDONLY;
   30941     fd = robust_open(path, openFlags, 0);
   30942     terrno = errno;
   30943   }
   30944   if( fd<0 ){
   30945     if( islockfile ){
   30946       return SQLITE_BUSY;
   30947     }
   30948     switch (terrno) {
   30949       case EACCES:
   30950         return SQLITE_PERM;
   30951       case EIO:
   30952         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   30953       default:
   30954         return SQLITE_CANTOPEN_BKPT;
   30955     }
   30956   }
   30957 
   30958   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   30959   if( pNew==NULL ){
   30960     rc = SQLITE_NOMEM;
   30961     goto end_create_proxy;
   30962   }
   30963   memset(pNew, 0, sizeof(unixFile));
   30964   pNew->openFlags = openFlags;
   30965   memset(&dummyVfs, 0, sizeof(dummyVfs));
   30966   dummyVfs.pAppData = (void*)&autolockIoFinder;
   30967   dummyVfs.zName = "dummy";
   30968   pUnused->fd = fd;
   30969   pUnused->flags = openFlags;
   30970   pNew->pUnused = pUnused;
   30971 
   30972   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   30973   if( rc==SQLITE_OK ){
   30974     *ppFile = pNew;
   30975     return SQLITE_OK;
   30976   }
   30977 end_create_proxy:
   30978   robust_close(pNew, fd, __LINE__);
   30979   sqlite3_free(pNew);
   30980   sqlite3_free(pUnused);
   30981   return rc;
   30982 }
   30983 
   30984 #ifdef SQLITE_TEST
   30985 /* simulate multiple hosts by creating unique hostid file paths */
   30986 SQLITE_API int sqlite3_hostid_num = 0;
   30987 #endif
   30988 
   30989 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   30990 
   30991 /* Not always defined in the headers as it ought to be */
   30992 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   30993 
   30994 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   30995 ** bytes of writable memory.
   30996 */
   30997 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   30998   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   30999   memset(pHostID, 0, PROXY_HOSTIDLEN);
   31000 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   31001                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   31002   {
   31003     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
   31004     if( gethostuuid(pHostID, &timeout) ){
   31005       int err = errno;
   31006       if( pError ){
   31007         *pError = err;
   31008       }
   31009       return SQLITE_IOERR;
   31010     }
   31011   }
   31012 #else
   31013   UNUSED_PARAMETER(pError);
   31014 #endif
   31015 #ifdef SQLITE_TEST
   31016   /* simulate multiple hosts by creating unique hostid file paths */
   31017   if( sqlite3_hostid_num != 0){
   31018     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   31019   }
   31020 #endif
   31021 
   31022   return SQLITE_OK;
   31023 }
   31024 
   31025 /* The conch file contains the header, host id and lock file path
   31026  */
   31027 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   31028 #define PROXY_HEADERLEN    1   /* conch file header length */
   31029 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   31030 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   31031 
   31032 /*
   31033 ** Takes an open conch file, copies the contents to a new path and then moves
   31034 ** it back.  The newly created file's file descriptor is assigned to the
   31035 ** conch file structure and finally the original conch file descriptor is
   31036 ** closed.  Returns zero if successful.
   31037 */
   31038 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   31039   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31040   unixFile *conchFile = pCtx->conchFile;
   31041   char tPath[MAXPATHLEN];
   31042   char buf[PROXY_MAXCONCHLEN];
   31043   char *cPath = pCtx->conchFilePath;
   31044   size_t readLen = 0;
   31045   size_t pathLen = 0;
   31046   char errmsg[64] = "";
   31047   int fd = -1;
   31048   int rc = -1;
   31049   UNUSED_PARAMETER(myHostID);
   31050 
   31051   /* create a new path by replace the trailing '-conch' with '-break' */
   31052   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   31053   if( pathLen>MAXPATHLEN || pathLen<6 ||
   31054      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   31055     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   31056     goto end_breaklock;
   31057   }
   31058   /* read the conch content */
   31059   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   31060   if( readLen<PROXY_PATHINDEX ){
   31061     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   31062     goto end_breaklock;
   31063   }
   31064   /* write it out to the temporary break file */
   31065   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
   31066   if( fd<0 ){
   31067     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   31068     goto end_breaklock;
   31069   }
   31070   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   31071     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   31072     goto end_breaklock;
   31073   }
   31074   if( rename(tPath, cPath) ){
   31075     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   31076     goto end_breaklock;
   31077   }
   31078   rc = 0;
   31079   fprintf(stderr, "broke stale lock on %s\n", cPath);
   31080   robust_close(pFile, conchFile->h, __LINE__);
   31081   conchFile->h = fd;
   31082   conchFile->openFlags = O_RDWR | O_CREAT;
   31083 
   31084 end_breaklock:
   31085   if( rc ){
   31086     if( fd>=0 ){
   31087       osUnlink(tPath);
   31088       robust_close(pFile, fd, __LINE__);
   31089     }
   31090     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   31091   }
   31092   return rc;
   31093 }
   31094 
   31095 /* Take the requested lock on the conch file and break a stale lock if the
   31096 ** host id matches.
   31097 */
   31098 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   31099   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31100   unixFile *conchFile = pCtx->conchFile;
   31101   int rc = SQLITE_OK;
   31102   int nTries = 0;
   31103   struct timespec conchModTime;
   31104 
   31105   memset(&conchModTime, 0, sizeof(conchModTime));
   31106   do {
   31107     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31108     nTries ++;
   31109     if( rc==SQLITE_BUSY ){
   31110       /* If the lock failed (busy):
   31111        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   31112        * 2nd try: fail if the mod time changed or host id is different, wait
   31113        *           10 sec and try again
   31114        * 3rd try: break the lock unless the mod time has changed.
   31115        */
   31116       struct stat buf;
   31117       if( osFstat(conchFile->h, &buf) ){
   31118         pFile->lastErrno = errno;
   31119         return SQLITE_IOERR_LOCK;
   31120       }
   31121 
   31122       if( nTries==1 ){
   31123         conchModTime = buf.st_mtimespec;
   31124         usleep(500000); /* wait 0.5 sec and try the lock again*/
   31125         continue;
   31126       }
   31127 
   31128       assert( nTries>1 );
   31129       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   31130          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   31131         return SQLITE_BUSY;
   31132       }
   31133 
   31134       if( nTries==2 ){
   31135         char tBuf[PROXY_MAXCONCHLEN];
   31136         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   31137         if( len<0 ){
   31138           pFile->lastErrno = errno;
   31139           return SQLITE_IOERR_LOCK;
   31140         }
   31141         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   31142           /* don't break the lock if the host id doesn't match */
   31143           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   31144             return SQLITE_BUSY;
   31145           }
   31146         }else{
   31147           /* don't break the lock on short read or a version mismatch */
   31148           return SQLITE_BUSY;
   31149         }
   31150         usleep(10000000); /* wait 10 sec and try the lock again */
   31151         continue;
   31152       }
   31153 
   31154       assert( nTries==3 );
   31155       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   31156         rc = SQLITE_OK;
   31157         if( lockType==EXCLUSIVE_LOCK ){
   31158           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   31159         }
   31160         if( !rc ){
   31161           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31162         }
   31163       }
   31164     }
   31165   } while( rc==SQLITE_BUSY && nTries<3 );
   31166 
   31167   return rc;
   31168 }
   31169 
   31170 /* Takes the conch by taking a shared lock and read the contents conch, if
   31171 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   31172 ** lockPath means that the lockPath in the conch file will be used if the
   31173 ** host IDs match, or a new lock path will be generated automatically
   31174 ** and written to the conch file.
   31175 */
   31176 static int proxyTakeConch(unixFile *pFile){
   31177   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31178 
   31179   if( pCtx->conchHeld!=0 ){
   31180     return SQLITE_OK;
   31181   }else{
   31182     unixFile *conchFile = pCtx->conchFile;
   31183     uuid_t myHostID;
   31184     int pError = 0;
   31185     char readBuf[PROXY_MAXCONCHLEN];
   31186     char lockPath[MAXPATHLEN];
   31187     char *tempLockPath = NULL;
   31188     int rc = SQLITE_OK;
   31189     int createConch = 0;
   31190     int hostIdMatch = 0;
   31191     int readLen = 0;
   31192     int tryOldLockPath = 0;
   31193     int forceNewLockPath = 0;
   31194 
   31195     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   31196              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   31197 
   31198     rc = proxyGetHostID(myHostID, &pError);
   31199     if( (rc&0xff)==SQLITE_IOERR ){
   31200       pFile->lastErrno = pError;
   31201       goto end_takeconch;
   31202     }
   31203     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   31204     if( rc!=SQLITE_OK ){
   31205       goto end_takeconch;
   31206     }
   31207     /* read the existing conch file */
   31208     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   31209     if( readLen<0 ){
   31210       /* I/O error: lastErrno set by seekAndRead */
   31211       pFile->lastErrno = conchFile->lastErrno;
   31212       rc = SQLITE_IOERR_READ;
   31213       goto end_takeconch;
   31214     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   31215              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   31216       /* a short read or version format mismatch means we need to create a new
   31217       ** conch file.
   31218       */
   31219       createConch = 1;
   31220     }
   31221     /* if the host id matches and the lock path already exists in the conch
   31222     ** we'll try to use the path there, if we can't open that path, we'll
   31223     ** retry with a new auto-generated path
   31224     */
   31225     do { /* in case we need to try again for an :auto: named lock file */
   31226 
   31227       if( !createConch && !forceNewLockPath ){
   31228         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   31229                                   PROXY_HOSTIDLEN);
   31230         /* if the conch has data compare the contents */
   31231         if( !pCtx->lockProxyPath ){
   31232           /* for auto-named local lock file, just check the host ID and we'll
   31233            ** use the local lock file path that's already in there
   31234            */
   31235           if( hostIdMatch ){
   31236             size_t pathLen = (readLen - PROXY_PATHINDEX);
   31237 
   31238             if( pathLen>=MAXPATHLEN ){
   31239               pathLen=MAXPATHLEN-1;
   31240             }
   31241             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   31242             lockPath[pathLen] = 0;
   31243             tempLockPath = lockPath;
   31244             tryOldLockPath = 1;
   31245             /* create a copy of the lock path if the conch is taken */
   31246             goto end_takeconch;
   31247           }
   31248         }else if( hostIdMatch
   31249                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   31250                            readLen-PROXY_PATHINDEX)
   31251         ){
   31252           /* conch host and lock path match */
   31253           goto end_takeconch;
   31254         }
   31255       }
   31256 
   31257       /* if the conch isn't writable and doesn't match, we can't take it */
   31258       if( (conchFile->openFlags&O_RDWR) == 0 ){
   31259         rc = SQLITE_BUSY;
   31260         goto end_takeconch;
   31261       }
   31262 
   31263       /* either the conch didn't match or we need to create a new one */
   31264       if( !pCtx->lockProxyPath ){
   31265         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   31266         tempLockPath = lockPath;
   31267         /* create a copy of the lock path _only_ if the conch is taken */
   31268       }
   31269 
   31270       /* update conch with host and path (this will fail if other process
   31271       ** has a shared lock already), if the host id matches, use the big
   31272       ** stick.
   31273       */
   31274       futimes(conchFile->h, NULL);
   31275       if( hostIdMatch && !createConch ){
   31276         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   31277           /* We are trying for an exclusive lock but another thread in this
   31278            ** same process is still holding a shared lock. */
   31279           rc = SQLITE_BUSY;
   31280         } else {
   31281           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   31282         }
   31283       }else{
   31284         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   31285       }
   31286       if( rc==SQLITE_OK ){
   31287         char writeBuffer[PROXY_MAXCONCHLEN];
   31288         int writeSize = 0;
   31289 
   31290         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   31291         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   31292         if( pCtx->lockProxyPath!=NULL ){
   31293           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   31294         }else{
   31295           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   31296         }
   31297         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   31298         robust_ftruncate(conchFile->h, writeSize);
   31299         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   31300         fsync(conchFile->h);
   31301         /* If we created a new conch file (not just updated the contents of a
   31302          ** valid conch file), try to match the permissions of the database
   31303          */
   31304         if( rc==SQLITE_OK && createConch ){
   31305           struct stat buf;
   31306           int err = osFstat(pFile->h, &buf);
   31307           if( err==0 ){
   31308             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   31309                                         S_IROTH|S_IWOTH);
   31310             /* try to match the database file R/W permissions, ignore failure */
   31311 #ifndef SQLITE_PROXY_DEBUG
   31312             osFchmod(conchFile->h, cmode);
   31313 #else
   31314             do{
   31315               rc = osFchmod(conchFile->h, cmode);
   31316             }while( rc==(-1) && errno==EINTR );
   31317             if( rc!=0 ){
   31318               int code = errno;
   31319               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   31320                       cmode, code, strerror(code));
   31321             } else {
   31322               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   31323             }
   31324           }else{
   31325             int code = errno;
   31326             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   31327                     err, code, strerror(code));
   31328 #endif
   31329           }
   31330         }
   31331       }
   31332       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   31333 
   31334     end_takeconch:
   31335       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   31336       if( rc==SQLITE_OK && pFile->openFlags ){
   31337         int fd;
   31338         if( pFile->h>=0 ){
   31339           robust_close(pFile, pFile->h, __LINE__);
   31340         }
   31341         pFile->h = -1;
   31342         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
   31343         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   31344         if( fd>=0 ){
   31345           pFile->h = fd;
   31346         }else{
   31347           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   31348            during locking */
   31349         }
   31350       }
   31351       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   31352         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   31353         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   31354         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   31355           /* we couldn't create the proxy lock file with the old lock file path
   31356            ** so try again via auto-naming
   31357            */
   31358           forceNewLockPath = 1;
   31359           tryOldLockPath = 0;
   31360           continue; /* go back to the do {} while start point, try again */
   31361         }
   31362       }
   31363       if( rc==SQLITE_OK ){
   31364         /* Need to make a copy of path if we extracted the value
   31365          ** from the conch file or the path was allocated on the stack
   31366          */
   31367         if( tempLockPath ){
   31368           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   31369           if( !pCtx->lockProxyPath ){
   31370             rc = SQLITE_NOMEM;
   31371           }
   31372         }
   31373       }
   31374       if( rc==SQLITE_OK ){
   31375         pCtx->conchHeld = 1;
   31376 
   31377         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   31378           afpLockingContext *afpCtx;
   31379           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   31380           afpCtx->dbPath = pCtx->lockProxyPath;
   31381         }
   31382       } else {
   31383         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31384       }
   31385       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   31386                rc==SQLITE_OK?"ok":"failed"));
   31387       return rc;
   31388     } while (1); /* in case we need to retry the :auto: lock file -
   31389                  ** we should never get here except via the 'continue' call. */
   31390   }
   31391 }
   31392 
   31393 /*
   31394 ** If pFile holds a lock on a conch file, then release that lock.
   31395 */
   31396 static int proxyReleaseConch(unixFile *pFile){
   31397   int rc = SQLITE_OK;         /* Subroutine return code */
   31398   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   31399   unixFile *conchFile;        /* Name of the conch file */
   31400 
   31401   pCtx = (proxyLockingContext *)pFile->lockingContext;
   31402   conchFile = pCtx->conchFile;
   31403   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   31404            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   31405            getpid()));
   31406   if( pCtx->conchHeld>0 ){
   31407     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31408   }
   31409   pCtx->conchHeld = 0;
   31410   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   31411            (rc==SQLITE_OK ? "ok" : "failed")));
   31412   return rc;
   31413 }
   31414 
   31415 /*
   31416 ** Given the name of a database file, compute the name of its conch file.
   31417 ** Store the conch filename in memory obtained from sqlite3_malloc().
   31418 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   31419 ** or SQLITE_NOMEM if unable to obtain memory.
   31420 **
   31421 ** The caller is responsible for ensuring that the allocated memory
   31422 ** space is eventually freed.
   31423 **
   31424 ** *pConchPath is set to NULL if a memory allocation error occurs.
   31425 */
   31426 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   31427   int i;                        /* Loop counter */
   31428   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   31429   char *conchPath;              /* buffer in which to construct conch name */
   31430 
   31431   /* Allocate space for the conch filename and initialize the name to
   31432   ** the name of the original database file. */
   31433   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   31434   if( conchPath==0 ){
   31435     return SQLITE_NOMEM;
   31436   }
   31437   memcpy(conchPath, dbPath, len+1);
   31438 
   31439   /* now insert a "." before the last / character */
   31440   for( i=(len-1); i>=0; i-- ){
   31441     if( conchPath[i]=='/' ){
   31442       i++;
   31443       break;
   31444     }
   31445   }
   31446   conchPath[i]='.';
   31447   while ( i<len ){
   31448     conchPath[i+1]=dbPath[i];
   31449     i++;
   31450   }
   31451 
   31452   /* append the "-conch" suffix to the file */
   31453   memcpy(&conchPath[i+1], "-conch", 7);
   31454   assert( (int)strlen(conchPath) == len+7 );
   31455 
   31456   return SQLITE_OK;
   31457 }
   31458 
   31459 
   31460 /* Takes a fully configured proxy locking-style unix file and switches
   31461 ** the local lock file path
   31462 */
   31463 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   31464   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31465   char *oldPath = pCtx->lockProxyPath;
   31466   int rc = SQLITE_OK;
   31467 
   31468   if( pFile->eFileLock!=NO_LOCK ){
   31469     return SQLITE_BUSY;
   31470   }
   31471 
   31472   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   31473   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   31474     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   31475     return SQLITE_OK;
   31476   }else{
   31477     unixFile *lockProxy = pCtx->lockProxy;
   31478     pCtx->lockProxy=NULL;
   31479     pCtx->conchHeld = 0;
   31480     if( lockProxy!=NULL ){
   31481       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   31482       if( rc ) return rc;
   31483       sqlite3_free(lockProxy);
   31484     }
   31485     sqlite3_free(oldPath);
   31486     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   31487   }
   31488 
   31489   return rc;
   31490 }
   31491 
   31492 /*
   31493 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   31494 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   31495 **
   31496 ** This routine find the filename associated with pFile and writes it
   31497 ** int dbPath.
   31498 */
   31499 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   31500 #if defined(__APPLE__)
   31501   if( pFile->pMethod == &afpIoMethods ){
   31502     /* afp style keeps a reference to the db path in the filePath field
   31503     ** of the struct */
   31504     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31505     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   31506   } else
   31507 #endif
   31508   if( pFile->pMethod == &dotlockIoMethods ){
   31509     /* dot lock style uses the locking context to store the dot lock
   31510     ** file path */
   31511     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   31512     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   31513   }else{
   31514     /* all other styles use the locking context to store the db file path */
   31515     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31516     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   31517   }
   31518   return SQLITE_OK;
   31519 }
   31520 
   31521 /*
   31522 ** Takes an already filled in unix file and alters it so all file locking
   31523 ** will be performed on the local proxy lock file.  The following fields
   31524 ** are preserved in the locking context so that they can be restored and
   31525 ** the unix structure properly cleaned up at close time:
   31526 **  ->lockingContext
   31527 **  ->pMethod
   31528 */
   31529 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   31530   proxyLockingContext *pCtx;
   31531   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   31532   char *lockPath=NULL;
   31533   int rc = SQLITE_OK;
   31534 
   31535   if( pFile->eFileLock!=NO_LOCK ){
   31536     return SQLITE_BUSY;
   31537   }
   31538   proxyGetDbPathForUnixFile(pFile, dbPath);
   31539   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   31540     lockPath=NULL;
   31541   }else{
   31542     lockPath=(char *)path;
   31543   }
   31544 
   31545   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   31546            (lockPath ? lockPath : ":auto:"), getpid()));
   31547 
   31548   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   31549   if( pCtx==0 ){
   31550     return SQLITE_NOMEM;
   31551   }
   31552   memset(pCtx, 0, sizeof(*pCtx));
   31553 
   31554   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   31555   if( rc==SQLITE_OK ){
   31556     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   31557     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   31558       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   31559       ** (c) the file system is read-only, then enable no-locking access.
   31560       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   31561       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   31562       */
   31563       struct statfs fsInfo;
   31564       struct stat conchInfo;
   31565       int goLockless = 0;
   31566 
   31567       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   31568         int err = errno;
   31569         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   31570           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   31571         }
   31572       }
   31573       if( goLockless ){
   31574         pCtx->conchHeld = -1; /* read only FS/ lockless */
   31575         rc = SQLITE_OK;
   31576       }
   31577     }
   31578   }
   31579   if( rc==SQLITE_OK && lockPath ){
   31580     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   31581   }
   31582 
   31583   if( rc==SQLITE_OK ){
   31584     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   31585     if( pCtx->dbPath==NULL ){
   31586       rc = SQLITE_NOMEM;
   31587     }
   31588   }
   31589   if( rc==SQLITE_OK ){
   31590     /* all memory is allocated, proxys are created and assigned,
   31591     ** switch the locking context and pMethod then return.
   31592     */
   31593     pCtx->oldLockingContext = pFile->lockingContext;
   31594     pFile->lockingContext = pCtx;
   31595     pCtx->pOldMethod = pFile->pMethod;
   31596     pFile->pMethod = &proxyIoMethods;
   31597   }else{
   31598     if( pCtx->conchFile ){
   31599       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   31600       sqlite3_free(pCtx->conchFile);
   31601     }
   31602     sqlite3DbFree(0, pCtx->lockProxyPath);
   31603     sqlite3_free(pCtx->conchFilePath);
   31604     sqlite3_free(pCtx);
   31605   }
   31606   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   31607            (rc==SQLITE_OK ? "ok" : "failed")));
   31608   return rc;
   31609 }
   31610 
   31611 
   31612 /*
   31613 ** This routine handles sqlite3_file_control() calls that are specific
   31614 ** to proxy locking.
   31615 */
   31616 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   31617   switch( op ){
   31618     case SQLITE_GET_LOCKPROXYFILE: {
   31619       unixFile *pFile = (unixFile*)id;
   31620       if( pFile->pMethod == &proxyIoMethods ){
   31621         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31622         proxyTakeConch(pFile);
   31623         if( pCtx->lockProxyPath ){
   31624           *(const char **)pArg = pCtx->lockProxyPath;
   31625         }else{
   31626           *(const char **)pArg = ":auto: (not held)";
   31627         }
   31628       } else {
   31629         *(const char **)pArg = NULL;
   31630       }
   31631       return SQLITE_OK;
   31632     }
   31633     case SQLITE_SET_LOCKPROXYFILE: {
   31634       unixFile *pFile = (unixFile*)id;
   31635       int rc = SQLITE_OK;
   31636       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   31637       if( pArg==NULL || (const char *)pArg==0 ){
   31638         if( isProxyStyle ){
   31639           /* turn off proxy locking - not supported */
   31640           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   31641         }else{
   31642           /* turn off proxy locking - already off - NOOP */
   31643           rc = SQLITE_OK;
   31644         }
   31645       }else{
   31646         const char *proxyPath = (const char *)pArg;
   31647         if( isProxyStyle ){
   31648           proxyLockingContext *pCtx =
   31649             (proxyLockingContext*)pFile->lockingContext;
   31650           if( !strcmp(pArg, ":auto:")
   31651            || (pCtx->lockProxyPath &&
   31652                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   31653           ){
   31654             rc = SQLITE_OK;
   31655           }else{
   31656             rc = switchLockProxyPath(pFile, proxyPath);
   31657           }
   31658         }else{
   31659           /* turn on proxy file locking */
   31660           rc = proxyTransformUnixFile(pFile, proxyPath);
   31661         }
   31662       }
   31663       return rc;
   31664     }
   31665     default: {
   31666       assert( 0 );  /* The call assures that only valid opcodes are sent */
   31667     }
   31668   }
   31669   /*NOTREACHED*/
   31670   return SQLITE_ERROR;
   31671 }
   31672 
   31673 /*
   31674 ** Within this division (the proxying locking implementation) the procedures
   31675 ** above this point are all utilities.  The lock-related methods of the
   31676 ** proxy-locking sqlite3_io_method object follow.
   31677 */
   31678 
   31679 
   31680 /*
   31681 ** This routine checks if there is a RESERVED lock held on the specified
   31682 ** file by this or any other process. If such a lock is held, set *pResOut
   31683 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   31684 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   31685 */
   31686 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   31687   unixFile *pFile = (unixFile*)id;
   31688   int rc = proxyTakeConch(pFile);
   31689   if( rc==SQLITE_OK ){
   31690     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31691     if( pCtx->conchHeld>0 ){
   31692       unixFile *proxy = pCtx->lockProxy;
   31693       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   31694     }else{ /* conchHeld < 0 is lockless */
   31695       pResOut=0;
   31696     }
   31697   }
   31698   return rc;
   31699 }
   31700 
   31701 /*
   31702 ** Lock the file with the lock specified by parameter eFileLock - one
   31703 ** of the following:
   31704 **
   31705 **     (1) SHARED_LOCK
   31706 **     (2) RESERVED_LOCK
   31707 **     (3) PENDING_LOCK
   31708 **     (4) EXCLUSIVE_LOCK
   31709 **
   31710 ** Sometimes when requesting one lock state, additional lock states
   31711 ** are inserted in between.  The locking might fail on one of the later
   31712 ** transitions leaving the lock state different from what it started but
   31713 ** still short of its goal.  The following chart shows the allowed
   31714 ** transitions and the inserted intermediate states:
   31715 **
   31716 **    UNLOCKED -> SHARED
   31717 **    SHARED -> RESERVED
   31718 **    SHARED -> (PENDING) -> EXCLUSIVE
   31719 **    RESERVED -> (PENDING) -> EXCLUSIVE
   31720 **    PENDING -> EXCLUSIVE
   31721 **
   31722 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   31723 ** routine to lower a locking level.
   31724 */
   31725 static int proxyLock(sqlite3_file *id, int eFileLock) {
   31726   unixFile *pFile = (unixFile*)id;
   31727   int rc = proxyTakeConch(pFile);
   31728   if( rc==SQLITE_OK ){
   31729     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31730     if( pCtx->conchHeld>0 ){
   31731       unixFile *proxy = pCtx->lockProxy;
   31732       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   31733       pFile->eFileLock = proxy->eFileLock;
   31734     }else{
   31735       /* conchHeld < 0 is lockless */
   31736     }
   31737   }
   31738   return rc;
   31739 }
   31740 
   31741 
   31742 /*
   31743 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   31744 ** must be either NO_LOCK or SHARED_LOCK.
   31745 **
   31746 ** If the locking level of the file descriptor is already at or below
   31747 ** the requested locking level, this routine is a no-op.
   31748 */
   31749 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   31750   unixFile *pFile = (unixFile*)id;
   31751   int rc = proxyTakeConch(pFile);
   31752   if( rc==SQLITE_OK ){
   31753     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31754     if( pCtx->conchHeld>0 ){
   31755       unixFile *proxy = pCtx->lockProxy;
   31756       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   31757       pFile->eFileLock = proxy->eFileLock;
   31758     }else{
   31759       /* conchHeld < 0 is lockless */
   31760     }
   31761   }
   31762   return rc;
   31763 }
   31764 
   31765 /*
   31766 ** Close a file that uses proxy locks.
   31767 */
   31768 static int proxyClose(sqlite3_file *id) {
   31769   if( id ){
   31770     unixFile *pFile = (unixFile*)id;
   31771     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31772     unixFile *lockProxy = pCtx->lockProxy;
   31773     unixFile *conchFile = pCtx->conchFile;
   31774     int rc = SQLITE_OK;
   31775 
   31776     if( lockProxy ){
   31777       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   31778       if( rc ) return rc;
   31779       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   31780       if( rc ) return rc;
   31781       sqlite3_free(lockProxy);
   31782       pCtx->lockProxy = 0;
   31783     }
   31784     if( conchFile ){
   31785       if( pCtx->conchHeld ){
   31786         rc = proxyReleaseConch(pFile);
   31787         if( rc ) return rc;
   31788       }
   31789       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   31790       if( rc ) return rc;
   31791       sqlite3_free(conchFile);
   31792     }
   31793     sqlite3DbFree(0, pCtx->lockProxyPath);
   31794     sqlite3_free(pCtx->conchFilePath);
   31795     sqlite3DbFree(0, pCtx->dbPath);
   31796     /* restore the original locking context and pMethod then close it */
   31797     pFile->lockingContext = pCtx->oldLockingContext;
   31798     pFile->pMethod = pCtx->pOldMethod;
   31799     sqlite3_free(pCtx);
   31800     return pFile->pMethod->xClose(id);
   31801   }
   31802   return SQLITE_OK;
   31803 }
   31804 
   31805 
   31806 
   31807 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   31808 /*
   31809 ** The proxy locking style is intended for use with AFP filesystems.
   31810 ** And since AFP is only supported on MacOSX, the proxy locking is also
   31811 ** restricted to MacOSX.
   31812 **
   31813 **
   31814 ******************* End of the proxy lock implementation **********************
   31815 ******************************************************************************/
   31816 
   31817 /*
   31818 ** Initialize the operating system interface.
   31819 **
   31820 ** This routine registers all VFS implementations for unix-like operating
   31821 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   31822 ** should be the only routines in this file that are visible from other
   31823 ** files.
   31824 **
   31825 ** This routine is called once during SQLite initialization and by a
   31826 ** single thread.  The memory allocation and mutex subsystems have not
   31827 ** necessarily been initialized when this routine is called, and so they
   31828 ** should not be used.
   31829 */
   31830 SQLITE_API int sqlite3_os_init(void){
   31831   /*
   31832   ** The following macro defines an initializer for an sqlite3_vfs object.
   31833   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   31834   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   31835   ** silly C90 rules prohibit a void* from being cast to a function pointer
   31836   ** and so we have to go through the intermediate pointer to avoid problems
   31837   ** when compiling with -pedantic-errors on GCC.)
   31838   **
   31839   ** The FINDER parameter to this macro is the name of the pointer to the
   31840   ** finder-function.  The finder-function returns a pointer to the
   31841   ** sqlite_io_methods object that implements the desired locking
   31842   ** behaviors.  See the division above that contains the IOMETHODS
   31843   ** macro for addition information on finder-functions.
   31844   **
   31845   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   31846   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   31847   ** more than that; it looks at the filesystem type that hosts the
   31848   ** database file and tries to choose an locking method appropriate for
   31849   ** that filesystem time.
   31850   */
   31851   #define UNIXVFS(VFSNAME, FINDER) {                        \
   31852     3,                    /* iVersion */                    \
   31853     sizeof(unixFile),     /* szOsFile */                    \
   31854     MAX_PATHNAME,         /* mxPathname */                  \
   31855     0,                    /* pNext */                       \
   31856     VFSNAME,              /* zName */                       \
   31857     (void*)&FINDER,       /* pAppData */                    \
   31858     unixOpen,             /* xOpen */                       \
   31859     unixDelete,           /* xDelete */                     \
   31860     unixAccess,           /* xAccess */                     \
   31861     unixFullPathname,     /* xFullPathname */               \
   31862     unixDlOpen,           /* xDlOpen */                     \
   31863     unixDlError,          /* xDlError */                    \
   31864     unixDlSym,            /* xDlSym */                      \
   31865     unixDlClose,          /* xDlClose */                    \
   31866     unixRandomness,       /* xRandomness */                 \
   31867     unixSleep,            /* xSleep */                      \
   31868     unixCurrentTime,      /* xCurrentTime */                \
   31869     unixGetLastError,     /* xGetLastError */               \
   31870     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   31871     unixSetSystemCall,    /* xSetSystemCall */              \
   31872     unixGetSystemCall,    /* xGetSystemCall */              \
   31873     unixNextSystemCall,   /* xNextSystemCall */             \
   31874   }
   31875 
   31876   /*
   31877   ** All default VFSes for unix are contained in the following array.
   31878   **
   31879   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   31880   ** by the SQLite core when the VFS is registered.  So the following
   31881   ** array cannot be const.
   31882   */
   31883   static sqlite3_vfs aVfs[] = {
   31884 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   31885     UNIXVFS("unix",          autolockIoFinder ),
   31886 #else
   31887     UNIXVFS("unix",          posixIoFinder ),
   31888 #endif
   31889     UNIXVFS("unix-none",     nolockIoFinder ),
   31890     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   31891     UNIXVFS("unix-excl",     posixIoFinder ),
   31892 #if OS_VXWORKS
   31893     UNIXVFS("unix-namedsem", semIoFinder ),
   31894 #endif
   31895 #if SQLITE_ENABLE_LOCKING_STYLE
   31896     UNIXVFS("unix-posix",    posixIoFinder ),
   31897 #if !OS_VXWORKS
   31898     UNIXVFS("unix-flock",    flockIoFinder ),
   31899 #endif
   31900 #endif
   31901 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   31902     UNIXVFS("unix-afp",      afpIoFinder ),
   31903     UNIXVFS("unix-nfs",      nfsIoFinder ),
   31904     UNIXVFS("unix-proxy",    proxyIoFinder ),
   31905 #endif
   31906   };
   31907   unsigned int i;          /* Loop counter */
   31908 
   31909   /* Double-check that the aSyscall[] array has been constructed
   31910   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   31911   assert( ArraySize(aSyscall)==22 );
   31912 
   31913   /* Register all VFSes defined in the aVfs[] array */
   31914   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   31915     sqlite3_vfs_register(&aVfs[i], i==0);
   31916   }
   31917   return SQLITE_OK;
   31918 }
   31919 
   31920 /*
   31921 ** Shutdown the operating system interface.
   31922 **
   31923 ** Some operating systems might need to do some cleanup in this routine,
   31924 ** to release dynamically allocated objects.  But not on unix.
   31925 ** This routine is a no-op for unix.
   31926 */
   31927 SQLITE_API int sqlite3_os_end(void){
   31928   return SQLITE_OK;
   31929 }
   31930 
   31931 #endif /* SQLITE_OS_UNIX */
   31932 
   31933 /************** End of os_unix.c *********************************************/
   31934 /************** Begin file os_win.c ******************************************/
   31935 /*
   31936 ** 2004 May 22
   31937 **
   31938 ** The author disclaims copyright to this source code.  In place of
   31939 ** a legal notice, here is a blessing:
   31940 **
   31941 **    May you do good and not evil.
   31942 **    May you find forgiveness for yourself and forgive others.
   31943 **    May you share freely, never taking more than you give.
   31944 **
   31945 ******************************************************************************
   31946 **
   31947 ** This file contains code that is specific to Windows.
   31948 */
   31949 #if SQLITE_OS_WIN               /* This file is used for Windows only */
   31950 
   31951 #ifdef __CYGWIN__
   31952 # include <sys/cygwin.h>
   31953 #endif
   31954 
   31955 /*
   31956 ** Include code that is common to all os_*.c files
   31957 */
   31958 /************** Include os_common.h in the middle of os_win.c ****************/
   31959 /************** Begin file os_common.h ***************************************/
   31960 /*
   31961 ** 2004 May 22
   31962 **
   31963 ** The author disclaims copyright to this source code.  In place of
   31964 ** a legal notice, here is a blessing:
   31965 **
   31966 **    May you do good and not evil.
   31967 **    May you find forgiveness for yourself and forgive others.
   31968 **    May you share freely, never taking more than you give.
   31969 **
   31970 ******************************************************************************
   31971 **
   31972 ** This file contains macros and a little bit of code that is common to
   31973 ** all of the platform-specific files (os_*.c) and is #included into those
   31974 ** files.
   31975 **
   31976 ** This file should be #included by the os_*.c files only.  It is not a
   31977 ** general purpose header file.
   31978 */
   31979 #ifndef _OS_COMMON_H_
   31980 #define _OS_COMMON_H_
   31981 
   31982 /*
   31983 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   31984 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   31985 ** switch.  The following code should catch this problem at compile-time.
   31986 */
   31987 #ifdef MEMORY_DEBUG
   31988 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   31989 #endif
   31990 
   31991 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   31992 # ifndef SQLITE_DEBUG_OS_TRACE
   31993 #   define SQLITE_DEBUG_OS_TRACE 0
   31994 # endif
   31995   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   31996 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   31997 #else
   31998 # define OSTRACE(X)
   31999 #endif
   32000 
   32001 /*
   32002 ** Macros for performance tracing.  Normally turned off.  Only works
   32003 ** on i486 hardware.
   32004 */
   32005 #ifdef SQLITE_PERFORMANCE_TRACE
   32006 
   32007 /*
   32008 ** hwtime.h contains inline assembler code for implementing
   32009 ** high-performance timing routines.
   32010 */
   32011 /************** Include hwtime.h in the middle of os_common.h ****************/
   32012 /************** Begin file hwtime.h ******************************************/
   32013 /*
   32014 ** 2008 May 27
   32015 **
   32016 ** The author disclaims copyright to this source code.  In place of
   32017 ** a legal notice, here is a blessing:
   32018 **
   32019 **    May you do good and not evil.
   32020 **    May you find forgiveness for yourself and forgive others.
   32021 **    May you share freely, never taking more than you give.
   32022 **
   32023 ******************************************************************************
   32024 **
   32025 ** This file contains inline asm code for retrieving "high-performance"
   32026 ** counters for x86 class CPUs.
   32027 */
   32028 #ifndef _HWTIME_H_
   32029 #define _HWTIME_H_
   32030 
   32031 /*
   32032 ** The following routine only works on pentium-class (or newer) processors.
   32033 ** It uses the RDTSC opcode to read the cycle count value out of the
   32034 ** processor and returns that value.  This can be used for high-res
   32035 ** profiling.
   32036 */
   32037 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   32038       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   32039 
   32040   #if defined(__GNUC__)
   32041 
   32042   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32043      unsigned int lo, hi;
   32044      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   32045      return (sqlite_uint64)hi << 32 | lo;
   32046   }
   32047 
   32048   #elif defined(_MSC_VER)
   32049 
   32050   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   32051      __asm {
   32052         rdtsc
   32053         ret       ; return value at EDX:EAX
   32054      }
   32055   }
   32056 
   32057   #endif
   32058 
   32059 #elif (defined(__GNUC__) && defined(__x86_64__))
   32060 
   32061   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32062       unsigned long val;
   32063       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   32064       return val;
   32065   }
   32066 
   32067 #elif (defined(__GNUC__) && defined(__ppc__))
   32068 
   32069   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32070       unsigned long long retval;
   32071       unsigned long junk;
   32072       __asm__ __volatile__ ("\n\
   32073           1:      mftbu   %1\n\
   32074                   mftb    %L0\n\
   32075                   mftbu   %0\n\
   32076                   cmpw    %0,%1\n\
   32077                   bne     1b"
   32078                   : "=r" (retval), "=r" (junk));
   32079       return retval;
   32080   }
   32081 
   32082 #else
   32083 
   32084   #error Need implementation of sqlite3Hwtime() for your platform.
   32085 
   32086   /*
   32087   ** To compile without implementing sqlite3Hwtime() for your platform,
   32088   ** you can remove the above #error and use the following
   32089   ** stub function.  You will lose timing support for many
   32090   ** of the debugging and testing utilities, but it should at
   32091   ** least compile and run.
   32092   */
   32093 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   32094 
   32095 #endif
   32096 
   32097 #endif /* !defined(_HWTIME_H_) */
   32098 
   32099 /************** End of hwtime.h **********************************************/
   32100 /************** Continuing where we left off in os_common.h ******************/
   32101 
   32102 static sqlite_uint64 g_start;
   32103 static sqlite_uint64 g_elapsed;
   32104 #define TIMER_START       g_start=sqlite3Hwtime()
   32105 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   32106 #define TIMER_ELAPSED     g_elapsed
   32107 #else
   32108 #define TIMER_START
   32109 #define TIMER_END
   32110 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   32111 #endif
   32112 
   32113 /*
   32114 ** If we compile with the SQLITE_TEST macro set, then the following block
   32115 ** of code will give us the ability to simulate a disk I/O error.  This
   32116 ** is used for testing the I/O recovery logic.
   32117 */
   32118 #ifdef SQLITE_TEST
   32119 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   32120 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   32121 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   32122 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   32123 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   32124 SQLITE_API int sqlite3_diskfull_pending = 0;
   32125 SQLITE_API int sqlite3_diskfull = 0;
   32126 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   32127 #define SimulateIOError(CODE)  \
   32128   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   32129        || sqlite3_io_error_pending-- == 1 )  \
   32130               { local_ioerr(); CODE; }
   32131 static void local_ioerr(){
   32132   IOTRACE(("IOERR\n"));
   32133   sqlite3_io_error_hit++;
   32134   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   32135 }
   32136 #define SimulateDiskfullError(CODE) \
   32137    if( sqlite3_diskfull_pending ){ \
   32138      if( sqlite3_diskfull_pending == 1 ){ \
   32139        local_ioerr(); \
   32140        sqlite3_diskfull = 1; \
   32141        sqlite3_io_error_hit = 1; \
   32142        CODE; \
   32143      }else{ \
   32144        sqlite3_diskfull_pending--; \
   32145      } \
   32146    }
   32147 #else
   32148 #define SimulateIOErrorBenign(X)
   32149 #define SimulateIOError(A)
   32150 #define SimulateDiskfullError(A)
   32151 #endif
   32152 
   32153 /*
   32154 ** When testing, keep a count of the number of open files.
   32155 */
   32156 #ifdef SQLITE_TEST
   32157 SQLITE_API int sqlite3_open_file_count = 0;
   32158 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   32159 #else
   32160 #define OpenCounter(X)
   32161 #endif
   32162 
   32163 #endif /* !defined(_OS_COMMON_H_) */
   32164 
   32165 /************** End of os_common.h *******************************************/
   32166 /************** Continuing where we left off in os_win.c *********************/
   32167 
   32168 /*
   32169 ** Some Microsoft compilers lack this definition.
   32170 */
   32171 #ifndef INVALID_FILE_ATTRIBUTES
   32172 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   32173 #endif
   32174 
   32175 /* Forward references */
   32176 typedef struct winShm winShm;           /* A connection to shared-memory */
   32177 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   32178 
   32179 /*
   32180 ** WinCE lacks native support for file locking so we have to fake it
   32181 ** with some code of our own.
   32182 */
   32183 #if SQLITE_OS_WINCE
   32184 typedef struct winceLock {
   32185   int nReaders;       /* Number of reader locks obtained */
   32186   BOOL bPending;      /* Indicates a pending lock has been obtained */
   32187   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   32188   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   32189 } winceLock;
   32190 #endif
   32191 
   32192 /*
   32193 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   32194 ** portability layer.
   32195 */
   32196 typedef struct winFile winFile;
   32197 struct winFile {
   32198   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   32199   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   32200   HANDLE h;               /* Handle for accessing the file */
   32201   u8 locktype;            /* Type of lock currently held on this file */
   32202   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   32203   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   32204   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   32205   winShm *pShm;           /* Instance of shared memory on this file */
   32206   const char *zPath;      /* Full pathname of this file */
   32207   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   32208 #if SQLITE_OS_WINCE
   32209   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   32210   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   32211   HANDLE hShared;         /* Shared memory segment used for locking */
   32212   winceLock local;        /* Locks obtained by this instance of winFile */
   32213   winceLock *shared;      /* Global shared lock memory for the file  */
   32214 #endif
   32215 };
   32216 
   32217 /*
   32218 ** Allowed values for winFile.ctrlFlags
   32219 */
   32220 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
   32221 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   32222 
   32223 /*
   32224  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   32225  * various Win32 API heap functions instead of our own.
   32226  */
   32227 #ifdef SQLITE_WIN32_MALLOC
   32228 /*
   32229  * The initial size of the Win32-specific heap.  This value may be zero.
   32230  */
   32231 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
   32232 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
   32233                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
   32234 #endif
   32235 
   32236 /*
   32237  * The maximum size of the Win32-specific heap.  This value may be zero.
   32238  */
   32239 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
   32240 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
   32241 #endif
   32242 
   32243 /*
   32244  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   32245  * zero for the default behavior.
   32246  */
   32247 #ifndef SQLITE_WIN32_HEAP_FLAGS
   32248 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
   32249 #endif
   32250 
   32251 /*
   32252 ** The winMemData structure stores information required by the Win32-specific
   32253 ** sqlite3_mem_methods implementation.
   32254 */
   32255 typedef struct winMemData winMemData;
   32256 struct winMemData {
   32257 #ifndef NDEBUG
   32258   u32 magic;    /* Magic number to detect structure corruption. */
   32259 #endif
   32260   HANDLE hHeap; /* The handle to our heap. */
   32261   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
   32262 };
   32263 
   32264 #ifndef NDEBUG
   32265 #define WINMEM_MAGIC     0x42b2830b
   32266 #endif
   32267 
   32268 static struct winMemData win_mem_data = {
   32269 #ifndef NDEBUG
   32270   WINMEM_MAGIC,
   32271 #endif
   32272   NULL, FALSE
   32273 };
   32274 
   32275 #ifndef NDEBUG
   32276 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
   32277 #else
   32278 #define winMemAssertMagic()
   32279 #endif
   32280 
   32281 #define winMemGetHeap() win_mem_data.hHeap
   32282 
   32283 static void *winMemMalloc(int nBytes);
   32284 static void winMemFree(void *pPrior);
   32285 static void *winMemRealloc(void *pPrior, int nBytes);
   32286 static int winMemSize(void *p);
   32287 static int winMemRoundup(int n);
   32288 static int winMemInit(void *pAppData);
   32289 static void winMemShutdown(void *pAppData);
   32290 
   32291 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   32292 #endif /* SQLITE_WIN32_MALLOC */
   32293 
   32294 /*
   32295 ** The following variable is (normally) set once and never changes
   32296 ** thereafter.  It records whether the operating system is Win9x
   32297 ** or WinNT.
   32298 **
   32299 ** 0:   Operating system unknown.
   32300 ** 1:   Operating system is Win9x.
   32301 ** 2:   Operating system is WinNT.
   32302 **
   32303 ** In order to facilitate testing on a WinNT system, the test fixture
   32304 ** can manually set this value to 1 to emulate Win98 behavior.
   32305 */
   32306 #ifdef SQLITE_TEST
   32307 SQLITE_API int sqlite3_os_type = 0;
   32308 #else
   32309 static int sqlite3_os_type = 0;
   32310 #endif
   32311 
   32312 /*
   32313 ** Many system calls are accessed through pointer-to-functions so that
   32314 ** they may be overridden at runtime to facilitate fault injection during
   32315 ** testing and sandboxing.  The following array holds the names and pointers
   32316 ** to all overrideable system calls.
   32317 */
   32318 #if !SQLITE_OS_WINCE
   32319 #  define SQLITE_WIN32_HAS_ANSI
   32320 #endif
   32321 
   32322 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT
   32323 #  define SQLITE_WIN32_HAS_WIDE
   32324 #endif
   32325 
   32326 #ifndef SYSCALL
   32327 #  define SYSCALL sqlite3_syscall_ptr
   32328 #endif
   32329 
   32330 #if SQLITE_OS_WINCE
   32331 /*
   32332 ** These macros are necessary because Windows CE does not natively support the
   32333 ** Win32 APIs LockFile, UnlockFile, and LockFileEx.
   32334  */
   32335 
   32336 #  define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
   32337 #  define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
   32338 #  define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
   32339 
   32340 /*
   32341 ** These are the special syscall hacks for Windows CE.  The locking related
   32342 ** defines here refer to the macros defined just above.
   32343  */
   32344 
   32345 #  define osAreFileApisANSI()       1
   32346 #  define osLockFile                LockFile
   32347 #  define osUnlockFile              UnlockFile
   32348 #  define osLockFileEx              LockFileEx
   32349 #endif
   32350 
   32351 static struct win_syscall {
   32352   const char *zName;            /* Name of the sytem call */
   32353   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   32354   sqlite3_syscall_ptr pDefault; /* Default value */
   32355 } aSyscall[] = {
   32356 #if !SQLITE_OS_WINCE
   32357   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
   32358 
   32359 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
   32360 #else
   32361   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
   32362 #endif
   32363 
   32364 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32365   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
   32366 #else
   32367   { "CharLowerW",              (SYSCALL)0,                       0 },
   32368 #endif
   32369 
   32370 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
   32371 
   32372 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32373   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
   32374 #else
   32375   { "CharUpperW",              (SYSCALL)0,                       0 },
   32376 #endif
   32377 
   32378 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
   32379 
   32380   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
   32381 
   32382 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
   32383 
   32384 #if defined(SQLITE_WIN32_HAS_ANSI)
   32385   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
   32386 #else
   32387   { "CreateFileA",             (SYSCALL)0,                       0 },
   32388 #endif
   32389 
   32390 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
   32391         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
   32392 
   32393 #if defined(SQLITE_WIN32_HAS_WIDE)
   32394   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
   32395 #else
   32396   { "CreateFileW",             (SYSCALL)0,                       0 },
   32397 #endif
   32398 
   32399 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
   32400         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
   32401 
   32402   { "CreateFileMapping",       (SYSCALL)CreateFileMapping,       0 },
   32403 
   32404 #define osCreateFileMapping ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32405         DWORD,DWORD,DWORD,LPCTSTR))aSyscall[6].pCurrent)
   32406 
   32407 #if defined(SQLITE_WIN32_HAS_WIDE)
   32408   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
   32409 #else
   32410   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
   32411 #endif
   32412 
   32413 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32414         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
   32415 
   32416 #if defined(SQLITE_WIN32_HAS_WIDE)
   32417   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
   32418 #else
   32419   { "CreateMutexW",            (SYSCALL)0,                       0 },
   32420 #endif
   32421 
   32422 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
   32423         LPCWSTR))aSyscall[8].pCurrent)
   32424 
   32425 #if defined(SQLITE_WIN32_HAS_ANSI)
   32426   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
   32427 #else
   32428   { "DeleteFileA",             (SYSCALL)0,                       0 },
   32429 #endif
   32430 
   32431 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
   32432 
   32433 #if defined(SQLITE_WIN32_HAS_WIDE)
   32434   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
   32435 #else
   32436   { "DeleteFileW",             (SYSCALL)0,                       0 },
   32437 #endif
   32438 
   32439 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
   32440 
   32441 #if SQLITE_OS_WINCE
   32442   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
   32443 #else
   32444   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
   32445 #endif
   32446 
   32447 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32448         LPFILETIME))aSyscall[11].pCurrent)
   32449 
   32450 #if SQLITE_OS_WINCE
   32451   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
   32452 #else
   32453   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
   32454 #endif
   32455 
   32456 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32457         LPSYSTEMTIME))aSyscall[12].pCurrent)
   32458 
   32459   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
   32460 
   32461 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
   32462 
   32463 #if defined(SQLITE_WIN32_HAS_ANSI)
   32464   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
   32465 #else
   32466   { "FormatMessageA",          (SYSCALL)0,                       0 },
   32467 #endif
   32468 
   32469 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
   32470         DWORD,va_list*))aSyscall[14].pCurrent)
   32471 
   32472 #if defined(SQLITE_WIN32_HAS_WIDE)
   32473   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
   32474 #else
   32475   { "FormatMessageW",          (SYSCALL)0,                       0 },
   32476 #endif
   32477 
   32478 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
   32479         DWORD,va_list*))aSyscall[15].pCurrent)
   32480 
   32481   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
   32482 
   32483 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
   32484 
   32485   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
   32486 
   32487 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
   32488 
   32489 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32490   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
   32491 #else
   32492   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
   32493 #endif
   32494 
   32495 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
   32496         LPDWORD))aSyscall[18].pCurrent)
   32497 
   32498 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32499   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
   32500 #else
   32501   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
   32502 #endif
   32503 
   32504 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
   32505         LPDWORD))aSyscall[19].pCurrent)
   32506 
   32507 #if defined(SQLITE_WIN32_HAS_ANSI)
   32508   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
   32509 #else
   32510   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
   32511 #endif
   32512 
   32513 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
   32514 
   32515 #if defined(SQLITE_WIN32_HAS_WIDE)
   32516   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
   32517 #else
   32518   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
   32519 #endif
   32520 
   32521 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
   32522 
   32523 #if defined(SQLITE_WIN32_HAS_WIDE)
   32524   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
   32525 #else
   32526   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
   32527 #endif
   32528 
   32529 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
   32530         LPVOID))aSyscall[22].pCurrent)
   32531 
   32532   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
   32533 
   32534 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
   32535 
   32536 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32537   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
   32538 #else
   32539   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
   32540 #endif
   32541 
   32542 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
   32543         LPSTR*))aSyscall[24].pCurrent)
   32544 
   32545 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32546   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
   32547 #else
   32548   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
   32549 #endif
   32550 
   32551 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
   32552         LPWSTR*))aSyscall[25].pCurrent)
   32553 
   32554   { "GetLastError",            (SYSCALL)GetLastError,            0 },
   32555 
   32556 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
   32557 
   32558 #if SQLITE_OS_WINCE
   32559   /* The GetProcAddressA() routine is only available on Windows CE. */
   32560   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
   32561 #else
   32562   /* All other Windows platforms expect GetProcAddress() to take
   32563   ** an ANSI string regardless of the _UNICODE setting */
   32564   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
   32565 #endif
   32566 
   32567 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
   32568         LPCSTR))aSyscall[27].pCurrent)
   32569 
   32570   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
   32571 
   32572 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
   32573 
   32574   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
   32575 
   32576 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
   32577 
   32578 #if !SQLITE_OS_WINCE
   32579   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
   32580 #else
   32581   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
   32582 #endif
   32583 
   32584 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
   32585         LPFILETIME))aSyscall[30].pCurrent)
   32586 
   32587 #if defined(SQLITE_WIN32_HAS_ANSI)
   32588   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
   32589 #else
   32590   { "GetTempPathA",            (SYSCALL)0,                       0 },
   32591 #endif
   32592 
   32593 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
   32594 
   32595 #if defined(SQLITE_WIN32_HAS_WIDE)
   32596   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
   32597 #else
   32598   { "GetTempPathW",            (SYSCALL)0,                       0 },
   32599 #endif
   32600 
   32601 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
   32602 
   32603   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
   32604 
   32605 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
   32606 
   32607 #if defined(SQLITE_WIN32_HAS_ANSI)
   32608   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
   32609 #else
   32610   { "GetVersionExA",           (SYSCALL)0,                       0 },
   32611 #endif
   32612 
   32613 #define osGetVersionExA ((BOOL(WINAPI*)( \
   32614         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
   32615 
   32616   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
   32617 
   32618 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
   32619         SIZE_T))aSyscall[35].pCurrent)
   32620 
   32621   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
   32622 
   32623 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
   32624         SIZE_T))aSyscall[36].pCurrent)
   32625 
   32626   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
   32627 
   32628 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
   32629 
   32630   { "HeapFree",                (SYSCALL)HeapFree,                0 },
   32631 
   32632 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
   32633 
   32634   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
   32635 
   32636 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
   32637         SIZE_T))aSyscall[39].pCurrent)
   32638 
   32639   { "HeapSize",                (SYSCALL)HeapSize,                0 },
   32640 
   32641 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
   32642         LPCVOID))aSyscall[40].pCurrent)
   32643 
   32644   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
   32645 
   32646 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
   32647         LPCVOID))aSyscall[41].pCurrent)
   32648 
   32649 #if defined(SQLITE_WIN32_HAS_ANSI)
   32650   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
   32651 #else
   32652   { "LoadLibraryA",            (SYSCALL)0,                       0 },
   32653 #endif
   32654 
   32655 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
   32656 
   32657 #if defined(SQLITE_WIN32_HAS_WIDE)
   32658   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
   32659 #else
   32660   { "LoadLibraryW",            (SYSCALL)0,                       0 },
   32661 #endif
   32662 
   32663 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
   32664 
   32665   { "LocalFree",               (SYSCALL)LocalFree,               0 },
   32666 
   32667 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
   32668 
   32669 #if !SQLITE_OS_WINCE
   32670   { "LockFile",                (SYSCALL)LockFile,                0 },
   32671 
   32672 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32673         DWORD))aSyscall[45].pCurrent)
   32674 #else
   32675   { "LockFile",                (SYSCALL)0,                       0 },
   32676 #endif
   32677 
   32678 #if !SQLITE_OS_WINCE
   32679   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
   32680 
   32681 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
   32682         LPOVERLAPPED))aSyscall[46].pCurrent)
   32683 #else
   32684   { "LockFileEx",              (SYSCALL)0,                       0 },
   32685 #endif
   32686 
   32687   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
   32688 
   32689 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32690         SIZE_T))aSyscall[47].pCurrent)
   32691 
   32692   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
   32693 
   32694 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
   32695         int))aSyscall[48].pCurrent)
   32696 
   32697   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
   32698 
   32699 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
   32700         LARGE_INTEGER*))aSyscall[49].pCurrent)
   32701 
   32702   { "ReadFile",                (SYSCALL)ReadFile,                0 },
   32703 
   32704 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
   32705         LPOVERLAPPED))aSyscall[50].pCurrent)
   32706 
   32707   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
   32708 
   32709 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
   32710 
   32711   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
   32712 
   32713 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
   32714         DWORD))aSyscall[52].pCurrent)
   32715 
   32716   { "Sleep",                   (SYSCALL)Sleep,                   0 },
   32717 
   32718 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
   32719 
   32720   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
   32721 
   32722 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
   32723         LPFILETIME))aSyscall[54].pCurrent)
   32724 
   32725 #if !SQLITE_OS_WINCE
   32726   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
   32727 
   32728 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32729         DWORD))aSyscall[55].pCurrent)
   32730 #else
   32731   { "UnlockFile",              (SYSCALL)0,                       0 },
   32732 #endif
   32733 
   32734 #if !SQLITE_OS_WINCE
   32735   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
   32736 
   32737 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32738         LPOVERLAPPED))aSyscall[56].pCurrent)
   32739 #else
   32740   { "UnlockFileEx",            (SYSCALL)0,                       0 },
   32741 #endif
   32742 
   32743   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
   32744 
   32745 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
   32746 
   32747   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
   32748 
   32749 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
   32750         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
   32751 
   32752   { "WriteFile",               (SYSCALL)WriteFile,               0 },
   32753 
   32754 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
   32755         LPOVERLAPPED))aSyscall[59].pCurrent)
   32756 
   32757 }; /* End of the overrideable system calls */
   32758 
   32759 /*
   32760 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   32761 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
   32762 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   32763 ** system call named zName.
   32764 */
   32765 static int winSetSystemCall(
   32766   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   32767   const char *zName,            /* Name of system call to override */
   32768   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   32769 ){
   32770   unsigned int i;
   32771   int rc = SQLITE_NOTFOUND;
   32772 
   32773   UNUSED_PARAMETER(pNotUsed);
   32774   if( zName==0 ){
   32775     /* If no zName is given, restore all system calls to their default
   32776     ** settings and return NULL
   32777     */
   32778     rc = SQLITE_OK;
   32779     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32780       if( aSyscall[i].pDefault ){
   32781         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   32782       }
   32783     }
   32784   }else{
   32785     /* If zName is specified, operate on only the one system call
   32786     ** specified.
   32787     */
   32788     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32789       if( strcmp(zName, aSyscall[i].zName)==0 ){
   32790         if( aSyscall[i].pDefault==0 ){
   32791           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   32792         }
   32793         rc = SQLITE_OK;
   32794         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   32795         aSyscall[i].pCurrent = pNewFunc;
   32796         break;
   32797       }
   32798     }
   32799   }
   32800   return rc;
   32801 }
   32802 
   32803 /*
   32804 ** Return the value of a system call.  Return NULL if zName is not a
   32805 ** recognized system call name.  NULL is also returned if the system call
   32806 ** is currently undefined.
   32807 */
   32808 static sqlite3_syscall_ptr winGetSystemCall(
   32809   sqlite3_vfs *pNotUsed,
   32810   const char *zName
   32811 ){
   32812   unsigned int i;
   32813 
   32814   UNUSED_PARAMETER(pNotUsed);
   32815   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32816     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   32817   }
   32818   return 0;
   32819 }
   32820 
   32821 /*
   32822 ** Return the name of the first system call after zName.  If zName==NULL
   32823 ** then return the name of the first system call.  Return NULL if zName
   32824 ** is the last system call or if zName is not the name of a valid
   32825 ** system call.
   32826 */
   32827 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
   32828   int i = -1;
   32829 
   32830   UNUSED_PARAMETER(p);
   32831   if( zName ){
   32832     for(i=0; i<ArraySize(aSyscall)-1; i++){
   32833       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   32834     }
   32835   }
   32836   for(i++; i<ArraySize(aSyscall); i++){
   32837     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   32838   }
   32839   return 0;
   32840 }
   32841 
   32842 /*
   32843 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   32844 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   32845 **
   32846 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   32847 ** the LockFileEx() API.  But we can still statically link against that
   32848 ** API as long as we don't call it when running Win95/98/ME.  A call to
   32849 ** this routine is used to determine if the host is Win95/98/ME or
   32850 ** WinNT/2K/XP so that we will know whether or not we can safely call
   32851 ** the LockFileEx() API.
   32852 */
   32853 #if SQLITE_OS_WINCE
   32854 # define isNT()  (1)
   32855 #else
   32856   static int isNT(void){
   32857     if( sqlite3_os_type==0 ){
   32858       OSVERSIONINFOA sInfo;
   32859       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   32860       osGetVersionExA(&sInfo);
   32861       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   32862     }
   32863     return sqlite3_os_type==2;
   32864   }
   32865 #endif /* SQLITE_OS_WINCE */
   32866 
   32867 #ifdef SQLITE_WIN32_MALLOC
   32868 /*
   32869 ** Allocate nBytes of memory.
   32870 */
   32871 static void *winMemMalloc(int nBytes){
   32872   HANDLE hHeap;
   32873   void *p;
   32874 
   32875   winMemAssertMagic();
   32876   hHeap = winMemGetHeap();
   32877   assert( hHeap!=0 );
   32878   assert( hHeap!=INVALID_HANDLE_VALUE );
   32879 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32880   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32881 #endif
   32882   assert( nBytes>=0 );
   32883   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   32884   if( !p ){
   32885     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
   32886                 nBytes, osGetLastError(), (void*)hHeap);
   32887   }
   32888   return p;
   32889 }
   32890 
   32891 /*
   32892 ** Free memory.
   32893 */
   32894 static void winMemFree(void *pPrior){
   32895   HANDLE hHeap;
   32896 
   32897   winMemAssertMagic();
   32898   hHeap = winMemGetHeap();
   32899   assert( hHeap!=0 );
   32900   assert( hHeap!=INVALID_HANDLE_VALUE );
   32901 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32902   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   32903 #endif
   32904   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   32905   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   32906     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
   32907                 pPrior, osGetLastError(), (void*)hHeap);
   32908   }
   32909 }
   32910 
   32911 /*
   32912 ** Change the size of an existing memory allocation
   32913 */
   32914 static void *winMemRealloc(void *pPrior, int nBytes){
   32915   HANDLE hHeap;
   32916   void *p;
   32917 
   32918   winMemAssertMagic();
   32919   hHeap = winMemGetHeap();
   32920   assert( hHeap!=0 );
   32921   assert( hHeap!=INVALID_HANDLE_VALUE );
   32922 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32923   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   32924 #endif
   32925   assert( nBytes>=0 );
   32926   if( !pPrior ){
   32927     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   32928   }else{
   32929     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   32930   }
   32931   if( !p ){
   32932     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
   32933                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
   32934                 (void*)hHeap);
   32935   }
   32936   return p;
   32937 }
   32938 
   32939 /*
   32940 ** Return the size of an outstanding allocation, in bytes.
   32941 */
   32942 static int winMemSize(void *p){
   32943   HANDLE hHeap;
   32944   SIZE_T n;
   32945 
   32946   winMemAssertMagic();
   32947   hHeap = winMemGetHeap();
   32948   assert( hHeap!=0 );
   32949   assert( hHeap!=INVALID_HANDLE_VALUE );
   32950 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32951   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32952 #endif
   32953   if( !p ) return 0;
   32954   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   32955   if( n==(SIZE_T)-1 ){
   32956     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
   32957                 p, osGetLastError(), (void*)hHeap);
   32958     return 0;
   32959   }
   32960   return (int)n;
   32961 }
   32962 
   32963 /*
   32964 ** Round up a request size to the next valid allocation size.
   32965 */
   32966 static int winMemRoundup(int n){
   32967   return n;
   32968 }
   32969 
   32970 /*
   32971 ** Initialize this module.
   32972 */
   32973 static int winMemInit(void *pAppData){
   32974   winMemData *pWinMemData = (winMemData *)pAppData;
   32975 
   32976   if( !pWinMemData ) return SQLITE_ERROR;
   32977   assert( pWinMemData->magic==WINMEM_MAGIC );
   32978   if( !pWinMemData->hHeap ){
   32979     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   32980                                       SQLITE_WIN32_HEAP_INIT_SIZE,
   32981                                       SQLITE_WIN32_HEAP_MAX_SIZE);
   32982     if( !pWinMemData->hHeap ){
   32983       sqlite3_log(SQLITE_NOMEM,
   32984           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
   32985           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
   32986           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
   32987       return SQLITE_NOMEM;
   32988     }
   32989     pWinMemData->bOwned = TRUE;
   32990   }
   32991   assert( pWinMemData->hHeap!=0 );
   32992   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   32993 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32994   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32995 #endif
   32996   return SQLITE_OK;
   32997 }
   32998 
   32999 /*
   33000 ** Deinitialize this module.
   33001 */
   33002 static void winMemShutdown(void *pAppData){
   33003   winMemData *pWinMemData = (winMemData *)pAppData;
   33004 
   33005   if( !pWinMemData ) return;
   33006   if( pWinMemData->hHeap ){
   33007     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   33008 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   33009     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   33010 #endif
   33011     if( pWinMemData->bOwned ){
   33012       if( !osHeapDestroy(pWinMemData->hHeap) ){
   33013         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
   33014                     osGetLastError(), (void*)pWinMemData->hHeap);
   33015       }
   33016       pWinMemData->bOwned = FALSE;
   33017     }
   33018     pWinMemData->hHeap = NULL;
   33019   }
   33020 }
   33021 
   33022 /*
   33023 ** Populate the low-level memory allocation function pointers in
   33024 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   33025 ** arguments specify the block of memory to manage.
   33026 **
   33027 ** This routine is only called by sqlite3_config(), and therefore
   33028 ** is not required to be threadsafe (it is not).
   33029 */
   33030 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
   33031   static const sqlite3_mem_methods winMemMethods = {
   33032     winMemMalloc,
   33033     winMemFree,
   33034     winMemRealloc,
   33035     winMemSize,
   33036     winMemRoundup,
   33037     winMemInit,
   33038     winMemShutdown,
   33039     &win_mem_data
   33040   };
   33041   return &winMemMethods;
   33042 }
   33043 
   33044 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   33045   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   33046 }
   33047 #endif /* SQLITE_WIN32_MALLOC */
   33048 
   33049 /*
   33050 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
   33051 **
   33052 ** Space to hold the returned string is obtained from malloc.
   33053 */
   33054 static LPWSTR utf8ToUnicode(const char *zFilename){
   33055   int nChar;
   33056   LPWSTR zWideFilename;
   33057 
   33058   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   33059   if( nChar==0 ){
   33060     return 0;
   33061   }
   33062   zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
   33063   if( zWideFilename==0 ){
   33064     return 0;
   33065   }
   33066   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
   33067                                 nChar);
   33068   if( nChar==0 ){
   33069     sqlite3_free(zWideFilename);
   33070     zWideFilename = 0;
   33071   }
   33072   return zWideFilename;
   33073 }
   33074 
   33075 /*
   33076 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
   33077 ** obtained from sqlite3_malloc().
   33078 */
   33079 static char *unicodeToUtf8(LPCWSTR zWideFilename){
   33080   int nByte;
   33081   char *zFilename;
   33082 
   33083   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   33084   if( nByte == 0 ){
   33085     return 0;
   33086   }
   33087   zFilename = sqlite3_malloc( nByte );
   33088   if( zFilename==0 ){
   33089     return 0;
   33090   }
   33091   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   33092                                 0, 0);
   33093   if( nByte == 0 ){
   33094     sqlite3_free(zFilename);
   33095     zFilename = 0;
   33096   }
   33097   return zFilename;
   33098 }
   33099 
   33100 /*
   33101 ** Convert an ANSI string to Microsoft Unicode, based on the
   33102 ** current codepage settings for file apis.
   33103 **
   33104 ** Space to hold the returned string is obtained
   33105 ** from sqlite3_malloc.
   33106 */
   33107 static LPWSTR mbcsToUnicode(const char *zFilename){
   33108   int nByte;
   33109   LPWSTR zMbcsFilename;
   33110   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33111 
   33112   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
   33113                                 0)*sizeof(WCHAR);
   33114   if( nByte==0 ){
   33115     return 0;
   33116   }
   33117   zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
   33118   if( zMbcsFilename==0 ){
   33119     return 0;
   33120   }
   33121   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
   33122                                 nByte);
   33123   if( nByte==0 ){
   33124     sqlite3_free(zMbcsFilename);
   33125     zMbcsFilename = 0;
   33126   }
   33127   return zMbcsFilename;
   33128 }
   33129 
   33130 /*
   33131 ** Convert Microsoft Unicode to multi-byte character string, based on the
   33132 ** user's ANSI codepage.
   33133 **
   33134 ** Space to hold the returned string is obtained from
   33135 ** sqlite3_malloc().
   33136 */
   33137 static char *unicodeToMbcs(LPCWSTR zWideFilename){
   33138   int nByte;
   33139   char *zFilename;
   33140   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33141 
   33142   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   33143   if( nByte == 0 ){
   33144     return 0;
   33145   }
   33146   zFilename = sqlite3_malloc( nByte );
   33147   if( zFilename==0 ){
   33148     return 0;
   33149   }
   33150   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
   33151                                 nByte, 0, 0);
   33152   if( nByte == 0 ){
   33153     sqlite3_free(zFilename);
   33154     zFilename = 0;
   33155   }
   33156   return zFilename;
   33157 }
   33158 
   33159 /*
   33160 ** Convert multibyte character string to UTF-8.  Space to hold the
   33161 ** returned string is obtained from sqlite3_malloc().
   33162 */
   33163 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   33164   char *zFilenameUtf8;
   33165   LPWSTR zTmpWide;
   33166 
   33167   zTmpWide = mbcsToUnicode(zFilename);
   33168   if( zTmpWide==0 ){
   33169     return 0;
   33170   }
   33171   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
   33172   sqlite3_free(zTmpWide);
   33173   return zFilenameUtf8;
   33174 }
   33175 
   33176 /*
   33177 ** Convert UTF-8 to multibyte character string.  Space to hold the
   33178 ** returned string is obtained from sqlite3_malloc().
   33179 */
   33180 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
   33181   char *zFilenameMbcs;
   33182   LPWSTR zTmpWide;
   33183 
   33184   zTmpWide = utf8ToUnicode(zFilename);
   33185   if( zTmpWide==0 ){
   33186     return 0;
   33187   }
   33188   zFilenameMbcs = unicodeToMbcs(zTmpWide);
   33189   sqlite3_free(zTmpWide);
   33190   return zFilenameMbcs;
   33191 }
   33192 
   33193 
   33194 /*
   33195 ** The return value of getLastErrorMsg
   33196 ** is zero if the error message fits in the buffer, or non-zero
   33197 ** otherwise (if the message was truncated).
   33198 */
   33199 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   33200   /* FormatMessage returns 0 on failure.  Otherwise it
   33201   ** returns the number of TCHARs written to the output
   33202   ** buffer, excluding the terminating null char.
   33203   */
   33204   DWORD dwLen = 0;
   33205   char *zOut = 0;
   33206 
   33207   if( isNT() ){
   33208     LPWSTR zTempWide = NULL;
   33209     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33210                              FORMAT_MESSAGE_FROM_SYSTEM |
   33211                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33212                              NULL,
   33213                              lastErrno,
   33214                              0,
   33215                              (LPWSTR) &zTempWide,
   33216                              0,
   33217                              0);
   33218     if( dwLen > 0 ){
   33219       /* allocate a buffer and convert to UTF8 */
   33220       sqlite3BeginBenignMalloc();
   33221       zOut = unicodeToUtf8(zTempWide);
   33222       sqlite3EndBenignMalloc();
   33223       /* free the system buffer allocated by FormatMessage */
   33224       osLocalFree(zTempWide);
   33225     }
   33226 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   33227 ** Since the ANSI version of these Windows API do not exist for WINCE,
   33228 ** it's important to not reference them for WINCE builds.
   33229 */
   33230 #if SQLITE_OS_WINCE==0
   33231   }else{
   33232     char *zTemp = NULL;
   33233     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33234                              FORMAT_MESSAGE_FROM_SYSTEM |
   33235                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33236                              NULL,
   33237                              lastErrno,
   33238                              0,
   33239                              (LPSTR) &zTemp,
   33240                              0,
   33241                              0);
   33242     if( dwLen > 0 ){
   33243       /* allocate a buffer and convert to UTF8 */
   33244       sqlite3BeginBenignMalloc();
   33245       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   33246       sqlite3EndBenignMalloc();
   33247       /* free the system buffer allocated by FormatMessage */
   33248       osLocalFree(zTemp);
   33249     }
   33250 #endif
   33251   }
   33252   if( 0 == dwLen ){
   33253     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
   33254   }else{
   33255     /* copy a maximum of nBuf chars to output buffer */
   33256     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   33257     /* free the UTF8 buffer */
   33258     sqlite3_free(zOut);
   33259   }
   33260   return 0;
   33261 }
   33262 
   33263 /*
   33264 **
   33265 ** This function - winLogErrorAtLine() - is only ever called via the macro
   33266 ** winLogError().
   33267 **
   33268 ** This routine is invoked after an error occurs in an OS function.
   33269 ** It logs a message using sqlite3_log() containing the current value of
   33270 ** error code and, if possible, the human-readable equivalent from
   33271 ** FormatMessage.
   33272 **
   33273 ** The first argument passed to the macro should be the error code that
   33274 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   33275 ** The two subsequent arguments should be the name of the OS function that
   33276 ** failed and the the associated file-system path, if any.
   33277 */
   33278 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   33279 static int winLogErrorAtLine(
   33280   int errcode,                    /* SQLite error code */
   33281   DWORD lastErrno,                /* Win32 last error */
   33282   const char *zFunc,              /* Name of OS function that failed */
   33283   const char *zPath,              /* File path associated with error */
   33284   int iLine                       /* Source line number where error occurred */
   33285 ){
   33286   char zMsg[500];                 /* Human readable error text */
   33287   int i;                          /* Loop counter */
   33288 
   33289   zMsg[0] = 0;
   33290   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   33291   assert( errcode!=SQLITE_OK );
   33292   if( zPath==0 ) zPath = "";
   33293   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   33294   zMsg[i] = 0;
   33295   sqlite3_log(errcode,
   33296       "os_win.c:%d: (%d) %s(%s) - %s",
   33297       iLine, lastErrno, zFunc, zPath, zMsg
   33298   );
   33299 
   33300   return errcode;
   33301 }
   33302 
   33303 /*
   33304 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
   33305 ** will be retried following a locking error - probably caused by
   33306 ** antivirus software.  Also the initial delay before the first retry.
   33307 ** The delay increases linearly with each retry.
   33308 */
   33309 #ifndef SQLITE_WIN32_IOERR_RETRY
   33310 # define SQLITE_WIN32_IOERR_RETRY 10
   33311 #endif
   33312 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
   33313 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
   33314 #endif
   33315 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
   33316 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   33317 
   33318 /*
   33319 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   33320 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   33321 ** to give up with an error.
   33322 */
   33323 static int retryIoerr(int *pnRetry, DWORD *pError){
   33324   DWORD e = osGetLastError();
   33325   if( *pnRetry>=win32IoerrRetry ){
   33326     if( pError ){
   33327       *pError = e;
   33328     }
   33329     return 0;
   33330   }
   33331   if( e==ERROR_ACCESS_DENIED ||
   33332       e==ERROR_LOCK_VIOLATION ||
   33333       e==ERROR_SHARING_VIOLATION ){
   33334     osSleep(win32IoerrRetryDelay*(1+*pnRetry));
   33335     ++*pnRetry;
   33336     return 1;
   33337   }
   33338   if( pError ){
   33339     *pError = e;
   33340   }
   33341   return 0;
   33342 }
   33343 
   33344 /*
   33345 ** Log a I/O error retry episode.
   33346 */
   33347 static void logIoerr(int nRetry){
   33348   if( nRetry ){
   33349     sqlite3_log(SQLITE_IOERR,
   33350       "delayed %dms for lock/sharing conflict",
   33351       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
   33352     );
   33353   }
   33354 }
   33355 
   33356 #if SQLITE_OS_WINCE
   33357 /*************************************************************************
   33358 ** This section contains code for WinCE only.
   33359 */
   33360 /*
   33361 ** Windows CE does not have a localtime() function.  So create a
   33362 ** substitute.
   33363 */
   33364 /* #include <time.h> */
   33365 struct tm *__cdecl localtime(const time_t *t)
   33366 {
   33367   static struct tm y;
   33368   FILETIME uTm, lTm;
   33369   SYSTEMTIME pTm;
   33370   sqlite3_int64 t64;
   33371   t64 = *t;
   33372   t64 = (t64 + 11644473600)*10000000;
   33373   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   33374   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   33375   osFileTimeToLocalFileTime(&uTm,&lTm);
   33376   osFileTimeToSystemTime(&lTm,&pTm);
   33377   y.tm_year = pTm.wYear - 1900;
   33378   y.tm_mon = pTm.wMonth - 1;
   33379   y.tm_wday = pTm.wDayOfWeek;
   33380   y.tm_mday = pTm.wDay;
   33381   y.tm_hour = pTm.wHour;
   33382   y.tm_min = pTm.wMinute;
   33383   y.tm_sec = pTm.wSecond;
   33384   return &y;
   33385 }
   33386 
   33387 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   33388 
   33389 /*
   33390 ** Acquire a lock on the handle h
   33391 */
   33392 static void winceMutexAcquire(HANDLE h){
   33393    DWORD dwErr;
   33394    do {
   33395      dwErr = WaitForSingleObject(h, INFINITE);
   33396    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   33397 }
   33398 /*
   33399 ** Release a lock acquired by winceMutexAcquire()
   33400 */
   33401 #define winceMutexRelease(h) ReleaseMutex(h)
   33402 
   33403 /*
   33404 ** Create the mutex and shared memory used for locking in the file
   33405 ** descriptor pFile
   33406 */
   33407 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
   33408   LPWSTR zTok;
   33409   LPWSTR zName;
   33410   BOOL bInit = TRUE;
   33411 
   33412   zName = utf8ToUnicode(zFilename);
   33413   if( zName==0 ){
   33414     /* out of memory */
   33415     return FALSE;
   33416   }
   33417 
   33418   /* Initialize the local lockdata */
   33419   memset(&pFile->local, 0, sizeof(pFile->local));
   33420 
   33421   /* Replace the backslashes from the filename and lowercase it
   33422   ** to derive a mutex name. */
   33423   zTok = osCharLowerW(zName);
   33424   for (;*zTok;zTok++){
   33425     if (*zTok == '\\') *zTok = '_';
   33426   }
   33427 
   33428   /* Create/open the named mutex */
   33429   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   33430   if (!pFile->hMutex){
   33431     pFile->lastErrno = osGetLastError();
   33432     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
   33433     sqlite3_free(zName);
   33434     return FALSE;
   33435   }
   33436 
   33437   /* Acquire the mutex before continuing */
   33438   winceMutexAcquire(pFile->hMutex);
   33439 
   33440   /* Since the names of named mutexes, semaphores, file mappings etc are
   33441   ** case-sensitive, take advantage of that by uppercasing the mutex name
   33442   ** and using that as the shared filemapping name.
   33443   */
   33444   osCharUpperW(zName);
   33445   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   33446                                         PAGE_READWRITE, 0, sizeof(winceLock),
   33447                                         zName);
   33448 
   33449   /* Set a flag that indicates we're the first to create the memory so it
   33450   ** must be zero-initialized */
   33451   if (osGetLastError() == ERROR_ALREADY_EXISTS){
   33452     bInit = FALSE;
   33453   }
   33454 
   33455   sqlite3_free(zName);
   33456 
   33457   /* If we succeeded in making the shared memory handle, map it. */
   33458   if (pFile->hShared){
   33459     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
   33460              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   33461     /* If mapping failed, close the shared memory handle and erase it */
   33462     if (!pFile->shared){
   33463       pFile->lastErrno = osGetLastError();
   33464       winLogError(SQLITE_ERROR, pFile->lastErrno,
   33465                "winceCreateLock2", zFilename);
   33466       osCloseHandle(pFile->hShared);
   33467       pFile->hShared = NULL;
   33468     }
   33469   }
   33470 
   33471   /* If shared memory could not be created, then close the mutex and fail */
   33472   if (pFile->hShared == NULL){
   33473     winceMutexRelease(pFile->hMutex);
   33474     osCloseHandle(pFile->hMutex);
   33475     pFile->hMutex = NULL;
   33476     return FALSE;
   33477   }
   33478 
   33479   /* Initialize the shared memory if we're supposed to */
   33480   if (bInit) {
   33481     memset(pFile->shared, 0, sizeof(winceLock));
   33482   }
   33483 
   33484   winceMutexRelease(pFile->hMutex);
   33485   return TRUE;
   33486 }
   33487 
   33488 /*
   33489 ** Destroy the part of winFile that deals with wince locks
   33490 */
   33491 static void winceDestroyLock(winFile *pFile){
   33492   if (pFile->hMutex){
   33493     /* Acquire the mutex */
   33494     winceMutexAcquire(pFile->hMutex);
   33495 
   33496     /* The following blocks should probably assert in debug mode, but they
   33497        are to cleanup in case any locks remained open */
   33498     if (pFile->local.nReaders){
   33499       pFile->shared->nReaders --;
   33500     }
   33501     if (pFile->local.bReserved){
   33502       pFile->shared->bReserved = FALSE;
   33503     }
   33504     if (pFile->local.bPending){
   33505       pFile->shared->bPending = FALSE;
   33506     }
   33507     if (pFile->local.bExclusive){
   33508       pFile->shared->bExclusive = FALSE;
   33509     }
   33510 
   33511     /* De-reference and close our copy of the shared memory handle */
   33512     osUnmapViewOfFile(pFile->shared);
   33513     osCloseHandle(pFile->hShared);
   33514 
   33515     /* Done with the mutex */
   33516     winceMutexRelease(pFile->hMutex);
   33517     osCloseHandle(pFile->hMutex);
   33518     pFile->hMutex = NULL;
   33519   }
   33520 }
   33521 
   33522 /*
   33523 ** An implementation of the LockFile() API of Windows for CE
   33524 */
   33525 static BOOL winceLockFile(
   33526   HANDLE *phFile,
   33527   DWORD dwFileOffsetLow,
   33528   DWORD dwFileOffsetHigh,
   33529   DWORD nNumberOfBytesToLockLow,
   33530   DWORD nNumberOfBytesToLockHigh
   33531 ){
   33532   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   33533   BOOL bReturn = FALSE;
   33534 
   33535   UNUSED_PARAMETER(dwFileOffsetHigh);
   33536   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   33537 
   33538   if (!pFile->hMutex) return TRUE;
   33539   winceMutexAcquire(pFile->hMutex);
   33540 
   33541   /* Wanting an exclusive lock? */
   33542   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   33543        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   33544     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   33545        pFile->shared->bExclusive = TRUE;
   33546        pFile->local.bExclusive = TRUE;
   33547        bReturn = TRUE;
   33548     }
   33549   }
   33550 
   33551   /* Want a read-only lock? */
   33552   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   33553            nNumberOfBytesToLockLow == 1){
   33554     if (pFile->shared->bExclusive == 0){
   33555       pFile->local.nReaders ++;
   33556       if (pFile->local.nReaders == 1){
   33557         pFile->shared->nReaders ++;
   33558       }
   33559       bReturn = TRUE;
   33560     }
   33561   }
   33562 
   33563   /* Want a pending lock? */
   33564   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
   33565     /* If no pending lock has been acquired, then acquire it */
   33566     if (pFile->shared->bPending == 0) {
   33567       pFile->shared->bPending = TRUE;
   33568       pFile->local.bPending = TRUE;
   33569       bReturn = TRUE;
   33570     }
   33571   }
   33572 
   33573   /* Want a reserved lock? */
   33574   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
   33575     if (pFile->shared->bReserved == 0) {
   33576       pFile->shared->bReserved = TRUE;
   33577       pFile->local.bReserved = TRUE;
   33578       bReturn = TRUE;
   33579     }
   33580   }
   33581 
   33582   winceMutexRelease(pFile->hMutex);
   33583   return bReturn;
   33584 }
   33585 
   33586 /*
   33587 ** An implementation of the UnlockFile API of Windows for CE
   33588 */
   33589 static BOOL winceUnlockFile(
   33590   HANDLE *phFile,
   33591   DWORD dwFileOffsetLow,
   33592   DWORD dwFileOffsetHigh,
   33593   DWORD nNumberOfBytesToUnlockLow,
   33594   DWORD nNumberOfBytesToUnlockHigh
   33595 ){
   33596   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   33597   BOOL bReturn = FALSE;
   33598 
   33599   UNUSED_PARAMETER(dwFileOffsetHigh);
   33600   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   33601 
   33602   if (!pFile->hMutex) return TRUE;
   33603   winceMutexAcquire(pFile->hMutex);
   33604 
   33605   /* Releasing a reader lock or an exclusive lock */
   33606   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   33607     /* Did we have an exclusive lock? */
   33608     if (pFile->local.bExclusive){
   33609       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   33610       pFile->local.bExclusive = FALSE;
   33611       pFile->shared->bExclusive = FALSE;
   33612       bReturn = TRUE;
   33613     }
   33614 
   33615     /* Did we just have a reader lock? */
   33616     else if (pFile->local.nReaders){
   33617       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
   33618       pFile->local.nReaders --;
   33619       if (pFile->local.nReaders == 0)
   33620       {
   33621         pFile->shared->nReaders --;
   33622       }
   33623       bReturn = TRUE;
   33624     }
   33625   }
   33626 
   33627   /* Releasing a pending lock */
   33628   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
   33629     if (pFile->local.bPending){
   33630       pFile->local.bPending = FALSE;
   33631       pFile->shared->bPending = FALSE;
   33632       bReturn = TRUE;
   33633     }
   33634   }
   33635   /* Releasing a reserved lock */
   33636   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
   33637     if (pFile->local.bReserved) {
   33638       pFile->local.bReserved = FALSE;
   33639       pFile->shared->bReserved = FALSE;
   33640       bReturn = TRUE;
   33641     }
   33642   }
   33643 
   33644   winceMutexRelease(pFile->hMutex);
   33645   return bReturn;
   33646 }
   33647 
   33648 /*
   33649 ** An implementation of the LockFileEx() API of Windows for CE
   33650 */
   33651 static BOOL winceLockFileEx(
   33652   HANDLE *phFile,
   33653   DWORD dwFlags,
   33654   DWORD dwReserved,
   33655   DWORD nNumberOfBytesToLockLow,
   33656   DWORD nNumberOfBytesToLockHigh,
   33657   LPOVERLAPPED lpOverlapped
   33658 ){
   33659   UNUSED_PARAMETER(dwReserved);
   33660   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   33661 
   33662   /* If the caller wants a shared read lock, forward this call
   33663   ** to winceLockFile */
   33664   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
   33665       dwFlags == 1 &&
   33666       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   33667     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
   33668   }
   33669   return FALSE;
   33670 }
   33671 /*
   33672 ** End of the special code for wince
   33673 *****************************************************************************/
   33674 #endif /* SQLITE_OS_WINCE */
   33675 
   33676 /*****************************************************************************
   33677 ** The next group of routines implement the I/O methods specified
   33678 ** by the sqlite3_io_methods object.
   33679 ******************************************************************************/
   33680 
   33681 /*
   33682 ** Some Microsoft compilers lack this definition.
   33683 */
   33684 #ifndef INVALID_SET_FILE_POINTER
   33685 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   33686 #endif
   33687 
   33688 /*
   33689 ** Move the current position of the file handle passed as the first
   33690 ** argument to offset iOffset within the file. If successful, return 0.
   33691 ** Otherwise, set pFile->lastErrno and return non-zero.
   33692 */
   33693 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
   33694   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   33695   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   33696   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   33697   DWORD lastErrno;                /* Value returned by GetLastError() */
   33698 
   33699   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   33700   lowerBits = (LONG)(iOffset & 0xffffffff);
   33701 
   33702   /* API oddity: If successful, SetFilePointer() returns a dword
   33703   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   33704   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   33705   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   33706   ** whether an error has actually occured, it is also necessary to call
   33707   ** GetLastError().
   33708   */
   33709   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   33710 
   33711   if( (dwRet==INVALID_SET_FILE_POINTER
   33712       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
   33713     pFile->lastErrno = lastErrno;
   33714     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   33715              "seekWinFile", pFile->zPath);
   33716     return 1;
   33717   }
   33718 
   33719   return 0;
   33720 }
   33721 
   33722 /*
   33723 ** Close a file.
   33724 **
   33725 ** It is reported that an attempt to close a handle might sometimes
   33726 ** fail.  This is a very unreasonable result, but Windows is notorious
   33727 ** for being unreasonable so I do not doubt that it might happen.  If
   33728 ** the close fails, we pause for 100 milliseconds and try again.  As
   33729 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   33730 ** giving up and returning an error.
   33731 */
   33732 #define MX_CLOSE_ATTEMPT 3
   33733 static int winClose(sqlite3_file *id){
   33734   int rc, cnt = 0;
   33735   winFile *pFile = (winFile*)id;
   33736 
   33737   assert( id!=0 );
   33738   assert( pFile->pShm==0 );
   33739   OSTRACE(("CLOSE %d\n", pFile->h));
   33740   do{
   33741     rc = osCloseHandle(pFile->h);
   33742     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   33743   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) );
   33744 #if SQLITE_OS_WINCE
   33745 #define WINCE_DELETION_ATTEMPTS 3
   33746   winceDestroyLock(pFile);
   33747   if( pFile->zDeleteOnClose ){
   33748     int cnt = 0;
   33749     while(
   33750            osDeleteFileW(pFile->zDeleteOnClose)==0
   33751         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   33752         && cnt++ < WINCE_DELETION_ATTEMPTS
   33753     ){
   33754        osSleep(100);  /* Wait a little before trying again */
   33755     }
   33756     sqlite3_free(pFile->zDeleteOnClose);
   33757   }
   33758 #endif
   33759   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
   33760   OpenCounter(-1);
   33761   return rc ? SQLITE_OK
   33762             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
   33763                           "winClose", pFile->zPath);
   33764 }
   33765 
   33766 /*
   33767 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   33768 ** bytes were read successfully and SQLITE_IOERR if anything goes
   33769 ** wrong.
   33770 */
   33771 static int winRead(
   33772   sqlite3_file *id,          /* File to read from */
   33773   void *pBuf,                /* Write content into this buffer */
   33774   int amt,                   /* Number of bytes to read */
   33775   sqlite3_int64 offset       /* Begin reading at this offset */
   33776 ){
   33777   winFile *pFile = (winFile*)id;  /* file handle */
   33778   DWORD nRead;                    /* Number of bytes actually read from file */
   33779   int nRetry = 0;                 /* Number of retrys */
   33780 
   33781   assert( id!=0 );
   33782   SimulateIOError(return SQLITE_IOERR_READ);
   33783   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
   33784 
   33785   if( seekWinFile(pFile, offset) ){
   33786     return SQLITE_FULL;
   33787   }
   33788   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   33789     DWORD lastErrno;
   33790     if( retryIoerr(&nRetry, &lastErrno) ) continue;
   33791     pFile->lastErrno = lastErrno;
   33792     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
   33793              "winRead", pFile->zPath);
   33794   }
   33795   logIoerr(nRetry);
   33796   if( nRead<(DWORD)amt ){
   33797     /* Unread parts of the buffer must be zero-filled */
   33798     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   33799     return SQLITE_IOERR_SHORT_READ;
   33800   }
   33801 
   33802   return SQLITE_OK;
   33803 }
   33804 
   33805 /*
   33806 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   33807 ** or some other error code on failure.
   33808 */
   33809 static int winWrite(
   33810   sqlite3_file *id,               /* File to write into */
   33811   const void *pBuf,               /* The bytes to be written */
   33812   int amt,                        /* Number of bytes to write */
   33813   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   33814 ){
   33815   int rc;                         /* True if error has occured, else false */
   33816   winFile *pFile = (winFile*)id;  /* File handle */
   33817   int nRetry = 0;                 /* Number of retries */
   33818 
   33819   assert( amt>0 );
   33820   assert( pFile );
   33821   SimulateIOError(return SQLITE_IOERR_WRITE);
   33822   SimulateDiskfullError(return SQLITE_FULL);
   33823 
   33824   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
   33825 
   33826   rc = seekWinFile(pFile, offset);
   33827   if( rc==0 ){
   33828     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   33829     int nRem = amt;               /* Number of bytes yet to be written */
   33830     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   33831     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
   33832 
   33833     while( nRem>0 ){
   33834       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
   33835         if( retryIoerr(&nRetry, &lastErrno) ) continue;
   33836         break;
   33837       }
   33838       if( nWrite<=0 ) break;
   33839       aRem += nWrite;
   33840       nRem -= nWrite;
   33841     }
   33842     if( nRem>0 ){
   33843       pFile->lastErrno = lastErrno;
   33844       rc = 1;
   33845     }
   33846   }
   33847 
   33848   if( rc ){
   33849     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
   33850        || ( pFile->lastErrno==ERROR_DISK_FULL )){
   33851       return SQLITE_FULL;
   33852     }
   33853     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
   33854              "winWrite", pFile->zPath);
   33855   }else{
   33856     logIoerr(nRetry);
   33857   }
   33858   return SQLITE_OK;
   33859 }
   33860 
   33861 /*
   33862 ** Truncate an open file to a specified size
   33863 */
   33864 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   33865   winFile *pFile = (winFile*)id;  /* File handle object */
   33866   int rc = SQLITE_OK;             /* Return code for this function */
   33867 
   33868   assert( pFile );
   33869 
   33870   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
   33871   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   33872 
   33873   /* If the user has configured a chunk-size for this file, truncate the
   33874   ** file so that it consists of an integer number of chunks (i.e. the
   33875   ** actual file size after the operation may be larger than the requested
   33876   ** size).
   33877   */
   33878   if( pFile->szChunk>0 ){
   33879     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   33880   }
   33881 
   33882   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   33883   if( seekWinFile(pFile, nByte) ){
   33884     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   33885              "winTruncate1", pFile->zPath);
   33886   }else if( 0==osSetEndOfFile(pFile->h) ){
   33887     pFile->lastErrno = osGetLastError();
   33888     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   33889              "winTruncate2", pFile->zPath);
   33890   }
   33891 
   33892   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
   33893   return rc;
   33894 }
   33895 
   33896 #ifdef SQLITE_TEST
   33897 /*
   33898 ** Count the number of fullsyncs and normal syncs.  This is used to test
   33899 ** that syncs and fullsyncs are occuring at the right times.
   33900 */
   33901 SQLITE_API int sqlite3_sync_count = 0;
   33902 SQLITE_API int sqlite3_fullsync_count = 0;
   33903 #endif
   33904 
   33905 /*
   33906 ** Make sure all writes to a particular file are committed to disk.
   33907 */
   33908 static int winSync(sqlite3_file *id, int flags){
   33909 #ifndef SQLITE_NO_SYNC
   33910   /*
   33911   ** Used only when SQLITE_NO_SYNC is not defined.
   33912    */
   33913   BOOL rc;
   33914 #endif
   33915 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
   33916     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
   33917   /*
   33918   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
   33919   ** OSTRACE() macros.
   33920    */
   33921   winFile *pFile = (winFile*)id;
   33922 #else
   33923   UNUSED_PARAMETER(id);
   33924 #endif
   33925 
   33926   assert( pFile );
   33927   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   33928   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   33929       || (flags&0x0F)==SQLITE_SYNC_FULL
   33930   );
   33931 
   33932   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
   33933 
   33934   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   33935   ** line is to test that doing so does not cause any problems.
   33936   */
   33937   SimulateDiskfullError( return SQLITE_FULL );
   33938 
   33939 #ifndef SQLITE_TEST
   33940   UNUSED_PARAMETER(flags);
   33941 #else
   33942   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
   33943     sqlite3_fullsync_count++;
   33944   }
   33945   sqlite3_sync_count++;
   33946 #endif
   33947 
   33948   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   33949   ** no-op
   33950   */
   33951 #ifdef SQLITE_NO_SYNC
   33952   return SQLITE_OK;
   33953 #else
   33954   rc = osFlushFileBuffers(pFile->h);
   33955   SimulateIOError( rc=FALSE );
   33956   if( rc ){
   33957     return SQLITE_OK;
   33958   }else{
   33959     pFile->lastErrno = osGetLastError();
   33960     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
   33961              "winSync", pFile->zPath);
   33962   }
   33963 #endif
   33964 }
   33965 
   33966 /*
   33967 ** Determine the current size of a file in bytes
   33968 */
   33969 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   33970   DWORD upperBits;
   33971   DWORD lowerBits;
   33972   winFile *pFile = (winFile*)id;
   33973   DWORD lastErrno;
   33974 
   33975   assert( id!=0 );
   33976   SimulateIOError(return SQLITE_IOERR_FSTAT);
   33977   lowerBits = osGetFileSize(pFile->h, &upperBits);
   33978   if(   (lowerBits == INVALID_FILE_SIZE)
   33979      && ((lastErrno = osGetLastError())!=NO_ERROR) )
   33980   {
   33981     pFile->lastErrno = lastErrno;
   33982     return winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   33983              "winFileSize", pFile->zPath);
   33984   }
   33985   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   33986   return SQLITE_OK;
   33987 }
   33988 
   33989 /*
   33990 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   33991 */
   33992 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   33993 # define LOCKFILE_FAIL_IMMEDIATELY 1
   33994 #endif
   33995 
   33996 /*
   33997 ** Acquire a reader lock.
   33998 ** Different API routines are called depending on whether or not this
   33999 ** is Win9x or WinNT.
   34000 */
   34001 static int getReadLock(winFile *pFile){
   34002   int res;
   34003   if( isNT() ){
   34004     OVERLAPPED ovlp;
   34005     ovlp.Offset = SHARED_FIRST;
   34006     ovlp.OffsetHigh = 0;
   34007     ovlp.hEvent = 0;
   34008     res = osLockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
   34009                        0, SHARED_SIZE, 0, &ovlp);
   34010 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   34011 */
   34012 #if SQLITE_OS_WINCE==0
   34013   }else{
   34014     int lk;
   34015     sqlite3_randomness(sizeof(lk), &lk);
   34016     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   34017     res = osLockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34018 #endif
   34019   }
   34020   if( res == 0 ){
   34021     pFile->lastErrno = osGetLastError();
   34022     /* No need to log a failure to lock */
   34023   }
   34024   return res;
   34025 }
   34026 
   34027 /*
   34028 ** Undo a readlock
   34029 */
   34030 static int unlockReadLock(winFile *pFile){
   34031   int res;
   34032   DWORD lastErrno;
   34033   if( isNT() ){
   34034     res = osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34035 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   34036 */
   34037 #if SQLITE_OS_WINCE==0
   34038   }else{
   34039     res = osUnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
   34040 #endif
   34041   }
   34042   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
   34043     pFile->lastErrno = lastErrno;
   34044     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
   34045              "unlockReadLock", pFile->zPath);
   34046   }
   34047   return res;
   34048 }
   34049 
   34050 /*
   34051 ** Lock the file with the lock specified by parameter locktype - one
   34052 ** of the following:
   34053 **
   34054 **     (1) SHARED_LOCK
   34055 **     (2) RESERVED_LOCK
   34056 **     (3) PENDING_LOCK
   34057 **     (4) EXCLUSIVE_LOCK
   34058 **
   34059 ** Sometimes when requesting one lock state, additional lock states
   34060 ** are inserted in between.  The locking might fail on one of the later
   34061 ** transitions leaving the lock state different from what it started but
   34062 ** still short of its goal.  The following chart shows the allowed
   34063 ** transitions and the inserted intermediate states:
   34064 **
   34065 **    UNLOCKED -> SHARED
   34066 **    SHARED -> RESERVED
   34067 **    SHARED -> (PENDING) -> EXCLUSIVE
   34068 **    RESERVED -> (PENDING) -> EXCLUSIVE
   34069 **    PENDING -> EXCLUSIVE
   34070 **
   34071 ** This routine will only increase a lock.  The winUnlock() routine
   34072 ** erases all locks at once and returns us immediately to locking level 0.
   34073 ** It is not possible to lower the locking level one step at a time.  You
   34074 ** must go straight to locking level 0.
   34075 */
   34076 static int winLock(sqlite3_file *id, int locktype){
   34077   int rc = SQLITE_OK;    /* Return code from subroutines */
   34078   int res = 1;           /* Result of a Windows lock call */
   34079   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   34080   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   34081   winFile *pFile = (winFile*)id;
   34082   DWORD lastErrno = NO_ERROR;
   34083 
   34084   assert( id!=0 );
   34085   OSTRACE(("LOCK %d %d was %d(%d)\n",
   34086            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
   34087 
   34088   /* If there is already a lock of this type or more restrictive on the
   34089   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   34090   ** sqlite3OsEnterMutex() hasn't been called yet.
   34091   */
   34092   if( pFile->locktype>=locktype ){
   34093     return SQLITE_OK;
   34094   }
   34095 
   34096   /* Make sure the locking sequence is correct
   34097   */
   34098   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   34099   assert( locktype!=PENDING_LOCK );
   34100   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   34101 
   34102   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   34103   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   34104   ** the PENDING_LOCK byte is temporary.
   34105   */
   34106   newLocktype = pFile->locktype;
   34107   if(   (pFile->locktype==NO_LOCK)
   34108      || (   (locktype==EXCLUSIVE_LOCK)
   34109          && (pFile->locktype==RESERVED_LOCK))
   34110   ){
   34111     int cnt = 3;
   34112     while( cnt-->0 && (res = osLockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
   34113       /* Try 3 times to get the pending lock.  This is needed to work
   34114       ** around problems caused by indexing and/or anti-virus software on
   34115       ** Windows systems.
   34116       ** If you are using this code as a model for alternative VFSes, do not
   34117       ** copy this retry logic.  It is a hack intended for Windows only.
   34118       */
   34119       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
   34120       if( cnt ) osSleep(1);
   34121     }
   34122     gotPendingLock = res;
   34123     if( !res ){
   34124       lastErrno = osGetLastError();
   34125     }
   34126   }
   34127 
   34128   /* Acquire a shared lock
   34129   */
   34130   if( locktype==SHARED_LOCK && res ){
   34131     assert( pFile->locktype==NO_LOCK );
   34132     res = getReadLock(pFile);
   34133     if( res ){
   34134       newLocktype = SHARED_LOCK;
   34135     }else{
   34136       lastErrno = osGetLastError();
   34137     }
   34138   }
   34139 
   34140   /* Acquire a RESERVED lock
   34141   */
   34142   if( locktype==RESERVED_LOCK && res ){
   34143     assert( pFile->locktype==SHARED_LOCK );
   34144     res = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34145     if( res ){
   34146       newLocktype = RESERVED_LOCK;
   34147     }else{
   34148       lastErrno = osGetLastError();
   34149     }
   34150   }
   34151 
   34152   /* Acquire a PENDING lock
   34153   */
   34154   if( locktype==EXCLUSIVE_LOCK && res ){
   34155     newLocktype = PENDING_LOCK;
   34156     gotPendingLock = 0;
   34157   }
   34158 
   34159   /* Acquire an EXCLUSIVE lock
   34160   */
   34161   if( locktype==EXCLUSIVE_LOCK && res ){
   34162     assert( pFile->locktype>=SHARED_LOCK );
   34163     res = unlockReadLock(pFile);
   34164     OSTRACE(("unreadlock = %d\n", res));
   34165     res = osLockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34166     if( res ){
   34167       newLocktype = EXCLUSIVE_LOCK;
   34168     }else{
   34169       lastErrno = osGetLastError();
   34170       OSTRACE(("error-code = %d\n", lastErrno));
   34171       getReadLock(pFile);
   34172     }
   34173   }
   34174 
   34175   /* If we are holding a PENDING lock that ought to be released, then
   34176   ** release it now.
   34177   */
   34178   if( gotPendingLock && locktype==SHARED_LOCK ){
   34179     osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   34180   }
   34181 
   34182   /* Update the state of the lock has held in the file descriptor then
   34183   ** return the appropriate result code.
   34184   */
   34185   if( res ){
   34186     rc = SQLITE_OK;
   34187   }else{
   34188     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   34189            locktype, newLocktype));
   34190     pFile->lastErrno = lastErrno;
   34191     rc = SQLITE_BUSY;
   34192   }
   34193   pFile->locktype = (u8)newLocktype;
   34194   return rc;
   34195 }
   34196 
   34197 /*
   34198 ** This routine checks if there is a RESERVED lock held on the specified
   34199 ** file by this or any other process. If such a lock is held, return
   34200 ** non-zero, otherwise zero.
   34201 */
   34202 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   34203   int rc;
   34204   winFile *pFile = (winFile*)id;
   34205 
   34206   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   34207 
   34208   assert( id!=0 );
   34209   if( pFile->locktype>=RESERVED_LOCK ){
   34210     rc = 1;
   34211     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
   34212   }else{
   34213     rc = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34214     if( rc ){
   34215       osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34216     }
   34217     rc = !rc;
   34218     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
   34219   }
   34220   *pResOut = rc;
   34221   return SQLITE_OK;
   34222 }
   34223 
   34224 /*
   34225 ** Lower the locking level on file descriptor id to locktype.  locktype
   34226 ** must be either NO_LOCK or SHARED_LOCK.
   34227 **
   34228 ** If the locking level of the file descriptor is already at or below
   34229 ** the requested locking level, this routine is a no-op.
   34230 **
   34231 ** It is not possible for this routine to fail if the second argument
   34232 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   34233 ** might return SQLITE_IOERR;
   34234 */
   34235 static int winUnlock(sqlite3_file *id, int locktype){
   34236   int type;
   34237   winFile *pFile = (winFile*)id;
   34238   int rc = SQLITE_OK;
   34239   assert( pFile!=0 );
   34240   assert( locktype<=SHARED_LOCK );
   34241   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
   34242           pFile->locktype, pFile->sharedLockByte));
   34243   type = pFile->locktype;
   34244   if( type>=EXCLUSIVE_LOCK ){
   34245     osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34246     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
   34247       /* This should never happen.  We should always be able to
   34248       ** reacquire the read lock */
   34249       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
   34250                "winUnlock", pFile->zPath);
   34251     }
   34252   }
   34253   if( type>=RESERVED_LOCK ){
   34254     osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34255   }
   34256   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   34257     unlockReadLock(pFile);
   34258   }
   34259   if( type>=PENDING_LOCK ){
   34260     osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   34261   }
   34262   pFile->locktype = (u8)locktype;
   34263   return rc;
   34264 }
   34265 
   34266 /*
   34267 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   34268 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   34269 **
   34270 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   34271 */
   34272 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
   34273   if( *pArg<0 ){
   34274     *pArg = (pFile->ctrlFlags & mask)!=0;
   34275   }else if( (*pArg)==0 ){
   34276     pFile->ctrlFlags &= ~mask;
   34277   }else{
   34278     pFile->ctrlFlags |= mask;
   34279   }
   34280 }
   34281 
   34282 /*
   34283 ** Control and query of the open file handle.
   34284 */
   34285 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   34286   winFile *pFile = (winFile*)id;
   34287   switch( op ){
   34288     case SQLITE_FCNTL_LOCKSTATE: {
   34289       *(int*)pArg = pFile->locktype;
   34290       return SQLITE_OK;
   34291     }
   34292     case SQLITE_LAST_ERRNO: {
   34293       *(int*)pArg = (int)pFile->lastErrno;
   34294       return SQLITE_OK;
   34295     }
   34296     case SQLITE_FCNTL_CHUNK_SIZE: {
   34297       pFile->szChunk = *(int *)pArg;
   34298       return SQLITE_OK;
   34299     }
   34300     case SQLITE_FCNTL_SIZE_HINT: {
   34301       if( pFile->szChunk>0 ){
   34302         sqlite3_int64 oldSz;
   34303         int rc = winFileSize(id, &oldSz);
   34304         if( rc==SQLITE_OK ){
   34305           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
   34306           if( newSz>oldSz ){
   34307             SimulateIOErrorBenign(1);
   34308             rc = winTruncate(id, newSz);
   34309             SimulateIOErrorBenign(0);
   34310           }
   34311         }
   34312         return rc;
   34313       }
   34314       return SQLITE_OK;
   34315     }
   34316     case SQLITE_FCNTL_PERSIST_WAL: {
   34317       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
   34318       return SQLITE_OK;
   34319     }
   34320     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   34321       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
   34322       return SQLITE_OK;
   34323     }
   34324     case SQLITE_FCNTL_VFSNAME: {
   34325       *(char**)pArg = sqlite3_mprintf("win32");
   34326       return SQLITE_OK;
   34327     }
   34328     case SQLITE_FCNTL_WIN32_AV_RETRY: {
   34329       int *a = (int*)pArg;
   34330       if( a[0]>0 ){
   34331         win32IoerrRetry = a[0];
   34332       }else{
   34333         a[0] = win32IoerrRetry;
   34334       }
   34335       if( a[1]>0 ){
   34336         win32IoerrRetryDelay = a[1];
   34337       }else{
   34338         a[1] = win32IoerrRetryDelay;
   34339       }
   34340       return SQLITE_OK;
   34341     }
   34342   }
   34343   return SQLITE_NOTFOUND;
   34344 }
   34345 
   34346 /*
   34347 ** Return the sector size in bytes of the underlying block device for
   34348 ** the specified file. This is almost always 512 bytes, but may be
   34349 ** larger for some devices.
   34350 **
   34351 ** SQLite code assumes this function cannot fail. It also assumes that
   34352 ** if two files are created in the same file-system directory (i.e.
   34353 ** a database and its journal file) that the sector size will be the
   34354 ** same for both.
   34355 */
   34356 static int winSectorSize(sqlite3_file *id){
   34357   (void)id;
   34358   return SQLITE_DEFAULT_SECTOR_SIZE;
   34359 }
   34360 
   34361 /*
   34362 ** Return a vector of device characteristics.
   34363 */
   34364 static int winDeviceCharacteristics(sqlite3_file *id){
   34365   winFile *p = (winFile*)id;
   34366   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
   34367          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
   34368 }
   34369 
   34370 #ifndef SQLITE_OMIT_WAL
   34371 
   34372 /*
   34373 ** Windows will only let you create file view mappings
   34374 ** on allocation size granularity boundaries.
   34375 ** During sqlite3_os_init() we do a GetSystemInfo()
   34376 ** to get the granularity size.
   34377 */
   34378 SYSTEM_INFO winSysInfo;
   34379 
   34380 /*
   34381 ** Helper functions to obtain and relinquish the global mutex. The
   34382 ** global mutex is used to protect the winLockInfo objects used by
   34383 ** this file, all of which may be shared by multiple threads.
   34384 **
   34385 ** Function winShmMutexHeld() is used to assert() that the global mutex
   34386 ** is held when required. This function is only used as part of assert()
   34387 ** statements. e.g.
   34388 **
   34389 **   winShmEnterMutex()
   34390 **     assert( winShmMutexHeld() );
   34391 **   winShmLeaveMutex()
   34392 */
   34393 static void winShmEnterMutex(void){
   34394   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34395 }
   34396 static void winShmLeaveMutex(void){
   34397   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34398 }
   34399 #ifdef SQLITE_DEBUG
   34400 static int winShmMutexHeld(void) {
   34401   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34402 }
   34403 #endif
   34404 
   34405 /*
   34406 ** Object used to represent a single file opened and mmapped to provide
   34407 ** shared memory.  When multiple threads all reference the same
   34408 ** log-summary, each thread has its own winFile object, but they all
   34409 ** point to a single instance of this object.  In other words, each
   34410 ** log-summary is opened only once per process.
   34411 **
   34412 ** winShmMutexHeld() must be true when creating or destroying
   34413 ** this object or while reading or writing the following fields:
   34414 **
   34415 **      nRef
   34416 **      pNext
   34417 **
   34418 ** The following fields are read-only after the object is created:
   34419 **
   34420 **      fid
   34421 **      zFilename
   34422 **
   34423 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   34424 ** winShmMutexHeld() is true when reading or writing any other field
   34425 ** in this structure.
   34426 **
   34427 */
   34428 struct winShmNode {
   34429   sqlite3_mutex *mutex;      /* Mutex to access this object */
   34430   char *zFilename;           /* Name of the file */
   34431   winFile hFile;             /* File handle from winOpen */
   34432 
   34433   int szRegion;              /* Size of shared-memory regions */
   34434   int nRegion;               /* Size of array apRegion */
   34435   struct ShmRegion {
   34436     HANDLE hMap;             /* File handle from CreateFileMapping */
   34437     void *pMap;
   34438   } *aRegion;
   34439   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   34440 
   34441   int nRef;                  /* Number of winShm objects pointing to this */
   34442   winShm *pFirst;            /* All winShm objects pointing to this */
   34443   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   34444 #ifdef SQLITE_DEBUG
   34445   u8 nextShmId;              /* Next available winShm.id value */
   34446 #endif
   34447 };
   34448 
   34449 /*
   34450 ** A global array of all winShmNode objects.
   34451 **
   34452 ** The winShmMutexHeld() must be true while reading or writing this list.
   34453 */
   34454 static winShmNode *winShmNodeList = 0;
   34455 
   34456 /*
   34457 ** Structure used internally by this VFS to record the state of an
   34458 ** open shared memory connection.
   34459 **
   34460 ** The following fields are initialized when this object is created and
   34461 ** are read-only thereafter:
   34462 **
   34463 **    winShm.pShmNode
   34464 **    winShm.id
   34465 **
   34466 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   34467 ** while accessing any read/write fields.
   34468 */
   34469 struct winShm {
   34470   winShmNode *pShmNode;      /* The underlying winShmNode object */
   34471   winShm *pNext;             /* Next winShm with the same winShmNode */
   34472   u8 hasMutex;               /* True if holding the winShmNode mutex */
   34473   u16 sharedMask;            /* Mask of shared locks held */
   34474   u16 exclMask;              /* Mask of exclusive locks held */
   34475 #ifdef SQLITE_DEBUG
   34476   u8 id;                     /* Id of this connection with its winShmNode */
   34477 #endif
   34478 };
   34479 
   34480 /*
   34481 ** Constants used for locking
   34482 */
   34483 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   34484 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   34485 
   34486 /*
   34487 ** Apply advisory locks for all n bytes beginning at ofst.
   34488 */
   34489 #define _SHM_UNLCK  1
   34490 #define _SHM_RDLCK  2
   34491 #define _SHM_WRLCK  3
   34492 static int winShmSystemLock(
   34493   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   34494   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
   34495   int ofst,             /* Offset to first byte to be locked/unlocked */
   34496   int nByte             /* Number of bytes to lock or unlock */
   34497 ){
   34498   OVERLAPPED ovlp;
   34499   DWORD dwFlags;
   34500   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   34501 
   34502   /* Access to the winShmNode object is serialized by the caller */
   34503   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
   34504 
   34505   /* Initialize the locking parameters */
   34506   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   34507   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   34508 
   34509   memset(&ovlp, 0, sizeof(OVERLAPPED));
   34510   ovlp.Offset = ofst;
   34511 
   34512   /* Release/Acquire the system-level lock */
   34513   if( lockType==_SHM_UNLCK ){
   34514     rc = osUnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
   34515   }else{
   34516     rc = osLockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
   34517   }
   34518 
   34519   if( rc!= 0 ){
   34520     rc = SQLITE_OK;
   34521   }else{
   34522     pFile->lastErrno =  osGetLastError();
   34523     rc = SQLITE_BUSY;
   34524   }
   34525 
   34526   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
   34527            pFile->hFile.h,
   34528            rc==SQLITE_OK ? "ok" : "failed",
   34529            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
   34530            pFile->lastErrno));
   34531 
   34532   return rc;
   34533 }
   34534 
   34535 /* Forward references to VFS methods */
   34536 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   34537 static int winDelete(sqlite3_vfs *,const char*,int);
   34538 
   34539 /*
   34540 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   34541 **
   34542 ** This is not a VFS shared-memory method; it is a utility function called
   34543 ** by VFS shared-memory methods.
   34544 */
   34545 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   34546   winShmNode **pp;
   34547   winShmNode *p;
   34548   BOOL bRc;
   34549   assert( winShmMutexHeld() );
   34550   pp = &winShmNodeList;
   34551   while( (p = *pp)!=0 ){
   34552     if( p->nRef==0 ){
   34553       int i;
   34554       if( p->mutex ) sqlite3_mutex_free(p->mutex);
   34555       for(i=0; i<p->nRegion; i++){
   34556         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
   34557         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
   34558                  (int)osGetCurrentProcessId(), i,
   34559                  bRc ? "ok" : "failed"));
   34560         bRc = osCloseHandle(p->aRegion[i].hMap);
   34561         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
   34562                  (int)osGetCurrentProcessId(), i,
   34563                  bRc ? "ok" : "failed"));
   34564       }
   34565       if( p->hFile.h != INVALID_HANDLE_VALUE ){
   34566         SimulateIOErrorBenign(1);
   34567         winClose((sqlite3_file *)&p->hFile);
   34568         SimulateIOErrorBenign(0);
   34569       }
   34570       if( deleteFlag ){
   34571         SimulateIOErrorBenign(1);
   34572         sqlite3BeginBenignMalloc();
   34573         winDelete(pVfs, p->zFilename, 0);
   34574         sqlite3EndBenignMalloc();
   34575         SimulateIOErrorBenign(0);
   34576       }
   34577       *pp = p->pNext;
   34578       sqlite3_free(p->aRegion);
   34579       sqlite3_free(p);
   34580     }else{
   34581       pp = &p->pNext;
   34582     }
   34583   }
   34584 }
   34585 
   34586 /*
   34587 ** Open the shared-memory area associated with database file pDbFd.
   34588 **
   34589 ** When opening a new shared-memory file, if no other instances of that
   34590 ** file are currently open, in this process or in other processes, then
   34591 ** the file must be truncated to zero length or have its header cleared.
   34592 */
   34593 static int winOpenSharedMemory(winFile *pDbFd){
   34594   struct winShm *p;                  /* The connection to be opened */
   34595   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
   34596   int rc;                            /* Result code */
   34597   struct winShmNode *pNew;           /* Newly allocated winShmNode */
   34598   int nName;                         /* Size of zName in bytes */
   34599 
   34600   assert( pDbFd->pShm==0 );    /* Not previously opened */
   34601 
   34602   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   34603   ** allocate space for a new winShmNode and filename.
   34604   */
   34605   p = sqlite3_malloc( sizeof(*p) );
   34606   if( p==0 ) return SQLITE_IOERR_NOMEM;
   34607   memset(p, 0, sizeof(*p));
   34608   nName = sqlite3Strlen30(pDbFd->zPath);
   34609   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
   34610   if( pNew==0 ){
   34611     sqlite3_free(p);
   34612     return SQLITE_IOERR_NOMEM;
   34613   }
   34614   memset(pNew, 0, sizeof(*pNew) + nName + 17);
   34615   pNew->zFilename = (char*)&pNew[1];
   34616   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   34617   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
   34618 
   34619   /* Look to see if there is an existing winShmNode that can be used.
   34620   ** If no matching winShmNode currently exists, create a new one.
   34621   */
   34622   winShmEnterMutex();
   34623   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   34624     /* TBD need to come up with better match here.  Perhaps
   34625     ** use FILE_ID_BOTH_DIR_INFO Structure.
   34626     */
   34627     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   34628   }
   34629   if( pShmNode ){
   34630     sqlite3_free(pNew);
   34631   }else{
   34632     pShmNode = pNew;
   34633     pNew = 0;
   34634     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   34635     pShmNode->pNext = winShmNodeList;
   34636     winShmNodeList = pShmNode;
   34637 
   34638     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   34639     if( pShmNode->mutex==0 ){
   34640       rc = SQLITE_IOERR_NOMEM;
   34641       goto shm_open_err;
   34642     }
   34643 
   34644     rc = winOpen(pDbFd->pVfs,
   34645                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
   34646                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
   34647                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
   34648                  0);
   34649     if( SQLITE_OK!=rc ){
   34650       goto shm_open_err;
   34651     }
   34652 
   34653     /* Check to see if another process is holding the dead-man switch.
   34654     ** If not, truncate the file to zero length.
   34655     */
   34656     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
   34657       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
   34658       if( rc!=SQLITE_OK ){
   34659         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
   34660                  "winOpenShm", pDbFd->zPath);
   34661       }
   34662     }
   34663     if( rc==SQLITE_OK ){
   34664       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   34665       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
   34666     }
   34667     if( rc ) goto shm_open_err;
   34668   }
   34669 
   34670   /* Make the new connection a child of the winShmNode */
   34671   p->pShmNode = pShmNode;
   34672 #ifdef SQLITE_DEBUG
   34673   p->id = pShmNode->nextShmId++;
   34674 #endif
   34675   pShmNode->nRef++;
   34676   pDbFd->pShm = p;
   34677   winShmLeaveMutex();
   34678 
   34679   /* The reference count on pShmNode has already been incremented under
   34680   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   34681   ** new (struct winShm) object to the pShmNode has been set. All that is
   34682   ** left to do is to link the new object into the linked list starting
   34683   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   34684   ** mutex.
   34685   */
   34686   sqlite3_mutex_enter(pShmNode->mutex);
   34687   p->pNext = pShmNode->pFirst;
   34688   pShmNode->pFirst = p;
   34689   sqlite3_mutex_leave(pShmNode->mutex);
   34690   return SQLITE_OK;
   34691 
   34692   /* Jump here on any error */
   34693 shm_open_err:
   34694   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   34695   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   34696   sqlite3_free(p);
   34697   sqlite3_free(pNew);
   34698   winShmLeaveMutex();
   34699   return rc;
   34700 }
   34701 
   34702 /*
   34703 ** Close a connection to shared-memory.  Delete the underlying
   34704 ** storage if deleteFlag is true.
   34705 */
   34706 static int winShmUnmap(
   34707   sqlite3_file *fd,          /* Database holding shared memory */
   34708   int deleteFlag             /* Delete after closing if true */
   34709 ){
   34710   winFile *pDbFd;       /* Database holding shared-memory */
   34711   winShm *p;            /* The connection to be closed */
   34712   winShmNode *pShmNode; /* The underlying shared-memory file */
   34713   winShm **pp;          /* For looping over sibling connections */
   34714 
   34715   pDbFd = (winFile*)fd;
   34716   p = pDbFd->pShm;
   34717   if( p==0 ) return SQLITE_OK;
   34718   pShmNode = p->pShmNode;
   34719 
   34720   /* Remove connection p from the set of connections associated
   34721   ** with pShmNode */
   34722   sqlite3_mutex_enter(pShmNode->mutex);
   34723   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   34724   *pp = p->pNext;
   34725 
   34726   /* Free the connection p */
   34727   sqlite3_free(p);
   34728   pDbFd->pShm = 0;
   34729   sqlite3_mutex_leave(pShmNode->mutex);
   34730 
   34731   /* If pShmNode->nRef has reached 0, then close the underlying
   34732   ** shared-memory file, too */
   34733   winShmEnterMutex();
   34734   assert( pShmNode->nRef>0 );
   34735   pShmNode->nRef--;
   34736   if( pShmNode->nRef==0 ){
   34737     winShmPurge(pDbFd->pVfs, deleteFlag);
   34738   }
   34739   winShmLeaveMutex();
   34740 
   34741   return SQLITE_OK;
   34742 }
   34743 
   34744 /*
   34745 ** Change the lock state for a shared-memory segment.
   34746 */
   34747 static int winShmLock(
   34748   sqlite3_file *fd,          /* Database file holding the shared memory */
   34749   int ofst,                  /* First lock to acquire or release */
   34750   int n,                     /* Number of locks to acquire or release */
   34751   int flags                  /* What to do with the lock */
   34752 ){
   34753   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   34754   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   34755   winShm *pX;                           /* For looping over all siblings */
   34756   winShmNode *pShmNode = p->pShmNode;
   34757   int rc = SQLITE_OK;                   /* Result code */
   34758   u16 mask;                             /* Mask of locks to take or release */
   34759 
   34760   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   34761   assert( n>=1 );
   34762   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   34763        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   34764        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   34765        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   34766   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   34767 
   34768   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   34769   assert( n>1 || mask==(1<<ofst) );
   34770   sqlite3_mutex_enter(pShmNode->mutex);
   34771   if( flags & SQLITE_SHM_UNLOCK ){
   34772     u16 allMask = 0; /* Mask of locks held by siblings */
   34773 
   34774     /* See if any siblings hold this same lock */
   34775     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34776       if( pX==p ) continue;
   34777       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   34778       allMask |= pX->sharedMask;
   34779     }
   34780 
   34781     /* Unlock the system-level locks */
   34782     if( (mask & allMask)==0 ){
   34783       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
   34784     }else{
   34785       rc = SQLITE_OK;
   34786     }
   34787 
   34788     /* Undo the local locks */
   34789     if( rc==SQLITE_OK ){
   34790       p->exclMask &= ~mask;
   34791       p->sharedMask &= ~mask;
   34792     }
   34793   }else if( flags & SQLITE_SHM_SHARED ){
   34794     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   34795 
   34796     /* Find out which shared locks are already held by sibling connections.
   34797     ** If any sibling already holds an exclusive lock, go ahead and return
   34798     ** SQLITE_BUSY.
   34799     */
   34800     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34801       if( (pX->exclMask & mask)!=0 ){
   34802         rc = SQLITE_BUSY;
   34803         break;
   34804       }
   34805       allShared |= pX->sharedMask;
   34806     }
   34807 
   34808     /* Get shared locks at the system level, if necessary */
   34809     if( rc==SQLITE_OK ){
   34810       if( (allShared & mask)==0 ){
   34811         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
   34812       }else{
   34813         rc = SQLITE_OK;
   34814       }
   34815     }
   34816 
   34817     /* Get the local shared locks */
   34818     if( rc==SQLITE_OK ){
   34819       p->sharedMask |= mask;
   34820     }
   34821   }else{
   34822     /* Make sure no sibling connections hold locks that will block this
   34823     ** lock.  If any do, return SQLITE_BUSY right away.
   34824     */
   34825     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34826       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   34827         rc = SQLITE_BUSY;
   34828         break;
   34829       }
   34830     }
   34831 
   34832     /* Get the exclusive locks at the system level.  Then if successful
   34833     ** also mark the local connection as being locked.
   34834     */
   34835     if( rc==SQLITE_OK ){
   34836       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
   34837       if( rc==SQLITE_OK ){
   34838         assert( (p->sharedMask & mask)==0 );
   34839         p->exclMask |= mask;
   34840       }
   34841     }
   34842   }
   34843   sqlite3_mutex_leave(pShmNode->mutex);
   34844   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
   34845            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
   34846            rc ? "failed" : "ok"));
   34847   return rc;
   34848 }
   34849 
   34850 /*
   34851 ** Implement a memory barrier or memory fence on shared memory.
   34852 **
   34853 ** All loads and stores begun before the barrier must complete before
   34854 ** any load or store begun after the barrier.
   34855 */
   34856 static void winShmBarrier(
   34857   sqlite3_file *fd          /* Database holding the shared memory */
   34858 ){
   34859   UNUSED_PARAMETER(fd);
   34860   /* MemoryBarrier(); // does not work -- do not know why not */
   34861   winShmEnterMutex();
   34862   winShmLeaveMutex();
   34863 }
   34864 
   34865 /*
   34866 ** This function is called to obtain a pointer to region iRegion of the
   34867 ** shared-memory associated with the database file fd. Shared-memory regions
   34868 ** are numbered starting from zero. Each shared-memory region is szRegion
   34869 ** bytes in size.
   34870 **
   34871 ** If an error occurs, an error code is returned and *pp is set to NULL.
   34872 **
   34873 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   34874 ** region has not been allocated (by any client, including one running in a
   34875 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   34876 ** isWrite is non-zero and the requested shared-memory region has not yet
   34877 ** been allocated, it is allocated by this function.
   34878 **
   34879 ** If the shared-memory region has already been allocated or is allocated by
   34880 ** this call as described above, then it is mapped into this processes
   34881 ** address space (if it is not already), *pp is set to point to the mapped
   34882 ** memory and SQLITE_OK returned.
   34883 */
   34884 static int winShmMap(
   34885   sqlite3_file *fd,               /* Handle open on database file */
   34886   int iRegion,                    /* Region to retrieve */
   34887   int szRegion,                   /* Size of regions */
   34888   int isWrite,                    /* True to extend file if necessary */
   34889   void volatile **pp              /* OUT: Mapped memory */
   34890 ){
   34891   winFile *pDbFd = (winFile*)fd;
   34892   winShm *p = pDbFd->pShm;
   34893   winShmNode *pShmNode;
   34894   int rc = SQLITE_OK;
   34895 
   34896   if( !p ){
   34897     rc = winOpenSharedMemory(pDbFd);
   34898     if( rc!=SQLITE_OK ) return rc;
   34899     p = pDbFd->pShm;
   34900   }
   34901   pShmNode = p->pShmNode;
   34902 
   34903   sqlite3_mutex_enter(pShmNode->mutex);
   34904   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   34905 
   34906   if( pShmNode->nRegion<=iRegion ){
   34907     struct ShmRegion *apNew;           /* New aRegion[] array */
   34908     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   34909     sqlite3_int64 sz;                  /* Current size of wal-index file */
   34910 
   34911     pShmNode->szRegion = szRegion;
   34912 
   34913     /* The requested region is not mapped into this processes address space.
   34914     ** Check to see if it has been allocated (i.e. if the wal-index file is
   34915     ** large enough to contain the requested region).
   34916     */
   34917     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   34918     if( rc!=SQLITE_OK ){
   34919       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   34920                "winShmMap1", pDbFd->zPath);
   34921       goto shmpage_out;
   34922     }
   34923 
   34924     if( sz<nByte ){
   34925       /* The requested memory region does not exist. If isWrite is set to
   34926       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   34927       **
   34928       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   34929       ** the requested memory region.
   34930       */
   34931       if( !isWrite ) goto shmpage_out;
   34932       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   34933       if( rc!=SQLITE_OK ){
   34934         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   34935                  "winShmMap2", pDbFd->zPath);
   34936         goto shmpage_out;
   34937       }
   34938     }
   34939 
   34940     /* Map the requested memory region into this processes address space. */
   34941     apNew = (struct ShmRegion *)sqlite3_realloc(
   34942         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   34943     );
   34944     if( !apNew ){
   34945       rc = SQLITE_IOERR_NOMEM;
   34946       goto shmpage_out;
   34947     }
   34948     pShmNode->aRegion = apNew;
   34949 
   34950     while( pShmNode->nRegion<=iRegion ){
   34951       HANDLE hMap;                /* file-mapping handle */
   34952       void *pMap = 0;             /* Mapped memory region */
   34953 
   34954       hMap = osCreateFileMapping(pShmNode->hFile.h,
   34955           NULL, PAGE_READWRITE, 0, nByte, NULL
   34956       );
   34957       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
   34958                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
   34959                hMap ? "ok" : "failed"));
   34960       if( hMap ){
   34961         int iOffset = pShmNode->nRegion*szRegion;
   34962         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   34963         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   34964             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   34965         );
   34966         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
   34967                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
   34968                  szRegion, pMap ? "ok" : "failed"));
   34969       }
   34970       if( !pMap ){
   34971         pShmNode->lastErrno = osGetLastError();
   34972         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
   34973                  "winShmMap3", pDbFd->zPath);
   34974         if( hMap ) osCloseHandle(hMap);
   34975         goto shmpage_out;
   34976       }
   34977 
   34978       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   34979       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   34980       pShmNode->nRegion++;
   34981     }
   34982   }
   34983 
   34984 shmpage_out:
   34985   if( pShmNode->nRegion>iRegion ){
   34986     int iOffset = iRegion*szRegion;
   34987     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   34988     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   34989     *pp = (void *)&p[iOffsetShift];
   34990   }else{
   34991     *pp = 0;
   34992   }
   34993   sqlite3_mutex_leave(pShmNode->mutex);
   34994   return rc;
   34995 }
   34996 
   34997 #else
   34998 # define winShmMap     0
   34999 # define winShmLock    0
   35000 # define winShmBarrier 0
   35001 # define winShmUnmap   0
   35002 #endif /* #ifndef SQLITE_OMIT_WAL */
   35003 
   35004 /*
   35005 ** Here ends the implementation of all sqlite3_file methods.
   35006 **
   35007 ********************** End sqlite3_file Methods *******************************
   35008 ******************************************************************************/
   35009 
   35010 /*
   35011 ** This vector defines all the methods that can operate on an
   35012 ** sqlite3_file for win32.
   35013 */
   35014 static const sqlite3_io_methods winIoMethod = {
   35015   2,                              /* iVersion */
   35016   winClose,                       /* xClose */
   35017   winRead,                        /* xRead */
   35018   winWrite,                       /* xWrite */
   35019   winTruncate,                    /* xTruncate */
   35020   winSync,                        /* xSync */
   35021   winFileSize,                    /* xFileSize */
   35022   winLock,                        /* xLock */
   35023   winUnlock,                      /* xUnlock */
   35024   winCheckReservedLock,           /* xCheckReservedLock */
   35025   winFileControl,                 /* xFileControl */
   35026   winSectorSize,                  /* xSectorSize */
   35027   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   35028   winShmMap,                      /* xShmMap */
   35029   winShmLock,                     /* xShmLock */
   35030   winShmBarrier,                  /* xShmBarrier */
   35031   winShmUnmap                     /* xShmUnmap */
   35032 };
   35033 
   35034 /****************************************************************************
   35035 **************************** sqlite3_vfs methods ****************************
   35036 **
   35037 ** This division contains the implementation of methods on the
   35038 ** sqlite3_vfs object.
   35039 */
   35040 
   35041 /*
   35042 ** Convert a UTF-8 filename into whatever form the underlying
   35043 ** operating system wants filenames in.  Space to hold the result
   35044 ** is obtained from malloc and must be freed by the calling
   35045 ** function.
   35046 */
   35047 static void *convertUtf8Filename(const char *zFilename){
   35048   void *zConverted = 0;
   35049   if( isNT() ){
   35050     zConverted = utf8ToUnicode(zFilename);
   35051 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35052 */
   35053 #if SQLITE_OS_WINCE==0
   35054   }else{
   35055     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
   35056 #endif
   35057   }
   35058   /* caller will handle out of memory */
   35059   return zConverted;
   35060 }
   35061 
   35062 /*
   35063 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   35064 ** hold at pVfs->mxPathname characters.
   35065 */
   35066 static int getTempname(int nBuf, char *zBuf){
   35067   static char zChars[] =
   35068     "abcdefghijklmnopqrstuvwxyz"
   35069     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   35070     "0123456789";
   35071   size_t i, j;
   35072   char zTempPath[MAX_PATH+2];
   35073 
   35074   /* It's odd to simulate an io-error here, but really this is just
   35075   ** using the io-error infrastructure to test that SQLite handles this
   35076   ** function failing.
   35077   */
   35078   SimulateIOError( return SQLITE_IOERR );
   35079 
   35080   if( sqlite3_temp_directory ){
   35081     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
   35082   }else if( isNT() ){
   35083     char *zMulti;
   35084     WCHAR zWidePath[MAX_PATH];
   35085     osGetTempPathW(MAX_PATH-30, zWidePath);
   35086     zMulti = unicodeToUtf8(zWidePath);
   35087     if( zMulti ){
   35088       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
   35089       sqlite3_free(zMulti);
   35090     }else{
   35091       return SQLITE_IOERR_NOMEM;
   35092     }
   35093 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35094 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35095 ** it's important to not reference them for WINCE builds.
   35096 */
   35097 #if SQLITE_OS_WINCE==0
   35098   }else{
   35099     char *zUtf8;
   35100     char zMbcsPath[MAX_PATH];
   35101     osGetTempPathA(MAX_PATH-30, zMbcsPath);
   35102     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   35103     if( zUtf8 ){
   35104       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
   35105       sqlite3_free(zUtf8);
   35106     }else{
   35107       return SQLITE_IOERR_NOMEM;
   35108     }
   35109 #endif
   35110   }
   35111 
   35112   /* Check that the output buffer is large enough for the temporary file
   35113   ** name. If it is not, return SQLITE_ERROR.
   35114   */
   35115   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
   35116     return SQLITE_ERROR;
   35117   }
   35118 
   35119   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
   35120   zTempPath[i] = 0;
   35121 
   35122   sqlite3_snprintf(nBuf-18, zBuf,
   35123                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
   35124   j = sqlite3Strlen30(zBuf);
   35125   sqlite3_randomness(15, &zBuf[j]);
   35126   for(i=0; i<15; i++, j++){
   35127     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   35128   }
   35129   zBuf[j] = 0;
   35130   zBuf[j+1] = 0;
   35131 
   35132   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
   35133   return SQLITE_OK;
   35134 }
   35135 
   35136 /*
   35137 ** Open a file.
   35138 */
   35139 static int winOpen(
   35140   sqlite3_vfs *pVfs,        /* Not used */
   35141   const char *zName,        /* Name of the file (UTF-8) */
   35142   sqlite3_file *id,         /* Write the SQLite file handle here */
   35143   int flags,                /* Open mode flags */
   35144   int *pOutFlags            /* Status return flags */
   35145 ){
   35146   HANDLE h;
   35147   DWORD lastErrno;
   35148   DWORD dwDesiredAccess;
   35149   DWORD dwShareMode;
   35150   DWORD dwCreationDisposition;
   35151   DWORD dwFlagsAndAttributes = 0;
   35152 #if SQLITE_OS_WINCE
   35153   int isTemp = 0;
   35154 #endif
   35155   winFile *pFile = (winFile*)id;
   35156   void *zConverted;              /* Filename in OS encoding */
   35157   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   35158   int cnt = 0;
   35159 
   35160   /* If argument zPath is a NULL pointer, this function is required to open
   35161   ** a temporary file. Use this buffer to store the file name in.
   35162   */
   35163   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
   35164 
   35165   int rc = SQLITE_OK;            /* Function Return Code */
   35166 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   35167   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   35168 #endif
   35169 
   35170   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   35171   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   35172   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   35173 #ifndef NDEBUG
   35174   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   35175 #endif
   35176   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   35177 
   35178 #ifndef NDEBUG
   35179   int isOpenJournal = (isCreate && (
   35180         eType==SQLITE_OPEN_MASTER_JOURNAL
   35181      || eType==SQLITE_OPEN_MAIN_JOURNAL
   35182      || eType==SQLITE_OPEN_WAL
   35183   ));
   35184 #endif
   35185 
   35186   /* Check the following statements are true:
   35187   **
   35188   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   35189   **   (b) if CREATE is set, then READWRITE must also be set, and
   35190   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   35191   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   35192   */
   35193   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   35194   assert(isCreate==0 || isReadWrite);
   35195   assert(isExclusive==0 || isCreate);
   35196   assert(isDelete==0 || isCreate);
   35197 
   35198   /* The main DB, main journal, WAL file and master journal are never
   35199   ** automatically deleted. Nor are they ever temporary files.  */
   35200   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   35201   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   35202   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   35203   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   35204 
   35205   /* Assert that the upper layer has set one of the "file-type" flags. */
   35206   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   35207        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   35208        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   35209        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   35210   );
   35211 
   35212   assert( id!=0 );
   35213   UNUSED_PARAMETER(pVfs);
   35214 
   35215   pFile->h = INVALID_HANDLE_VALUE;
   35216 
   35217   /* If the second argument to this function is NULL, generate a
   35218   ** temporary file name to use
   35219   */
   35220   if( !zUtf8Name ){
   35221     assert(isDelete && !isOpenJournal);
   35222     rc = getTempname(MAX_PATH+2, zTmpname);
   35223     if( rc!=SQLITE_OK ){
   35224       return rc;
   35225     }
   35226     zUtf8Name = zTmpname;
   35227   }
   35228 
   35229   /* Database filenames are double-zero terminated if they are not
   35230   ** URIs with parameters.  Hence, they can always be passed into
   35231   ** sqlite3_uri_parameter().
   35232   */
   35233   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
   35234         zUtf8Name[strlen(zUtf8Name)+1]==0 );
   35235 
   35236   /* Convert the filename to the system encoding. */
   35237   zConverted = convertUtf8Filename(zUtf8Name);
   35238   if( zConverted==0 ){
   35239     return SQLITE_IOERR_NOMEM;
   35240   }
   35241 
   35242   if( isReadWrite ){
   35243     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   35244   }else{
   35245     dwDesiredAccess = GENERIC_READ;
   35246   }
   35247 
   35248   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   35249   ** created. SQLite doesn't use it to indicate "exclusive access"
   35250   ** as it is usually understood.
   35251   */
   35252   if( isExclusive ){
   35253     /* Creates a new file, only if it does not already exist. */
   35254     /* If the file exists, it fails. */
   35255     dwCreationDisposition = CREATE_NEW;
   35256   }else if( isCreate ){
   35257     /* Open existing file, or create if it doesn't exist */
   35258     dwCreationDisposition = OPEN_ALWAYS;
   35259   }else{
   35260     /* Opens a file, only if it exists. */
   35261     dwCreationDisposition = OPEN_EXISTING;
   35262   }
   35263 
   35264   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   35265 
   35266   if( isDelete ){
   35267 #if SQLITE_OS_WINCE
   35268     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   35269     isTemp = 1;
   35270 #else
   35271     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   35272                                | FILE_ATTRIBUTE_HIDDEN
   35273                                | FILE_FLAG_DELETE_ON_CLOSE;
   35274 #endif
   35275   }else{
   35276     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   35277   }
   35278   /* Reports from the internet are that performance is always
   35279   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   35280 #if SQLITE_OS_WINCE
   35281   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   35282 #endif
   35283 
   35284   if( isNT() ){
   35285     while( (h = osCreateFileW((LPCWSTR)zConverted,
   35286                               dwDesiredAccess,
   35287                               dwShareMode, NULL,
   35288                               dwCreationDisposition,
   35289                               dwFlagsAndAttributes,
   35290                               NULL))==INVALID_HANDLE_VALUE &&
   35291                               retryIoerr(&cnt, &lastErrno) ){}
   35292 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35293 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35294 ** it's important to not reference them for WINCE builds.
   35295 */
   35296 #if SQLITE_OS_WINCE==0
   35297   }else{
   35298     while( (h = osCreateFileA((LPCSTR)zConverted,
   35299                               dwDesiredAccess,
   35300                               dwShareMode, NULL,
   35301                               dwCreationDisposition,
   35302                               dwFlagsAndAttributes,
   35303                               NULL))==INVALID_HANDLE_VALUE &&
   35304                               retryIoerr(&cnt, &lastErrno) ){}
   35305 #endif
   35306   }
   35307 
   35308   logIoerr(cnt);
   35309 
   35310   OSTRACE(("OPEN %d %s 0x%lx %s\n",
   35311            h, zName, dwDesiredAccess,
   35312            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
   35313 
   35314   if( h==INVALID_HANDLE_VALUE ){
   35315     pFile->lastErrno = lastErrno;
   35316     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
   35317     sqlite3_free(zConverted);
   35318     if( isReadWrite && !isExclusive ){
   35319       return winOpen(pVfs, zName, id,
   35320              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
   35321     }else{
   35322       return SQLITE_CANTOPEN_BKPT;
   35323     }
   35324   }
   35325 
   35326   if( pOutFlags ){
   35327     if( isReadWrite ){
   35328       *pOutFlags = SQLITE_OPEN_READWRITE;
   35329     }else{
   35330       *pOutFlags = SQLITE_OPEN_READONLY;
   35331     }
   35332   }
   35333 
   35334   memset(pFile, 0, sizeof(*pFile));
   35335   pFile->pMethod = &winIoMethod;
   35336   pFile->h = h;
   35337   pFile->lastErrno = NO_ERROR;
   35338   pFile->pVfs = pVfs;
   35339   pFile->pShm = 0;
   35340   pFile->zPath = zName;
   35341   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   35342     pFile->ctrlFlags |= WINFILE_PSOW;
   35343   }
   35344 
   35345 #if SQLITE_OS_WINCE
   35346   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   35347        && !winceCreateLock(zName, pFile)
   35348   ){
   35349     osCloseHandle(h);
   35350     sqlite3_free(zConverted);
   35351     return SQLITE_CANTOPEN_BKPT;
   35352   }
   35353   if( isTemp ){
   35354     pFile->zDeleteOnClose = zConverted;
   35355   }else
   35356 #endif
   35357   {
   35358     sqlite3_free(zConverted);
   35359   }
   35360 
   35361   OpenCounter(+1);
   35362   return rc;
   35363 }
   35364 
   35365 /*
   35366 ** Delete the named file.
   35367 **
   35368 ** Note that Windows does not allow a file to be deleted if some other
   35369 ** process has it open.  Sometimes a virus scanner or indexing program
   35370 ** will open a journal file shortly after it is created in order to do
   35371 ** whatever it does.  While this other process is holding the
   35372 ** file open, we will be unable to delete it.  To work around this
   35373 ** problem, we delay 100 milliseconds and try to delete again.  Up
   35374 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   35375 ** up and returning an error.
   35376 */
   35377 static int winDelete(
   35378   sqlite3_vfs *pVfs,          /* Not used on win32 */
   35379   const char *zFilename,      /* Name of file to delete */
   35380   int syncDir                 /* Not used on win32 */
   35381 ){
   35382   int cnt = 0;
   35383   int rc;
   35384   DWORD lastErrno;
   35385   void *zConverted;
   35386   UNUSED_PARAMETER(pVfs);
   35387   UNUSED_PARAMETER(syncDir);
   35388 
   35389   SimulateIOError(return SQLITE_IOERR_DELETE);
   35390   zConverted = convertUtf8Filename(zFilename);
   35391   if( zConverted==0 ){
   35392     return SQLITE_IOERR_NOMEM;
   35393   }
   35394   if( isNT() ){
   35395     rc = 1;
   35396     while( osGetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
   35397          (rc = osDeleteFileW(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
   35398     rc = rc ? SQLITE_OK : SQLITE_ERROR;
   35399 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35400 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35401 ** it's important to not reference them for WINCE builds.
   35402 */
   35403 #if SQLITE_OS_WINCE==0
   35404   }else{
   35405     rc = 1;
   35406     while( osGetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
   35407          (rc = osDeleteFileA(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
   35408     rc = rc ? SQLITE_OK : SQLITE_ERROR;
   35409 #endif
   35410   }
   35411   if( rc ){
   35412     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
   35413              "winDelete", zFilename);
   35414   }else{
   35415     logIoerr(cnt);
   35416   }
   35417   sqlite3_free(zConverted);
   35418   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
   35419   return rc;
   35420 }
   35421 
   35422 /*
   35423 ** Check the existance and status of a file.
   35424 */
   35425 static int winAccess(
   35426   sqlite3_vfs *pVfs,         /* Not used on win32 */
   35427   const char *zFilename,     /* Name of file to check */
   35428   int flags,                 /* Type of test to make on this file */
   35429   int *pResOut               /* OUT: Result */
   35430 ){
   35431   DWORD attr;
   35432   int rc = 0;
   35433   DWORD lastErrno;
   35434   void *zConverted;
   35435   UNUSED_PARAMETER(pVfs);
   35436 
   35437   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   35438   zConverted = convertUtf8Filename(zFilename);
   35439   if( zConverted==0 ){
   35440     return SQLITE_IOERR_NOMEM;
   35441   }
   35442   if( isNT() ){
   35443     int cnt = 0;
   35444     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   35445     memset(&sAttrData, 0, sizeof(sAttrData));
   35446     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   35447                              GetFileExInfoStandard,
   35448                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
   35449     if( rc ){
   35450       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   35451       ** as if it does not exist.
   35452       */
   35453       if(    flags==SQLITE_ACCESS_EXISTS
   35454           && sAttrData.nFileSizeHigh==0
   35455           && sAttrData.nFileSizeLow==0 ){
   35456         attr = INVALID_FILE_ATTRIBUTES;
   35457       }else{
   35458         attr = sAttrData.dwFileAttributes;
   35459       }
   35460     }else{
   35461       logIoerr(cnt);
   35462       if( lastErrno!=ERROR_FILE_NOT_FOUND ){
   35463         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
   35464         sqlite3_free(zConverted);
   35465         return SQLITE_IOERR_ACCESS;
   35466       }else{
   35467         attr = INVALID_FILE_ATTRIBUTES;
   35468       }
   35469     }
   35470 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35471 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35472 ** it's important to not reference them for WINCE builds.
   35473 */
   35474 #if SQLITE_OS_WINCE==0
   35475   }else{
   35476     attr = osGetFileAttributesA((char*)zConverted);
   35477 #endif
   35478   }
   35479   sqlite3_free(zConverted);
   35480   switch( flags ){
   35481     case SQLITE_ACCESS_READ:
   35482     case SQLITE_ACCESS_EXISTS:
   35483       rc = attr!=INVALID_FILE_ATTRIBUTES;
   35484       break;
   35485     case SQLITE_ACCESS_READWRITE:
   35486       rc = attr!=INVALID_FILE_ATTRIBUTES &&
   35487              (attr & FILE_ATTRIBUTE_READONLY)==0;
   35488       break;
   35489     default:
   35490       assert(!"Invalid flags argument");
   35491   }
   35492   *pResOut = rc;
   35493   return SQLITE_OK;
   35494 }
   35495 
   35496 
   35497 /*
   35498 ** Turn a relative pathname into a full pathname.  Write the full
   35499 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   35500 ** bytes in size.
   35501 */
   35502 static int winFullPathname(
   35503   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   35504   const char *zRelative,        /* Possibly relative input path */
   35505   int nFull,                    /* Size of output buffer in bytes */
   35506   char *zFull                   /* Output buffer */
   35507 ){
   35508 
   35509 #if defined(__CYGWIN__)
   35510   SimulateIOError( return SQLITE_ERROR );
   35511   UNUSED_PARAMETER(nFull);
   35512   cygwin_conv_to_full_win32_path(zRelative, zFull);
   35513   return SQLITE_OK;
   35514 #endif
   35515 
   35516 #if SQLITE_OS_WINCE
   35517   SimulateIOError( return SQLITE_ERROR );
   35518   UNUSED_PARAMETER(nFull);
   35519   /* WinCE has no concept of a relative pathname, or so I am told. */
   35520   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
   35521   return SQLITE_OK;
   35522 #endif
   35523 
   35524 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
   35525   int nByte;
   35526   void *zConverted;
   35527   char *zOut;
   35528 
   35529   /* If this path name begins with "/X:", where "X" is any alphabetic
   35530   ** character, discard the initial "/" from the pathname.
   35531   */
   35532   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
   35533     zRelative++;
   35534   }
   35535 
   35536   /* It's odd to simulate an io-error here, but really this is just
   35537   ** using the io-error infrastructure to test that SQLite handles this
   35538   ** function failing. This function could fail if, for example, the
   35539   ** current working directory has been unlinked.
   35540   */
   35541   SimulateIOError( return SQLITE_ERROR );
   35542   UNUSED_PARAMETER(nFull);
   35543   zConverted = convertUtf8Filename(zRelative);
   35544   if( zConverted==0 ){
   35545     return SQLITE_IOERR_NOMEM;
   35546   }
   35547   if( isNT() ){
   35548     LPWSTR zTemp;
   35549     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
   35550     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
   35551     if( zTemp==0 ){
   35552       sqlite3_free(zConverted);
   35553       return SQLITE_IOERR_NOMEM;
   35554     }
   35555     osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
   35556     sqlite3_free(zConverted);
   35557     zOut = unicodeToUtf8(zTemp);
   35558     sqlite3_free(zTemp);
   35559 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35560 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35561 ** it's important to not reference them for WINCE builds.
   35562 */
   35563 #if SQLITE_OS_WINCE==0
   35564   }else{
   35565     char *zTemp;
   35566     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
   35567     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
   35568     if( zTemp==0 ){
   35569       sqlite3_free(zConverted);
   35570       return SQLITE_IOERR_NOMEM;
   35571     }
   35572     osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   35573     sqlite3_free(zConverted);
   35574     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   35575     sqlite3_free(zTemp);
   35576 #endif
   35577   }
   35578   if( zOut ){
   35579     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
   35580     sqlite3_free(zOut);
   35581     return SQLITE_OK;
   35582   }else{
   35583     return SQLITE_IOERR_NOMEM;
   35584   }
   35585 #endif
   35586 }
   35587 
   35588 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   35589 /*
   35590 ** Interfaces for opening a shared library, finding entry points
   35591 ** within the shared library, and closing the shared library.
   35592 */
   35593 /*
   35594 ** Interfaces for opening a shared library, finding entry points
   35595 ** within the shared library, and closing the shared library.
   35596 */
   35597 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   35598   HANDLE h;
   35599   void *zConverted = convertUtf8Filename(zFilename);
   35600   UNUSED_PARAMETER(pVfs);
   35601   if( zConverted==0 ){
   35602     return 0;
   35603   }
   35604   if( isNT() ){
   35605     h = osLoadLibraryW((LPCWSTR)zConverted);
   35606 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35607 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35608 ** it's important to not reference them for WINCE builds.
   35609 */
   35610 #if SQLITE_OS_WINCE==0
   35611   }else{
   35612     h = osLoadLibraryA((char*)zConverted);
   35613 #endif
   35614   }
   35615   sqlite3_free(zConverted);
   35616   return (void*)h;
   35617 }
   35618 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   35619   UNUSED_PARAMETER(pVfs);
   35620   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
   35621 }
   35622 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
   35623   UNUSED_PARAMETER(pVfs);
   35624   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
   35625 }
   35626 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   35627   UNUSED_PARAMETER(pVfs);
   35628   osFreeLibrary((HANDLE)pHandle);
   35629 }
   35630 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   35631   #define winDlOpen  0
   35632   #define winDlError 0
   35633   #define winDlSym   0
   35634   #define winDlClose 0
   35635 #endif
   35636 
   35637 
   35638 /*
   35639 ** Write up to nBuf bytes of randomness into zBuf.
   35640 */
   35641 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35642   int n = 0;
   35643   UNUSED_PARAMETER(pVfs);
   35644 #if defined(SQLITE_TEST)
   35645   n = nBuf;
   35646   memset(zBuf, 0, nBuf);
   35647 #else
   35648   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   35649     SYSTEMTIME x;
   35650     osGetSystemTime(&x);
   35651     memcpy(&zBuf[n], &x, sizeof(x));
   35652     n += sizeof(x);
   35653   }
   35654   if( sizeof(DWORD)<=nBuf-n ){
   35655     DWORD pid = osGetCurrentProcessId();
   35656     memcpy(&zBuf[n], &pid, sizeof(pid));
   35657     n += sizeof(pid);
   35658   }
   35659   if( sizeof(DWORD)<=nBuf-n ){
   35660     DWORD cnt = osGetTickCount();
   35661     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   35662     n += sizeof(cnt);
   35663   }
   35664   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   35665     LARGE_INTEGER i;
   35666     osQueryPerformanceCounter(&i);
   35667     memcpy(&zBuf[n], &i, sizeof(i));
   35668     n += sizeof(i);
   35669   }
   35670 #endif
   35671   return n;
   35672 }
   35673 
   35674 
   35675 /*
   35676 ** Sleep for a little while.  Return the amount of time slept.
   35677 */
   35678 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   35679   osSleep((microsec+999)/1000);
   35680   UNUSED_PARAMETER(pVfs);
   35681   return ((microsec+999)/1000)*1000;
   35682 }
   35683 
   35684 /*
   35685 ** The following variable, if set to a non-zero value, is interpreted as
   35686 ** the number of seconds since 1970 and is used to set the result of
   35687 ** sqlite3OsCurrentTime() during testing.
   35688 */
   35689 #ifdef SQLITE_TEST
   35690 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   35691 #endif
   35692 
   35693 /*
   35694 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   35695 ** the current time and date as a Julian Day number times 86_400_000.  In
   35696 ** other words, write into *piNow the number of milliseconds since the Julian
   35697 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   35698 ** proleptic Gregorian calendar.
   35699 **
   35700 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   35701 ** cannot be found.
   35702 */
   35703 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   35704   /* FILETIME structure is a 64-bit value representing the number of
   35705      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   35706   */
   35707   FILETIME ft;
   35708   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   35709 #ifdef SQLITE_TEST
   35710   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   35711 #endif
   35712   /* 2^32 - to avoid use of LL and warnings in gcc */
   35713   static const sqlite3_int64 max32BitValue =
   35714       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
   35715 
   35716 #if SQLITE_OS_WINCE
   35717   SYSTEMTIME time;
   35718   osGetSystemTime(&time);
   35719   /* if SystemTimeToFileTime() fails, it returns zero. */
   35720   if (!osSystemTimeToFileTime(&time,&ft)){
   35721     return SQLITE_ERROR;
   35722   }
   35723 #else
   35724   osGetSystemTimeAsFileTime( &ft );
   35725 #endif
   35726 
   35727   *piNow = winFiletimeEpoch +
   35728             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   35729                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   35730 
   35731 #ifdef SQLITE_TEST
   35732   if( sqlite3_current_time ){
   35733     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   35734   }
   35735 #endif
   35736   UNUSED_PARAMETER(pVfs);
   35737   return SQLITE_OK;
   35738 }
   35739 
   35740 /*
   35741 ** Find the current time (in Universal Coordinated Time).  Write the
   35742 ** current time and date as a Julian Day number into *prNow and
   35743 ** return 0.  Return 1 if the time and date cannot be found.
   35744 */
   35745 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   35746   int rc;
   35747   sqlite3_int64 i;
   35748   rc = winCurrentTimeInt64(pVfs, &i);
   35749   if( !rc ){
   35750     *prNow = i/86400000.0;
   35751   }
   35752   return rc;
   35753 }
   35754 
   35755 /*
   35756 ** The idea is that this function works like a combination of
   35757 ** GetLastError() and FormatMessage() on Windows (or errno and
   35758 ** strerror_r() on Unix). After an error is returned by an OS
   35759 ** function, SQLite calls this function with zBuf pointing to
   35760 ** a buffer of nBuf bytes. The OS layer should populate the
   35761 ** buffer with a nul-terminated UTF-8 encoded error message
   35762 ** describing the last IO error to have occurred within the calling
   35763 ** thread.
   35764 **
   35765 ** If the error message is too large for the supplied buffer,
   35766 ** it should be truncated. The return value of xGetLastError
   35767 ** is zero if the error message fits in the buffer, or non-zero
   35768 ** otherwise (if the message was truncated). If non-zero is returned,
   35769 ** then it is not necessary to include the nul-terminator character
   35770 ** in the output buffer.
   35771 **
   35772 ** Not supplying an error message will have no adverse effect
   35773 ** on SQLite. It is fine to have an implementation that never
   35774 ** returns an error message:
   35775 **
   35776 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35777 **     assert(zBuf[0]=='\0');
   35778 **     return 0;
   35779 **   }
   35780 **
   35781 ** However if an error message is supplied, it will be incorporated
   35782 ** by sqlite into the error message available to the user using
   35783 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   35784 */
   35785 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35786   UNUSED_PARAMETER(pVfs);
   35787   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
   35788 }
   35789 
   35790 /*
   35791 ** Initialize and deinitialize the operating system interface.
   35792 */
   35793 SQLITE_API int sqlite3_os_init(void){
   35794   static sqlite3_vfs winVfs = {
   35795     3,                   /* iVersion */
   35796     sizeof(winFile),     /* szOsFile */
   35797     MAX_PATH,            /* mxPathname */
   35798     0,                   /* pNext */
   35799     "win32",             /* zName */
   35800     0,                   /* pAppData */
   35801     winOpen,             /* xOpen */
   35802     winDelete,           /* xDelete */
   35803     winAccess,           /* xAccess */
   35804     winFullPathname,     /* xFullPathname */
   35805     winDlOpen,           /* xDlOpen */
   35806     winDlError,          /* xDlError */
   35807     winDlSym,            /* xDlSym */
   35808     winDlClose,          /* xDlClose */
   35809     winRandomness,       /* xRandomness */
   35810     winSleep,            /* xSleep */
   35811     winCurrentTime,      /* xCurrentTime */
   35812     winGetLastError,     /* xGetLastError */
   35813     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   35814     winSetSystemCall,    /* xSetSystemCall */
   35815     winGetSystemCall,    /* xGetSystemCall */
   35816     winNextSystemCall,   /* xNextSystemCall */
   35817   };
   35818 
   35819   /* Double-check that the aSyscall[] array has been constructed
   35820   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   35821   assert( ArraySize(aSyscall)==60 );
   35822 
   35823 #ifndef SQLITE_OMIT_WAL
   35824   /* get memory map allocation granularity */
   35825   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   35826   osGetSystemInfo(&winSysInfo);
   35827   assert(winSysInfo.dwAllocationGranularity > 0);
   35828 #endif
   35829 
   35830   sqlite3_vfs_register(&winVfs, 1);
   35831   return SQLITE_OK;
   35832 }
   35833 
   35834 SQLITE_API int sqlite3_os_end(void){
   35835   return SQLITE_OK;
   35836 }
   35837 
   35838 #endif /* SQLITE_OS_WIN */
   35839 
   35840 /************** End of os_win.c **********************************************/
   35841 /************** Begin file bitvec.c ******************************************/
   35842 /*
   35843 ** 2008 February 16
   35844 **
   35845 ** The author disclaims copyright to this source code.  In place of
   35846 ** a legal notice, here is a blessing:
   35847 **
   35848 **    May you do good and not evil.
   35849 **    May you find forgiveness for yourself and forgive others.
   35850 **    May you share freely, never taking more than you give.
   35851 **
   35852 *************************************************************************
   35853 ** This file implements an object that represents a fixed-length
   35854 ** bitmap.  Bits are numbered starting with 1.
   35855 **
   35856 ** A bitmap is used to record which pages of a database file have been
   35857 ** journalled during a transaction, or which pages have the "dont-write"
   35858 ** property.  Usually only a few pages are meet either condition.
   35859 ** So the bitmap is usually sparse and has low cardinality.
   35860 ** But sometimes (for example when during a DROP of a large table) most
   35861 ** or all of the pages in a database can get journalled.  In those cases,
   35862 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   35863 ** to handle both cases well.
   35864 **
   35865 ** The size of the bitmap is fixed when the object is created.
   35866 **
   35867 ** All bits are clear when the bitmap is created.  Individual bits
   35868 ** may be set or cleared one at a time.
   35869 **
   35870 ** Test operations are about 100 times more common that set operations.
   35871 ** Clear operations are exceedingly rare.  There are usually between
   35872 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   35873 ** sometimes grow into tens of thousands or larger.  The size of the
   35874 ** Bitvec object is the number of pages in the database file at the
   35875 ** start of a transaction, and is thus usually less than a few thousand,
   35876 ** but can be as large as 2 billion for a really big database.
   35877 */
   35878 
   35879 /* Size of the Bitvec structure in bytes. */
   35880 #define BITVEC_SZ        512
   35881 
   35882 /* Round the union size down to the nearest pointer boundary, since that's how
   35883 ** it will be aligned within the Bitvec struct. */
   35884 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   35885 
   35886 /* Type of the array "element" for the bitmap representation.
   35887 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   35888 ** Setting this to the "natural word" size of your CPU may improve
   35889 ** performance. */
   35890 #define BITVEC_TELEM     u8
   35891 /* Size, in bits, of the bitmap element. */
   35892 #define BITVEC_SZELEM    8
   35893 /* Number of elements in a bitmap array. */
   35894 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   35895 /* Number of bits in the bitmap array. */
   35896 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   35897 
   35898 /* Number of u32 values in hash table. */
   35899 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   35900 /* Maximum number of entries in hash table before
   35901 ** sub-dividing and re-hashing. */
   35902 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   35903 /* Hashing function for the aHash representation.
   35904 ** Empirical testing showed that the *37 multiplier
   35905 ** (an arbitrary prime)in the hash function provided
   35906 ** no fewer collisions than the no-op *1. */
   35907 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   35908 
   35909 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   35910 
   35911 
   35912 /*
   35913 ** A bitmap is an instance of the following structure.
   35914 **
   35915 ** This bitmap records the existance of zero or more bits
   35916 ** with values between 1 and iSize, inclusive.
   35917 **
   35918 ** There are three possible representations of the bitmap.
   35919 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   35920 ** bitmap.  The least significant bit is bit 1.
   35921 **
   35922 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   35923 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   35924 **
   35925 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   35926 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   35927 ** handles up to iDivisor separate values of i.  apSub[0] holds
   35928 ** values between 1 and iDivisor.  apSub[1] holds values between
   35929 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   35930 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   35931 ** to hold deal with values between 1 and iDivisor.
   35932 */
   35933 struct Bitvec {
   35934   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   35935   u32 nSet;       /* Number of bits that are set - only valid for aHash
   35936                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   35937                   ** this would be 125. */
   35938   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   35939                   /* Should >=0 for apSub element. */
   35940                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   35941                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   35942   union {
   35943     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   35944     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   35945     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   35946   } u;
   35947 };
   35948 
   35949 /*
   35950 ** Create a new bitmap object able to handle bits between 0 and iSize,
   35951 ** inclusive.  Return a pointer to the new object.  Return NULL if
   35952 ** malloc fails.
   35953 */
   35954 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   35955   Bitvec *p;
   35956   assert( sizeof(*p)==BITVEC_SZ );
   35957   p = sqlite3MallocZero( sizeof(*p) );
   35958   if( p ){
   35959     p->iSize = iSize;
   35960   }
   35961   return p;
   35962 }
   35963 
   35964 /*
   35965 ** Check to see if the i-th bit is set.  Return true or false.
   35966 ** If p is NULL (if the bitmap has not been created) or if
   35967 ** i is out of range, then return false.
   35968 */
   35969 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   35970   if( p==0 ) return 0;
   35971   if( i>p->iSize || i==0 ) return 0;
   35972   i--;
   35973   while( p->iDivisor ){
   35974     u32 bin = i/p->iDivisor;
   35975     i = i%p->iDivisor;
   35976     p = p->u.apSub[bin];
   35977     if (!p) {
   35978       return 0;
   35979     }
   35980   }
   35981   if( p->iSize<=BITVEC_NBIT ){
   35982     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   35983   } else{
   35984     u32 h = BITVEC_HASH(i++);
   35985     while( p->u.aHash[h] ){
   35986       if( p->u.aHash[h]==i ) return 1;
   35987       h = (h+1) % BITVEC_NINT;
   35988     }
   35989     return 0;
   35990   }
   35991 }
   35992 
   35993 /*
   35994 ** Set the i-th bit.  Return 0 on success and an error code if
   35995 ** anything goes wrong.
   35996 **
   35997 ** This routine might cause sub-bitmaps to be allocated.  Failing
   35998 ** to get the memory needed to hold the sub-bitmap is the only
   35999 ** that can go wrong with an insert, assuming p and i are valid.
   36000 **
   36001 ** The calling function must ensure that p is a valid Bitvec object
   36002 ** and that the value for "i" is within range of the Bitvec object.
   36003 ** Otherwise the behavior is undefined.
   36004 */
   36005 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   36006   u32 h;
   36007   if( p==0 ) return SQLITE_OK;
   36008   assert( i>0 );
   36009   assert( i<=p->iSize );
   36010   i--;
   36011   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   36012     u32 bin = i/p->iDivisor;
   36013     i = i%p->iDivisor;
   36014     if( p->u.apSub[bin]==0 ){
   36015       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   36016       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   36017     }
   36018     p = p->u.apSub[bin];
   36019   }
   36020   if( p->iSize<=BITVEC_NBIT ){
   36021     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   36022     return SQLITE_OK;
   36023   }
   36024   h = BITVEC_HASH(i++);
   36025   /* if there wasn't a hash collision, and this doesn't */
   36026   /* completely fill the hash, then just add it without */
   36027   /* worring about sub-dividing and re-hashing. */
   36028   if( !p->u.aHash[h] ){
   36029     if (p->nSet<(BITVEC_NINT-1)) {
   36030       goto bitvec_set_end;
   36031     } else {
   36032       goto bitvec_set_rehash;
   36033     }
   36034   }
   36035   /* there was a collision, check to see if it's already */
   36036   /* in hash, if not, try to find a spot for it */
   36037   do {
   36038     if( p->u.aHash[h]==i ) return SQLITE_OK;
   36039     h++;
   36040     if( h>=BITVEC_NINT ) h = 0;
   36041   } while( p->u.aHash[h] );
   36042   /* we didn't find it in the hash.  h points to the first */
   36043   /* available free spot. check to see if this is going to */
   36044   /* make our hash too "full".  */
   36045 bitvec_set_rehash:
   36046   if( p->nSet>=BITVEC_MXHASH ){
   36047     unsigned int j;
   36048     int rc;
   36049     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   36050     if( aiValues==0 ){
   36051       return SQLITE_NOMEM;
   36052     }else{
   36053       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   36054       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   36055       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   36056       rc = sqlite3BitvecSet(p, i);
   36057       for(j=0; j<BITVEC_NINT; j++){
   36058         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   36059       }
   36060       sqlite3StackFree(0, aiValues);
   36061       return rc;
   36062     }
   36063   }
   36064 bitvec_set_end:
   36065   p->nSet++;
   36066   p->u.aHash[h] = i;
   36067   return SQLITE_OK;
   36068 }
   36069 
   36070 /*
   36071 ** Clear the i-th bit.
   36072 **
   36073 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   36074 ** that BitvecClear can use to rebuilt its hash table.
   36075 */
   36076 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   36077   if( p==0 ) return;
   36078   assert( i>0 );
   36079   i--;
   36080   while( p->iDivisor ){
   36081     u32 bin = i/p->iDivisor;
   36082     i = i%p->iDivisor;
   36083     p = p->u.apSub[bin];
   36084     if (!p) {
   36085       return;
   36086     }
   36087   }
   36088   if( p->iSize<=BITVEC_NBIT ){
   36089     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   36090   }else{
   36091     unsigned int j;
   36092     u32 *aiValues = pBuf;
   36093     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   36094     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   36095     p->nSet = 0;
   36096     for(j=0; j<BITVEC_NINT; j++){
   36097       if( aiValues[j] && aiValues[j]!=(i+1) ){
   36098         u32 h = BITVEC_HASH(aiValues[j]-1);
   36099         p->nSet++;
   36100         while( p->u.aHash[h] ){
   36101           h++;
   36102           if( h>=BITVEC_NINT ) h = 0;
   36103         }
   36104         p->u.aHash[h] = aiValues[j];
   36105       }
   36106     }
   36107   }
   36108 }
   36109 
   36110 /*
   36111 ** Destroy a bitmap object.  Reclaim all memory used.
   36112 */
   36113 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   36114   if( p==0 ) return;
   36115   if( p->iDivisor ){
   36116     unsigned int i;
   36117     for(i=0; i<BITVEC_NPTR; i++){
   36118       sqlite3BitvecDestroy(p->u.apSub[i]);
   36119     }
   36120   }
   36121   sqlite3_free(p);
   36122 }
   36123 
   36124 /*
   36125 ** Return the value of the iSize parameter specified when Bitvec *p
   36126 ** was created.
   36127 */
   36128 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   36129   return p->iSize;
   36130 }
   36131 
   36132 #ifndef SQLITE_OMIT_BUILTIN_TEST
   36133 /*
   36134 ** Let V[] be an array of unsigned characters sufficient to hold
   36135 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   36136 ** Then the following macros can be used to set, clear, or test
   36137 ** individual bits within V.
   36138 */
   36139 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   36140 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   36141 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   36142 
   36143 /*
   36144 ** This routine runs an extensive test of the Bitvec code.
   36145 **
   36146 ** The input is an array of integers that acts as a program
   36147 ** to test the Bitvec.  The integers are opcodes followed
   36148 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   36149 ** opcode follows immediately after the last operand.
   36150 **
   36151 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   36152 ** "halt" opcode and causes the test to end.
   36153 **
   36154 **    0          Halt and return the number of errors
   36155 **    1 N S X    Set N bits beginning with S and incrementing by X
   36156 **    2 N S X    Clear N bits beginning with S and incrementing by X
   36157 **    3 N        Set N randomly chosen bits
   36158 **    4 N        Clear N randomly chosen bits
   36159 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   36160 **
   36161 ** The opcodes 1 through 4 perform set and clear operations are performed
   36162 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   36163 ** Opcode 5 works on the linear array only, not on the Bitvec.
   36164 ** Opcode 5 is used to deliberately induce a fault in order to
   36165 ** confirm that error detection works.
   36166 **
   36167 ** At the conclusion of the test the linear array is compared
   36168 ** against the Bitvec object.  If there are any differences,
   36169 ** an error is returned.  If they are the same, zero is returned.
   36170 **
   36171 ** If a memory allocation error occurs, return -1.
   36172 */
   36173 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   36174   Bitvec *pBitvec = 0;
   36175   unsigned char *pV = 0;
   36176   int rc = -1;
   36177   int i, nx, pc, op;
   36178   void *pTmpSpace;
   36179 
   36180   /* Allocate the Bitvec to be tested and a linear array of
   36181   ** bits to act as the reference */
   36182   pBitvec = sqlite3BitvecCreate( sz );
   36183   pV = sqlite3_malloc( (sz+7)/8 + 1 );
   36184   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   36185   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   36186   memset(pV, 0, (sz+7)/8 + 1);
   36187 
   36188   /* NULL pBitvec tests */
   36189   sqlite3BitvecSet(0, 1);
   36190   sqlite3BitvecClear(0, 1, pTmpSpace);
   36191 
   36192   /* Run the program */
   36193   pc = 0;
   36194   while( (op = aOp[pc])!=0 ){
   36195     switch( op ){
   36196       case 1:
   36197       case 2:
   36198       case 5: {
   36199         nx = 4;
   36200         i = aOp[pc+2] - 1;
   36201         aOp[pc+2] += aOp[pc+3];
   36202         break;
   36203       }
   36204       case 3:
   36205       case 4:
   36206       default: {
   36207         nx = 2;
   36208         sqlite3_randomness(sizeof(i), &i);
   36209         break;
   36210       }
   36211     }
   36212     if( (--aOp[pc+1]) > 0 ) nx = 0;
   36213     pc += nx;
   36214     i = (i & 0x7fffffff)%sz;
   36215     if( (op & 1)!=0 ){
   36216       SETBIT(pV, (i+1));
   36217       if( op!=5 ){
   36218         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   36219       }
   36220     }else{
   36221       CLEARBIT(pV, (i+1));
   36222       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   36223     }
   36224   }
   36225 
   36226   /* Test to make sure the linear array exactly matches the
   36227   ** Bitvec object.  Start with the assumption that they do
   36228   ** match (rc==0).  Change rc to non-zero if a discrepancy
   36229   ** is found.
   36230   */
   36231   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   36232           + sqlite3BitvecTest(pBitvec, 0)
   36233           + (sqlite3BitvecSize(pBitvec) - sz);
   36234   for(i=1; i<=sz; i++){
   36235     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   36236       rc = i;
   36237       break;
   36238     }
   36239   }
   36240 
   36241   /* Free allocated structure */
   36242 bitvec_end:
   36243   sqlite3_free(pTmpSpace);
   36244   sqlite3_free(pV);
   36245   sqlite3BitvecDestroy(pBitvec);
   36246   return rc;
   36247 }
   36248 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   36249 
   36250 /************** End of bitvec.c **********************************************/
   36251 /************** Begin file pcache.c ******************************************/
   36252 /*
   36253 ** 2008 August 05
   36254 **
   36255 ** The author disclaims copyright to this source code.  In place of
   36256 ** a legal notice, here is a blessing:
   36257 **
   36258 **    May you do good and not evil.
   36259 **    May you find forgiveness for yourself and forgive others.
   36260 **    May you share freely, never taking more than you give.
   36261 **
   36262 *************************************************************************
   36263 ** This file implements that page cache.
   36264 */
   36265 
   36266 /*
   36267 ** A complete page cache is an instance of this structure.
   36268 */
   36269 struct PCache {
   36270   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   36271   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   36272   int nRef;                           /* Number of referenced pages */
   36273   int szCache;                        /* Configured cache size */
   36274   int szPage;                         /* Size of every page in this cache */
   36275   int szExtra;                        /* Size of extra space for each page */
   36276   int bPurgeable;                     /* True if pages are on backing store */
   36277   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   36278   void *pStress;                      /* Argument to xStress */
   36279   sqlite3_pcache *pCache;             /* Pluggable cache module */
   36280   PgHdr *pPage1;                      /* Reference to page 1 */
   36281 };
   36282 
   36283 /*
   36284 ** Some of the assert() macros in this code are too expensive to run
   36285 ** even during normal debugging.  Use them only rarely on long-running
   36286 ** tests.  Enable the expensive asserts using the
   36287 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   36288 */
   36289 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   36290 # define expensive_assert(X)  assert(X)
   36291 #else
   36292 # define expensive_assert(X)
   36293 #endif
   36294 
   36295 /********************************** Linked List Management ********************/
   36296 
   36297 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   36298 /*
   36299 ** Check that the pCache->pSynced variable is set correctly. If it
   36300 ** is not, either fail an assert or return zero. Otherwise, return
   36301 ** non-zero. This is only used in debugging builds, as follows:
   36302 **
   36303 **   expensive_assert( pcacheCheckSynced(pCache) );
   36304 */
   36305 static int pcacheCheckSynced(PCache *pCache){
   36306   PgHdr *p;
   36307   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   36308     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   36309   }
   36310   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   36311 }
   36312 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   36313 
   36314 /*
   36315 ** Remove page pPage from the list of dirty pages.
   36316 */
   36317 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   36318   PCache *p = pPage->pCache;
   36319 
   36320   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   36321   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   36322 
   36323   /* Update the PCache1.pSynced variable if necessary. */
   36324   if( p->pSynced==pPage ){
   36325     PgHdr *pSynced = pPage->pDirtyPrev;
   36326     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   36327       pSynced = pSynced->pDirtyPrev;
   36328     }
   36329     p->pSynced = pSynced;
   36330   }
   36331 
   36332   if( pPage->pDirtyNext ){
   36333     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   36334   }else{
   36335     assert( pPage==p->pDirtyTail );
   36336     p->pDirtyTail = pPage->pDirtyPrev;
   36337   }
   36338   if( pPage->pDirtyPrev ){
   36339     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   36340   }else{
   36341     assert( pPage==p->pDirty );
   36342     p->pDirty = pPage->pDirtyNext;
   36343   }
   36344   pPage->pDirtyNext = 0;
   36345   pPage->pDirtyPrev = 0;
   36346 
   36347   expensive_assert( pcacheCheckSynced(p) );
   36348 }
   36349 
   36350 /*
   36351 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   36352 ** pPage).
   36353 */
   36354 static void pcacheAddToDirtyList(PgHdr *pPage){
   36355   PCache *p = pPage->pCache;
   36356 
   36357   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   36358 
   36359   pPage->pDirtyNext = p->pDirty;
   36360   if( pPage->pDirtyNext ){
   36361     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   36362     pPage->pDirtyNext->pDirtyPrev = pPage;
   36363   }
   36364   p->pDirty = pPage;
   36365   if( !p->pDirtyTail ){
   36366     p->pDirtyTail = pPage;
   36367   }
   36368   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   36369     p->pSynced = pPage;
   36370   }
   36371   expensive_assert( pcacheCheckSynced(p) );
   36372 }
   36373 
   36374 /*
   36375 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   36376 ** being used for an in-memory database, this function is a no-op.
   36377 */
   36378 static void pcacheUnpin(PgHdr *p){
   36379   PCache *pCache = p->pCache;
   36380   if( pCache->bPurgeable ){
   36381     if( p->pgno==1 ){
   36382       pCache->pPage1 = 0;
   36383     }
   36384     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
   36385   }
   36386 }
   36387 
   36388 /*************************************************** General Interfaces ******
   36389 **
   36390 ** Initialize and shutdown the page cache subsystem. Neither of these
   36391 ** functions are threadsafe.
   36392 */
   36393 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   36394   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   36395     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   36396     ** built-in default page cache is used instead of the application defined
   36397     ** page cache. */
   36398     sqlite3PCacheSetDefault();
   36399   }
   36400   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   36401 }
   36402 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   36403   if( sqlite3GlobalConfig.pcache2.xShutdown ){
   36404     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   36405     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   36406   }
   36407 }
   36408 
   36409 /*
   36410 ** Return the size in bytes of a PCache object.
   36411 */
   36412 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   36413 
   36414 /*
   36415 ** Create a new PCache object. Storage space to hold the object
   36416 ** has already been allocated and is passed in as the p pointer.
   36417 ** The caller discovers how much space needs to be allocated by
   36418 ** calling sqlite3PcacheSize().
   36419 */
   36420 SQLITE_PRIVATE void sqlite3PcacheOpen(
   36421   int szPage,                  /* Size of every page */
   36422   int szExtra,                 /* Extra space associated with each page */
   36423   int bPurgeable,              /* True if pages are on backing store */
   36424   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   36425   void *pStress,               /* Argument to xStress */
   36426   PCache *p                    /* Preallocated space for the PCache */
   36427 ){
   36428   memset(p, 0, sizeof(PCache));
   36429   p->szPage = szPage;
   36430   p->szExtra = szExtra;
   36431   p->bPurgeable = bPurgeable;
   36432   p->xStress = xStress;
   36433   p->pStress = pStress;
   36434   p->szCache = 100;
   36435 }
   36436 
   36437 /*
   36438 ** Change the page size for PCache object. The caller must ensure that there
   36439 ** are no outstanding page references when this function is called.
   36440 */
   36441 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   36442   assert( pCache->nRef==0 && pCache->pDirty==0 );
   36443   if( pCache->pCache ){
   36444     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   36445     pCache->pCache = 0;
   36446     pCache->pPage1 = 0;
   36447   }
   36448   pCache->szPage = szPage;
   36449 }
   36450 
   36451 /*
   36452 ** Compute the number of pages of cache requested.
   36453 */
   36454 static int numberOfCachePages(PCache *p){
   36455   if( p->szCache>=0 ){
   36456     return p->szCache;
   36457   }else{
   36458     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
   36459   }
   36460 }
   36461 
   36462 /*
   36463 ** Try to obtain a page from the cache.
   36464 */
   36465 SQLITE_PRIVATE int sqlite3PcacheFetch(
   36466   PCache *pCache,       /* Obtain the page from this cache */
   36467   Pgno pgno,            /* Page number to obtain */
   36468   int createFlag,       /* If true, create page if it does not exist already */
   36469   PgHdr **ppPage        /* Write the page here */
   36470 ){
   36471   sqlite3_pcache_page *pPage = 0;
   36472   PgHdr *pPgHdr = 0;
   36473   int eCreate;
   36474 
   36475   assert( pCache!=0 );
   36476   assert( createFlag==1 || createFlag==0 );
   36477   assert( pgno>0 );
   36478 
   36479   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   36480   ** allocate it now.
   36481   */
   36482   if( !pCache->pCache && createFlag ){
   36483     sqlite3_pcache *p;
   36484     p = sqlite3GlobalConfig.pcache2.xCreate(
   36485         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
   36486     );
   36487     if( !p ){
   36488       return SQLITE_NOMEM;
   36489     }
   36490     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
   36491     pCache->pCache = p;
   36492   }
   36493 
   36494   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
   36495   if( pCache->pCache ){
   36496     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   36497   }
   36498 
   36499   if( !pPage && eCreate==1 ){
   36500     PgHdr *pPg;
   36501 
   36502     /* Find a dirty page to write-out and recycle. First try to find a
   36503     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   36504     ** cleared), but if that is not possible settle for any other
   36505     ** unreferenced dirty page.
   36506     */
   36507     expensive_assert( pcacheCheckSynced(pCache) );
   36508     for(pPg=pCache->pSynced;
   36509         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   36510         pPg=pPg->pDirtyPrev
   36511     );
   36512     pCache->pSynced = pPg;
   36513     if( !pPg ){
   36514       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   36515     }
   36516     if( pPg ){
   36517       int rc;
   36518 #ifdef SQLITE_LOG_CACHE_SPILL
   36519       sqlite3_log(SQLITE_FULL,
   36520                   "spill page %d making room for %d - cache used: %d/%d",
   36521                   pPg->pgno, pgno,
   36522                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   36523                   numberOfCachePages(pCache));
   36524 #endif
   36525       rc = pCache->xStress(pCache->pStress, pPg);
   36526       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   36527         return rc;
   36528       }
   36529     }
   36530 
   36531     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   36532   }
   36533 
   36534   if( pPage ){
   36535     pPgHdr = (PgHdr *)pPage->pExtra;
   36536 
   36537     if( !pPgHdr->pPage ){
   36538       memset(pPgHdr, 0, sizeof(PgHdr));
   36539       pPgHdr->pPage = pPage;
   36540       pPgHdr->pData = pPage->pBuf;
   36541       pPgHdr->pExtra = (void *)&pPgHdr[1];
   36542       memset(pPgHdr->pExtra, 0, pCache->szExtra);
   36543       pPgHdr->pCache = pCache;
   36544       pPgHdr->pgno = pgno;
   36545     }
   36546     assert( pPgHdr->pCache==pCache );
   36547     assert( pPgHdr->pgno==pgno );
   36548     assert( pPgHdr->pData==pPage->pBuf );
   36549     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
   36550 
   36551     if( 0==pPgHdr->nRef ){
   36552       pCache->nRef++;
   36553     }
   36554     pPgHdr->nRef++;
   36555     if( pgno==1 ){
   36556       pCache->pPage1 = pPgHdr;
   36557     }
   36558   }
   36559   *ppPage = pPgHdr;
   36560   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   36561 }
   36562 
   36563 /*
   36564 ** Decrement the reference count on a page. If the page is clean and the
   36565 ** reference count drops to 0, then it is made elible for recycling.
   36566 */
   36567 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   36568   assert( p->nRef>0 );
   36569   p->nRef--;
   36570   if( p->nRef==0 ){
   36571     PCache *pCache = p->pCache;
   36572     pCache->nRef--;
   36573     if( (p->flags&PGHDR_DIRTY)==0 ){
   36574       pcacheUnpin(p);
   36575     }else{
   36576       /* Move the page to the head of the dirty list. */
   36577       pcacheRemoveFromDirtyList(p);
   36578       pcacheAddToDirtyList(p);
   36579     }
   36580   }
   36581 }
   36582 
   36583 /*
   36584 ** Increase the reference count of a supplied page by 1.
   36585 */
   36586 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   36587   assert(p->nRef>0);
   36588   p->nRef++;
   36589 }
   36590 
   36591 /*
   36592 ** Drop a page from the cache. There must be exactly one reference to the
   36593 ** page. This function deletes that reference, so after it returns the
   36594 ** page pointed to by p is invalid.
   36595 */
   36596 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   36597   PCache *pCache;
   36598   assert( p->nRef==1 );
   36599   if( p->flags&PGHDR_DIRTY ){
   36600     pcacheRemoveFromDirtyList(p);
   36601   }
   36602   pCache = p->pCache;
   36603   pCache->nRef--;
   36604   if( p->pgno==1 ){
   36605     pCache->pPage1 = 0;
   36606   }
   36607   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
   36608 }
   36609 
   36610 /*
   36611 ** Make sure the page is marked as dirty. If it isn't dirty already,
   36612 ** make it so.
   36613 */
   36614 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   36615   p->flags &= ~PGHDR_DONT_WRITE;
   36616   assert( p->nRef>0 );
   36617   if( 0==(p->flags & PGHDR_DIRTY) ){
   36618     p->flags |= PGHDR_DIRTY;
   36619     pcacheAddToDirtyList( p);
   36620   }
   36621 }
   36622 
   36623 /*
   36624 ** Make sure the page is marked as clean. If it isn't clean already,
   36625 ** make it so.
   36626 */
   36627 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   36628   if( (p->flags & PGHDR_DIRTY) ){
   36629     pcacheRemoveFromDirtyList(p);
   36630     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   36631     if( p->nRef==0 ){
   36632       pcacheUnpin(p);
   36633     }
   36634   }
   36635 }
   36636 
   36637 /*
   36638 ** Make every page in the cache clean.
   36639 */
   36640 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   36641   PgHdr *p;
   36642   while( (p = pCache->pDirty)!=0 ){
   36643     sqlite3PcacheMakeClean(p);
   36644   }
   36645 }
   36646 
   36647 /*
   36648 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   36649 */
   36650 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   36651   PgHdr *p;
   36652   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   36653     p->flags &= ~PGHDR_NEED_SYNC;
   36654   }
   36655   pCache->pSynced = pCache->pDirtyTail;
   36656 }
   36657 
   36658 /*
   36659 ** Change the page number of page p to newPgno.
   36660 */
   36661 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   36662   PCache *pCache = p->pCache;
   36663   assert( p->nRef>0 );
   36664   assert( newPgno>0 );
   36665   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   36666   p->pgno = newPgno;
   36667   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   36668     pcacheRemoveFromDirtyList(p);
   36669     pcacheAddToDirtyList(p);
   36670   }
   36671 }
   36672 
   36673 /*
   36674 ** Drop every cache entry whose page number is greater than "pgno". The
   36675 ** caller must ensure that there are no outstanding references to any pages
   36676 ** other than page 1 with a page number greater than pgno.
   36677 **
   36678 ** If there is a reference to page 1 and the pgno parameter passed to this
   36679 ** function is 0, then the data area associated with page 1 is zeroed, but
   36680 ** the page object is not dropped.
   36681 */
   36682 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   36683   if( pCache->pCache ){
   36684     PgHdr *p;
   36685     PgHdr *pNext;
   36686     for(p=pCache->pDirty; p; p=pNext){
   36687       pNext = p->pDirtyNext;
   36688       /* This routine never gets call with a positive pgno except right
   36689       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   36690       ** it must be that pgno==0.
   36691       */
   36692       assert( p->pgno>0 );
   36693       if( ALWAYS(p->pgno>pgno) ){
   36694         assert( p->flags&PGHDR_DIRTY );
   36695         sqlite3PcacheMakeClean(p);
   36696       }
   36697     }
   36698     if( pgno==0 && pCache->pPage1 ){
   36699       memset(pCache->pPage1->pData, 0, pCache->szPage);
   36700       pgno = 1;
   36701     }
   36702     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   36703   }
   36704 }
   36705 
   36706 /*
   36707 ** Close a cache.
   36708 */
   36709 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   36710   if( pCache->pCache ){
   36711     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   36712   }
   36713 }
   36714 
   36715 /*
   36716 ** Discard the contents of the cache.
   36717 */
   36718 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   36719   sqlite3PcacheTruncate(pCache, 0);
   36720 }
   36721 
   36722 /*
   36723 ** Merge two lists of pages connected by pDirty and in pgno order.
   36724 ** Do not both fixing the pDirtyPrev pointers.
   36725 */
   36726 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   36727   PgHdr result, *pTail;
   36728   pTail = &result;
   36729   while( pA && pB ){
   36730     if( pA->pgno<pB->pgno ){
   36731       pTail->pDirty = pA;
   36732       pTail = pA;
   36733       pA = pA->pDirty;
   36734     }else{
   36735       pTail->pDirty = pB;
   36736       pTail = pB;
   36737       pB = pB->pDirty;
   36738     }
   36739   }
   36740   if( pA ){
   36741     pTail->pDirty = pA;
   36742   }else if( pB ){
   36743     pTail->pDirty = pB;
   36744   }else{
   36745     pTail->pDirty = 0;
   36746   }
   36747   return result.pDirty;
   36748 }
   36749 
   36750 /*
   36751 ** Sort the list of pages in accending order by pgno.  Pages are
   36752 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   36753 ** corrupted by this sort.
   36754 **
   36755 ** Since there cannot be more than 2^31 distinct pages in a database,
   36756 ** there cannot be more than 31 buckets required by the merge sorter.
   36757 ** One extra bucket is added to catch overflow in case something
   36758 ** ever changes to make the previous sentence incorrect.
   36759 */
   36760 #define N_SORT_BUCKET  32
   36761 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   36762   PgHdr *a[N_SORT_BUCKET], *p;
   36763   int i;
   36764   memset(a, 0, sizeof(a));
   36765   while( pIn ){
   36766     p = pIn;
   36767     pIn = p->pDirty;
   36768     p->pDirty = 0;
   36769     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   36770       if( a[i]==0 ){
   36771         a[i] = p;
   36772         break;
   36773       }else{
   36774         p = pcacheMergeDirtyList(a[i], p);
   36775         a[i] = 0;
   36776       }
   36777     }
   36778     if( NEVER(i==N_SORT_BUCKET-1) ){
   36779       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   36780       ** the input list.  But that is impossible.
   36781       */
   36782       a[i] = pcacheMergeDirtyList(a[i], p);
   36783     }
   36784   }
   36785   p = a[0];
   36786   for(i=1; i<N_SORT_BUCKET; i++){
   36787     p = pcacheMergeDirtyList(p, a[i]);
   36788   }
   36789   return p;
   36790 }
   36791 
   36792 /*
   36793 ** Return a list of all dirty pages in the cache, sorted by page number.
   36794 */
   36795 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   36796   PgHdr *p;
   36797   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   36798     p->pDirty = p->pDirtyNext;
   36799   }
   36800   return pcacheSortDirtyList(pCache->pDirty);
   36801 }
   36802 
   36803 /*
   36804 ** Return the total number of referenced pages held by the cache.
   36805 */
   36806 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   36807   return pCache->nRef;
   36808 }
   36809 
   36810 /*
   36811 ** Return the number of references to the page supplied as an argument.
   36812 */
   36813 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   36814   return p->nRef;
   36815 }
   36816 
   36817 /*
   36818 ** Return the total number of pages in the cache.
   36819 */
   36820 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   36821   int nPage = 0;
   36822   if( pCache->pCache ){
   36823     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   36824   }
   36825   return nPage;
   36826 }
   36827 
   36828 #ifdef SQLITE_TEST
   36829 /*
   36830 ** Get the suggested cache-size value.
   36831 */
   36832 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   36833   return numberOfCachePages(pCache);
   36834 }
   36835 #endif
   36836 
   36837 /*
   36838 ** Set the suggested cache-size value.
   36839 */
   36840 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   36841   pCache->szCache = mxPage;
   36842   if( pCache->pCache ){
   36843     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
   36844                                            numberOfCachePages(pCache));
   36845   }
   36846 }
   36847 
   36848 /*
   36849 ** Free up as much memory as possible from the page cache.
   36850 */
   36851 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
   36852   if( pCache->pCache ){
   36853     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   36854   }
   36855 }
   36856 
   36857 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   36858 /*
   36859 ** For all dirty pages currently in the cache, invoke the specified
   36860 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   36861 ** defined.
   36862 */
   36863 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   36864   PgHdr *pDirty;
   36865   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   36866     xIter(pDirty);
   36867   }
   36868 }
   36869 #endif
   36870 
   36871 /************** End of pcache.c **********************************************/
   36872 /************** Begin file pcache1.c *****************************************/
   36873 /*
   36874 ** 2008 November 05
   36875 **
   36876 ** The author disclaims copyright to this source code.  In place of
   36877 ** a legal notice, here is a blessing:
   36878 **
   36879 **    May you do good and not evil.
   36880 **    May you find forgiveness for yourself and forgive others.
   36881 **    May you share freely, never taking more than you give.
   36882 **
   36883 *************************************************************************
   36884 **
   36885 ** This file implements the default page cache implementation (the
   36886 ** sqlite3_pcache interface). It also contains part of the implementation
   36887 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   36888 ** If the default page cache implementation is overriden, then neither of
   36889 ** these two features are available.
   36890 */
   36891 
   36892 
   36893 typedef struct PCache1 PCache1;
   36894 typedef struct PgHdr1 PgHdr1;
   36895 typedef struct PgFreeslot PgFreeslot;
   36896 typedef struct PGroup PGroup;
   36897 
   36898 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
   36899 ** of one or more PCaches that are able to recycle each others unpinned
   36900 ** pages when they are under memory pressure.  A PGroup is an instance of
   36901 ** the following object.
   36902 **
   36903 ** This page cache implementation works in one of two modes:
   36904 **
   36905 **   (1)  Every PCache is the sole member of its own PGroup.  There is
   36906 **        one PGroup per PCache.
   36907 **
   36908 **   (2)  There is a single global PGroup that all PCaches are a member
   36909 **        of.
   36910 **
   36911 ** Mode 1 uses more memory (since PCache instances are not able to rob
   36912 ** unused pages from other PCaches) but it also operates without a mutex,
   36913 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
   36914 ** threadsafe, but recycles pages more efficiently.
   36915 **
   36916 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
   36917 ** PGroup which is the pcache1.grp global variable and its mutex is
   36918 ** SQLITE_MUTEX_STATIC_LRU.
   36919 */
   36920 struct PGroup {
   36921   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
   36922   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
   36923   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
   36924   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
   36925   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
   36926   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
   36927 };
   36928 
   36929 /* Each page cache is an instance of the following object.  Every
   36930 ** open database file (including each in-memory database and each
   36931 ** temporary or transient database) has a single page cache which
   36932 ** is an instance of this object.
   36933 **
   36934 ** Pointers to structures of this type are cast and returned as
   36935 ** opaque sqlite3_pcache* handles.
   36936 */
   36937 struct PCache1 {
   36938   /* Cache configuration parameters. Page size (szPage) and the purgeable
   36939   ** flag (bPurgeable) are set when the cache is created. nMax may be
   36940   ** modified at any time by a call to the pcache1Cachesize() method.
   36941   ** The PGroup mutex must be held when accessing nMax.
   36942   */
   36943   PGroup *pGroup;                     /* PGroup this cache belongs to */
   36944   int szPage;                         /* Size of allocated pages in bytes */
   36945   int szExtra;                        /* Size of extra space in bytes */
   36946   int bPurgeable;                     /* True if cache is purgeable */
   36947   unsigned int nMin;                  /* Minimum number of pages reserved */
   36948   unsigned int nMax;                  /* Configured "cache_size" value */
   36949   unsigned int n90pct;                /* nMax*9/10 */
   36950   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   36951 
   36952   /* Hash table of all pages. The following variables may only be accessed
   36953   ** when the accessor is holding the PGroup mutex.
   36954   */
   36955   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   36956   unsigned int nPage;                 /* Total number of pages in apHash */
   36957   unsigned int nHash;                 /* Number of slots in apHash[] */
   36958   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   36959 };
   36960 
   36961 /*
   36962 ** Each cache entry is represented by an instance of the following
   36963 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
   36964 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
   36965 ** in memory.
   36966 */
   36967 struct PgHdr1 {
   36968   sqlite3_pcache_page page;
   36969   unsigned int iKey;             /* Key value (page number) */
   36970   PgHdr1 *pNext;                 /* Next in hash table chain */
   36971   PCache1 *pCache;               /* Cache that currently owns this page */
   36972   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   36973   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   36974 };
   36975 
   36976 /*
   36977 ** Free slots in the allocator used to divide up the buffer provided using
   36978 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   36979 */
   36980 struct PgFreeslot {
   36981   PgFreeslot *pNext;  /* Next free slot */
   36982 };
   36983 
   36984 /*
   36985 ** Global data used by this cache.
   36986 */
   36987 static SQLITE_WSD struct PCacheGlobal {
   36988   PGroup grp;                    /* The global PGroup for mode (2) */
   36989 
   36990   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
   36991   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
   36992   ** fixed at sqlite3_initialize() time and do not require mutex protection.
   36993   ** The nFreeSlot and pFree values do require mutex protection.
   36994   */
   36995   int isInit;                    /* True if initialized */
   36996   int szSlot;                    /* Size of each free slot */
   36997   int nSlot;                     /* The number of pcache slots */
   36998   int nReserve;                  /* Try to keep nFreeSlot above this */
   36999   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
   37000   /* Above requires no mutex.  Use mutex below for variable that follow. */
   37001   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
   37002   PgFreeslot *pFree;             /* Free page blocks */
   37003   int nFreeSlot;                 /* Number of unused pcache slots */
   37004   /* The following value requires a mutex to change.  We skip the mutex on
   37005   ** reading because (1) most platforms read a 32-bit integer atomically and
   37006   ** (2) even if an incorrect value is read, no great harm is done since this
   37007   ** is really just an optimization. */
   37008   int bUnderPressure;            /* True if low on PAGECACHE memory */
   37009 } pcache1_g;
   37010 
   37011 /*
   37012 ** All code in this file should access the global structure above via the
   37013 ** alias "pcache1". This ensures that the WSD emulation is used when
   37014 ** compiling for systems that do not support real WSD.
   37015 */
   37016 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   37017 
   37018 /*
   37019 ** Macros to enter and leave the PCache LRU mutex.
   37020 */
   37021 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   37022 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   37023 
   37024 /******************************************************************************/
   37025 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   37026 
   37027 /*
   37028 ** This function is called during initialization if a static buffer is
   37029 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   37030 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   37031 ** enough to contain 'n' buffers of 'sz' bytes each.
   37032 **
   37033 ** This routine is called from sqlite3_initialize() and so it is guaranteed
   37034 ** to be serialized already.  There is no need for further mutexing.
   37035 */
   37036 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   37037   if( pcache1.isInit ){
   37038     PgFreeslot *p;
   37039     sz = ROUNDDOWN8(sz);
   37040     pcache1.szSlot = sz;
   37041     pcache1.nSlot = pcache1.nFreeSlot = n;
   37042     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   37043     pcache1.pStart = pBuf;
   37044     pcache1.pFree = 0;
   37045     pcache1.bUnderPressure = 0;
   37046     while( n-- ){
   37047       p = (PgFreeslot*)pBuf;
   37048       p->pNext = pcache1.pFree;
   37049       pcache1.pFree = p;
   37050       pBuf = (void*)&((char*)pBuf)[sz];
   37051     }
   37052     pcache1.pEnd = pBuf;
   37053   }
   37054 }
   37055 
   37056 /*
   37057 ** Malloc function used within this file to allocate space from the buffer
   37058 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   37059 ** such buffer exists or there is no space left in it, this function falls
   37060 ** back to sqlite3Malloc().
   37061 **
   37062 ** Multiple threads can run this routine at the same time.  Global variables
   37063 ** in pcache1 need to be protected via mutex.
   37064 */
   37065 static void *pcache1Alloc(int nByte){
   37066   void *p = 0;
   37067   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   37068   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   37069   if( nByte<=pcache1.szSlot ){
   37070     sqlite3_mutex_enter(pcache1.mutex);
   37071     p = (PgHdr1 *)pcache1.pFree;
   37072     if( p ){
   37073       pcache1.pFree = pcache1.pFree->pNext;
   37074       pcache1.nFreeSlot--;
   37075       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   37076       assert( pcache1.nFreeSlot>=0 );
   37077       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   37078     }
   37079     sqlite3_mutex_leave(pcache1.mutex);
   37080   }
   37081   if( p==0 ){
   37082     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
   37083     ** it from sqlite3Malloc instead.
   37084     */
   37085     p = sqlite3Malloc(nByte);
   37086     if( p ){
   37087       int sz = sqlite3MallocSize(p);
   37088       sqlite3_mutex_enter(pcache1.mutex);
   37089       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   37090       sqlite3_mutex_leave(pcache1.mutex);
   37091     }
   37092     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   37093   }
   37094   return p;
   37095 }
   37096 
   37097 /*
   37098 ** Free an allocated buffer obtained from pcache1Alloc().
   37099 */
   37100 static int pcache1Free(void *p){
   37101   int nFreed = 0;
   37102   if( p==0 ) return 0;
   37103   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   37104     PgFreeslot *pSlot;
   37105     sqlite3_mutex_enter(pcache1.mutex);
   37106     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   37107     pSlot = (PgFreeslot*)p;
   37108     pSlot->pNext = pcache1.pFree;
   37109     pcache1.pFree = pSlot;
   37110     pcache1.nFreeSlot++;
   37111     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   37112     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   37113     sqlite3_mutex_leave(pcache1.mutex);
   37114   }else{
   37115     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   37116     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   37117     nFreed = sqlite3MallocSize(p);
   37118     sqlite3_mutex_enter(pcache1.mutex);
   37119     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
   37120     sqlite3_mutex_leave(pcache1.mutex);
   37121     sqlite3_free(p);
   37122   }
   37123   return nFreed;
   37124 }
   37125 
   37126 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   37127 /*
   37128 ** Return the size of a pcache allocation
   37129 */
   37130 static int pcache1MemSize(void *p){
   37131   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   37132     return pcache1.szSlot;
   37133   }else{
   37134     int iSize;
   37135     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   37136     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   37137     iSize = sqlite3MallocSize(p);
   37138     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   37139     return iSize;
   37140   }
   37141 }
   37142 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   37143 
   37144 /*
   37145 ** Allocate a new page object initially associated with cache pCache.
   37146 */
   37147 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   37148   PgHdr1 *p = 0;
   37149   void *pPg;
   37150 
   37151   /* The group mutex must be released before pcache1Alloc() is called. This
   37152   ** is because it may call sqlite3_release_memory(), which assumes that
   37153   ** this mutex is not held. */
   37154   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37155   pcache1LeaveMutex(pCache->pGroup);
   37156 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37157   pPg = pcache1Alloc(pCache->szPage);
   37158   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
   37159   if( !pPg || !p ){
   37160     pcache1Free(pPg);
   37161     sqlite3_free(p);
   37162     pPg = 0;
   37163   }
   37164 #else
   37165   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
   37166   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
   37167 #endif
   37168   pcache1EnterMutex(pCache->pGroup);
   37169 
   37170   if( pPg ){
   37171     p->page.pBuf = pPg;
   37172     p->page.pExtra = &p[1];
   37173     if( pCache->bPurgeable ){
   37174       pCache->pGroup->nCurrentPage++;
   37175     }
   37176     return p;
   37177   }
   37178   return 0;
   37179 }
   37180 
   37181 /*
   37182 ** Free a page object allocated by pcache1AllocPage().
   37183 **
   37184 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   37185 ** that the current implementation happens to never call this routine
   37186 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   37187 */
   37188 static void pcache1FreePage(PgHdr1 *p){
   37189   if( ALWAYS(p) ){
   37190     PCache1 *pCache = p->pCache;
   37191     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   37192     pcache1Free(p->page.pBuf);
   37193 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37194     sqlite3_free(p);
   37195 #endif
   37196     if( pCache->bPurgeable ){
   37197       pCache->pGroup->nCurrentPage--;
   37198     }
   37199   }
   37200 }
   37201 
   37202 /*
   37203 ** Malloc function used by SQLite to obtain space from the buffer configured
   37204 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   37205 ** exists, this function falls back to sqlite3Malloc().
   37206 */
   37207 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   37208   return pcache1Alloc(sz);
   37209 }
   37210 
   37211 /*
   37212 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   37213 */
   37214 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   37215   pcache1Free(p);
   37216 }
   37217 
   37218 
   37219 /*
   37220 ** Return true if it desirable to avoid allocating a new page cache
   37221 ** entry.
   37222 **
   37223 ** If memory was allocated specifically to the page cache using
   37224 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   37225 ** it is desirable to avoid allocating a new page cache entry because
   37226 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   37227 ** for all page cache needs and we should not need to spill the
   37228 ** allocation onto the heap.
   37229 **
   37230 ** Or, the heap is used for all page cache memory but the heap is
   37231 ** under memory pressure, then again it is desirable to avoid
   37232 ** allocating a new page cache entry in order to avoid stressing
   37233 ** the heap even further.
   37234 */
   37235 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   37236   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   37237     return pcache1.bUnderPressure;
   37238   }else{
   37239     return sqlite3HeapNearlyFull();
   37240   }
   37241 }
   37242 
   37243 /******************************************************************************/
   37244 /******** General Implementation Functions ************************************/
   37245 
   37246 /*
   37247 ** This function is used to resize the hash table used by the cache passed
   37248 ** as the first argument.
   37249 **
   37250 ** The PCache mutex must be held when this function is called.
   37251 */
   37252 static int pcache1ResizeHash(PCache1 *p){
   37253   PgHdr1 **apNew;
   37254   unsigned int nNew;
   37255   unsigned int i;
   37256 
   37257   assert( sqlite3_mutex_held(p->pGroup->mutex) );
   37258 
   37259   nNew = p->nHash*2;
   37260   if( nNew<256 ){
   37261     nNew = 256;
   37262   }
   37263 
   37264   pcache1LeaveMutex(p->pGroup);
   37265   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   37266   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
   37267   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   37268   pcache1EnterMutex(p->pGroup);
   37269   if( apNew ){
   37270     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
   37271     for(i=0; i<p->nHash; i++){
   37272       PgHdr1 *pPage;
   37273       PgHdr1 *pNext = p->apHash[i];
   37274       while( (pPage = pNext)!=0 ){
   37275         unsigned int h = pPage->iKey % nNew;
   37276         pNext = pPage->pNext;
   37277         pPage->pNext = apNew[h];
   37278         apNew[h] = pPage;
   37279       }
   37280     }
   37281     sqlite3_free(p->apHash);
   37282     p->apHash = apNew;
   37283     p->nHash = nNew;
   37284   }
   37285 
   37286   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   37287 }
   37288 
   37289 /*
   37290 ** This function is used internally to remove the page pPage from the
   37291 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
   37292 ** LRU list, then this function is a no-op.
   37293 **
   37294 ** The PGroup mutex must be held when this function is called.
   37295 **
   37296 ** If pPage is NULL then this routine is a no-op.
   37297 */
   37298 static void pcache1PinPage(PgHdr1 *pPage){
   37299   PCache1 *pCache;
   37300   PGroup *pGroup;
   37301 
   37302   if( pPage==0 ) return;
   37303   pCache = pPage->pCache;
   37304   pGroup = pCache->pGroup;
   37305   assert( sqlite3_mutex_held(pGroup->mutex) );
   37306   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
   37307     if( pPage->pLruPrev ){
   37308       pPage->pLruPrev->pLruNext = pPage->pLruNext;
   37309     }
   37310     if( pPage->pLruNext ){
   37311       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   37312     }
   37313     if( pGroup->pLruHead==pPage ){
   37314       pGroup->pLruHead = pPage->pLruNext;
   37315     }
   37316     if( pGroup->pLruTail==pPage ){
   37317       pGroup->pLruTail = pPage->pLruPrev;
   37318     }
   37319     pPage->pLruNext = 0;
   37320     pPage->pLruPrev = 0;
   37321     pPage->pCache->nRecyclable--;
   37322   }
   37323 }
   37324 
   37325 
   37326 /*
   37327 ** Remove the page supplied as an argument from the hash table
   37328 ** (PCache1.apHash structure) that it is currently stored in.
   37329 **
   37330 ** The PGroup mutex must be held when this function is called.
   37331 */
   37332 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   37333   unsigned int h;
   37334   PCache1 *pCache = pPage->pCache;
   37335   PgHdr1 **pp;
   37336 
   37337   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37338   h = pPage->iKey % pCache->nHash;
   37339   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   37340   *pp = (*pp)->pNext;
   37341 
   37342   pCache->nPage--;
   37343 }
   37344 
   37345 /*
   37346 ** If there are currently more than nMaxPage pages allocated, try
   37347 ** to recycle pages to reduce the number allocated to nMaxPage.
   37348 */
   37349 static void pcache1EnforceMaxPage(PGroup *pGroup){
   37350   assert( sqlite3_mutex_held(pGroup->mutex) );
   37351   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
   37352     PgHdr1 *p = pGroup->pLruTail;
   37353     assert( p->pCache->pGroup==pGroup );
   37354     pcache1PinPage(p);
   37355     pcache1RemoveFromHash(p);
   37356     pcache1FreePage(p);
   37357   }
   37358 }
   37359 
   37360 /*
   37361 ** Discard all pages from cache pCache with a page number (key value)
   37362 ** greater than or equal to iLimit. Any pinned pages that meet this
   37363 ** criteria are unpinned before they are discarded.
   37364 **
   37365 ** The PCache mutex must be held when this function is called.
   37366 */
   37367 static void pcache1TruncateUnsafe(
   37368   PCache1 *pCache,             /* The cache to truncate */
   37369   unsigned int iLimit          /* Drop pages with this pgno or larger */
   37370 ){
   37371   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
   37372   unsigned int h;
   37373   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37374   for(h=0; h<pCache->nHash; h++){
   37375     PgHdr1 **pp = &pCache->apHash[h];
   37376     PgHdr1 *pPage;
   37377     while( (pPage = *pp)!=0 ){
   37378       if( pPage->iKey>=iLimit ){
   37379         pCache->nPage--;
   37380         *pp = pPage->pNext;
   37381         pcache1PinPage(pPage);
   37382         pcache1FreePage(pPage);
   37383       }else{
   37384         pp = &pPage->pNext;
   37385         TESTONLY( nPage++; )
   37386       }
   37387     }
   37388   }
   37389   assert( pCache->nPage==nPage );
   37390 }
   37391 
   37392 /******************************************************************************/
   37393 /******** sqlite3_pcache Methods **********************************************/
   37394 
   37395 /*
   37396 ** Implementation of the sqlite3_pcache.xInit method.
   37397 */
   37398 static int pcache1Init(void *NotUsed){
   37399   UNUSED_PARAMETER(NotUsed);
   37400   assert( pcache1.isInit==0 );
   37401   memset(&pcache1, 0, sizeof(pcache1));
   37402   if( sqlite3GlobalConfig.bCoreMutex ){
   37403     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   37404     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
   37405   }
   37406   pcache1.grp.mxPinned = 10;
   37407   pcache1.isInit = 1;
   37408   return SQLITE_OK;
   37409 }
   37410 
   37411 /*
   37412 ** Implementation of the sqlite3_pcache.xShutdown method.
   37413 ** Note that the static mutex allocated in xInit does
   37414 ** not need to be freed.
   37415 */
   37416 static void pcache1Shutdown(void *NotUsed){
   37417   UNUSED_PARAMETER(NotUsed);
   37418   assert( pcache1.isInit!=0 );
   37419   memset(&pcache1, 0, sizeof(pcache1));
   37420 }
   37421 
   37422 /*
   37423 ** Implementation of the sqlite3_pcache.xCreate method.
   37424 **
   37425 ** Allocate a new cache.
   37426 */
   37427 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   37428   PCache1 *pCache;      /* The newly created page cache */
   37429   PGroup *pGroup;       /* The group the new page cache will belong to */
   37430   int sz;               /* Bytes of memory required to allocate the new cache */
   37431 
   37432   /*
   37433   ** The seperateCache variable is true if each PCache has its own private
   37434   ** PGroup.  In other words, separateCache is true for mode (1) where no
   37435   ** mutexing is required.
   37436   **
   37437   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
   37438   **
   37439   **   *  Always use a unified cache in single-threaded applications
   37440   **
   37441   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
   37442   **      use separate caches (mode-1)
   37443   */
   37444 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   37445   const int separateCache = 0;
   37446 #else
   37447   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
   37448 #endif
   37449 
   37450   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
   37451   assert( szExtra < 300 );
   37452 
   37453   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
   37454   pCache = (PCache1 *)sqlite3_malloc(sz);
   37455   if( pCache ){
   37456     memset(pCache, 0, sz);
   37457     if( separateCache ){
   37458       pGroup = (PGroup*)&pCache[1];
   37459       pGroup->mxPinned = 10;
   37460     }else{
   37461       pGroup = &pcache1.grp;
   37462     }
   37463     pCache->pGroup = pGroup;
   37464     pCache->szPage = szPage;
   37465     pCache->szExtra = szExtra;
   37466     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   37467     if( bPurgeable ){
   37468       pCache->nMin = 10;
   37469       pcache1EnterMutex(pGroup);
   37470       pGroup->nMinPage += pCache->nMin;
   37471       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37472       pcache1LeaveMutex(pGroup);
   37473     }
   37474   }
   37475   return (sqlite3_pcache *)pCache;
   37476 }
   37477 
   37478 /*
   37479 ** Implementation of the sqlite3_pcache.xCachesize method.
   37480 **
   37481 ** Configure the cache_size limit for a cache.
   37482 */
   37483 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   37484   PCache1 *pCache = (PCache1 *)p;
   37485   if( pCache->bPurgeable ){
   37486     PGroup *pGroup = pCache->pGroup;
   37487     pcache1EnterMutex(pGroup);
   37488     pGroup->nMaxPage += (nMax - pCache->nMax);
   37489     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37490     pCache->nMax = nMax;
   37491     pCache->n90pct = pCache->nMax*9/10;
   37492     pcache1EnforceMaxPage(pGroup);
   37493     pcache1LeaveMutex(pGroup);
   37494   }
   37495 }
   37496 
   37497 /*
   37498 ** Implementation of the sqlite3_pcache.xShrink method.
   37499 **
   37500 ** Free up as much memory as possible.
   37501 */
   37502 static void pcache1Shrink(sqlite3_pcache *p){
   37503   PCache1 *pCache = (PCache1*)p;
   37504   if( pCache->bPurgeable ){
   37505     PGroup *pGroup = pCache->pGroup;
   37506     int savedMaxPage;
   37507     pcache1EnterMutex(pGroup);
   37508     savedMaxPage = pGroup->nMaxPage;
   37509     pGroup->nMaxPage = 0;
   37510     pcache1EnforceMaxPage(pGroup);
   37511     pGroup->nMaxPage = savedMaxPage;
   37512     pcache1LeaveMutex(pGroup);
   37513   }
   37514 }
   37515 
   37516 /*
   37517 ** Implementation of the sqlite3_pcache.xPagecount method.
   37518 */
   37519 static int pcache1Pagecount(sqlite3_pcache *p){
   37520   int n;
   37521   PCache1 *pCache = (PCache1*)p;
   37522   pcache1EnterMutex(pCache->pGroup);
   37523   n = pCache->nPage;
   37524   pcache1LeaveMutex(pCache->pGroup);
   37525   return n;
   37526 }
   37527 
   37528 /*
   37529 ** Implementation of the sqlite3_pcache.xFetch method.
   37530 **
   37531 ** Fetch a page by key value.
   37532 **
   37533 ** Whether or not a new page may be allocated by this function depends on
   37534 ** the value of the createFlag argument.  0 means do not allocate a new
   37535 ** page.  1 means allocate a new page if space is easily available.  2
   37536 ** means to try really hard to allocate a new page.
   37537 **
   37538 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   37539 ** database) there is really no difference between createFlag 1 and 2.  So
   37540 ** the calling function (pcache.c) will never have a createFlag of 1 on
   37541 ** a non-purgeable cache.
   37542 **
   37543 ** There are three different approaches to obtaining space for a page,
   37544 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   37545 **
   37546 **   1. Regardless of the value of createFlag, the cache is searched for a
   37547 **      copy of the requested page. If one is found, it is returned.
   37548 **
   37549 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   37550 **      returned.
   37551 **
   37552 **   3. If createFlag is 1, and the page is not already in the cache, then
   37553 **      return NULL (do not allocate a new page) if any of the following
   37554 **      conditions are true:
   37555 **
   37556 **       (a) the number of pages pinned by the cache is greater than
   37557 **           PCache1.nMax, or
   37558 **
   37559 **       (b) the number of pages pinned by the cache is greater than
   37560 **           the sum of nMax for all purgeable caches, less the sum of
   37561 **           nMin for all other purgeable caches, or
   37562 **
   37563 **   4. If none of the first three conditions apply and the cache is marked
   37564 **      as purgeable, and if one of the following is true:
   37565 **
   37566 **       (a) The number of pages allocated for the cache is already
   37567 **           PCache1.nMax, or
   37568 **
   37569 **       (b) The number of pages allocated for all purgeable caches is
   37570 **           already equal to or greater than the sum of nMax for all
   37571 **           purgeable caches,
   37572 **
   37573 **       (c) The system is under memory pressure and wants to avoid
   37574 **           unnecessary pages cache entry allocations
   37575 **
   37576 **      then attempt to recycle a page from the LRU list. If it is the right
   37577 **      size, return the recycled buffer. Otherwise, free the buffer and
   37578 **      proceed to step 5.
   37579 **
   37580 **   5. Otherwise, allocate and return a new page buffer.
   37581 */
   37582 static sqlite3_pcache_page *pcache1Fetch(
   37583   sqlite3_pcache *p,
   37584   unsigned int iKey,
   37585   int createFlag
   37586 ){
   37587   unsigned int nPinned;
   37588   PCache1 *pCache = (PCache1 *)p;
   37589   PGroup *pGroup;
   37590   PgHdr1 *pPage = 0;
   37591 
   37592   assert( pCache->bPurgeable || createFlag!=1 );
   37593   assert( pCache->bPurgeable || pCache->nMin==0 );
   37594   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
   37595   assert( pCache->nMin==0 || pCache->bPurgeable );
   37596   pcache1EnterMutex(pGroup = pCache->pGroup);
   37597 
   37598   /* Step 1: Search the hash table for an existing entry. */
   37599   if( pCache->nHash>0 ){
   37600     unsigned int h = iKey % pCache->nHash;
   37601     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   37602   }
   37603 
   37604   /* Step 2: Abort if no existing page is found and createFlag is 0 */
   37605   if( pPage || createFlag==0 ){
   37606     pcache1PinPage(pPage);
   37607     goto fetch_out;
   37608   }
   37609 
   37610   /* The pGroup local variable will normally be initialized by the
   37611   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
   37612   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
   37613   ** local variable here.  Delaying the initialization of pGroup is an
   37614   ** optimization:  The common case is to exit the module before reaching
   37615   ** this point.
   37616   */
   37617 #ifdef SQLITE_MUTEX_OMIT
   37618   pGroup = pCache->pGroup;
   37619 #endif
   37620 
   37621   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
   37622   assert( pCache->nPage >= pCache->nRecyclable );
   37623   nPinned = pCache->nPage - pCache->nRecyclable;
   37624   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   37625   assert( pCache->n90pct == pCache->nMax*9/10 );
   37626   if( createFlag==1 && (
   37627         nPinned>=pGroup->mxPinned
   37628      || nPinned>=pCache->n90pct
   37629      || pcache1UnderMemoryPressure(pCache)
   37630   )){
   37631     goto fetch_out;
   37632   }
   37633 
   37634   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   37635     goto fetch_out;
   37636   }
   37637 
   37638   /* Step 4. Try to recycle a page. */
   37639   if( pCache->bPurgeable && pGroup->pLruTail && (
   37640          (pCache->nPage+1>=pCache->nMax)
   37641       || pGroup->nCurrentPage>=pGroup->nMaxPage
   37642       || pcache1UnderMemoryPressure(pCache)
   37643   )){
   37644     PCache1 *pOther;
   37645     pPage = pGroup->pLruTail;
   37646     pcache1RemoveFromHash(pPage);
   37647     pcache1PinPage(pPage);
   37648     pOther = pPage->pCache;
   37649 
   37650     /* We want to verify that szPage and szExtra are the same for pOther
   37651     ** and pCache.  Assert that we can verify this by comparing sums. */
   37652     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
   37653     assert( pCache->szExtra<512 );
   37654     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
   37655     assert( pOther->szExtra<512 );
   37656 
   37657     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
   37658       pcache1FreePage(pPage);
   37659       pPage = 0;
   37660     }else{
   37661       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
   37662     }
   37663   }
   37664 
   37665   /* Step 5. If a usable page buffer has still not been found,
   37666   ** attempt to allocate a new one.
   37667   */
   37668   if( !pPage ){
   37669     if( createFlag==1 ) sqlite3BeginBenignMalloc();
   37670     pPage = pcache1AllocPage(pCache);
   37671     if( createFlag==1 ) sqlite3EndBenignMalloc();
   37672   }
   37673 
   37674   if( pPage ){
   37675     unsigned int h = iKey % pCache->nHash;
   37676     pCache->nPage++;
   37677     pPage->iKey = iKey;
   37678     pPage->pNext = pCache->apHash[h];
   37679     pPage->pCache = pCache;
   37680     pPage->pLruPrev = 0;
   37681     pPage->pLruNext = 0;
   37682     *(void **)pPage->page.pExtra = 0;
   37683     pCache->apHash[h] = pPage;
   37684   }
   37685 
   37686 fetch_out:
   37687   if( pPage && iKey>pCache->iMaxKey ){
   37688     pCache->iMaxKey = iKey;
   37689   }
   37690   pcache1LeaveMutex(pGroup);
   37691   return &pPage->page;
   37692 }
   37693 
   37694 
   37695 /*
   37696 ** Implementation of the sqlite3_pcache.xUnpin method.
   37697 **
   37698 ** Mark a page as unpinned (eligible for asynchronous recycling).
   37699 */
   37700 static void pcache1Unpin(
   37701   sqlite3_pcache *p,
   37702   sqlite3_pcache_page *pPg,
   37703   int reuseUnlikely
   37704 ){
   37705   PCache1 *pCache = (PCache1 *)p;
   37706   PgHdr1 *pPage = (PgHdr1 *)pPg;
   37707   PGroup *pGroup = pCache->pGroup;
   37708 
   37709   assert( pPage->pCache==pCache );
   37710   pcache1EnterMutex(pGroup);
   37711 
   37712   /* It is an error to call this function if the page is already
   37713   ** part of the PGroup LRU list.
   37714   */
   37715   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   37716   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
   37717 
   37718   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
   37719     pcache1RemoveFromHash(pPage);
   37720     pcache1FreePage(pPage);
   37721   }else{
   37722     /* Add the page to the PGroup LRU list. */
   37723     if( pGroup->pLruHead ){
   37724       pGroup->pLruHead->pLruPrev = pPage;
   37725       pPage->pLruNext = pGroup->pLruHead;
   37726       pGroup->pLruHead = pPage;
   37727     }else{
   37728       pGroup->pLruTail = pPage;
   37729       pGroup->pLruHead = pPage;
   37730     }
   37731     pCache->nRecyclable++;
   37732   }
   37733 
   37734   pcache1LeaveMutex(pCache->pGroup);
   37735 }
   37736 
   37737 /*
   37738 ** Implementation of the sqlite3_pcache.xRekey method.
   37739 */
   37740 static void pcache1Rekey(
   37741   sqlite3_pcache *p,
   37742   sqlite3_pcache_page *pPg,
   37743   unsigned int iOld,
   37744   unsigned int iNew
   37745 ){
   37746   PCache1 *pCache = (PCache1 *)p;
   37747   PgHdr1 *pPage = (PgHdr1 *)pPg;
   37748   PgHdr1 **pp;
   37749   unsigned int h;
   37750   assert( pPage->iKey==iOld );
   37751   assert( pPage->pCache==pCache );
   37752 
   37753   pcache1EnterMutex(pCache->pGroup);
   37754 
   37755   h = iOld%pCache->nHash;
   37756   pp = &pCache->apHash[h];
   37757   while( (*pp)!=pPage ){
   37758     pp = &(*pp)->pNext;
   37759   }
   37760   *pp = pPage->pNext;
   37761 
   37762   h = iNew%pCache->nHash;
   37763   pPage->iKey = iNew;
   37764   pPage->pNext = pCache->apHash[h];
   37765   pCache->apHash[h] = pPage;
   37766   if( iNew>pCache->iMaxKey ){
   37767     pCache->iMaxKey = iNew;
   37768   }
   37769 
   37770   pcache1LeaveMutex(pCache->pGroup);
   37771 }
   37772 
   37773 /*
   37774 ** Implementation of the sqlite3_pcache.xTruncate method.
   37775 **
   37776 ** Discard all unpinned pages in the cache with a page number equal to
   37777 ** or greater than parameter iLimit. Any pinned pages with a page number
   37778 ** equal to or greater than iLimit are implicitly unpinned.
   37779 */
   37780 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   37781   PCache1 *pCache = (PCache1 *)p;
   37782   pcache1EnterMutex(pCache->pGroup);
   37783   if( iLimit<=pCache->iMaxKey ){
   37784     pcache1TruncateUnsafe(pCache, iLimit);
   37785     pCache->iMaxKey = iLimit-1;
   37786   }
   37787   pcache1LeaveMutex(pCache->pGroup);
   37788 }
   37789 
   37790 /*
   37791 ** Implementation of the sqlite3_pcache.xDestroy method.
   37792 **
   37793 ** Destroy a cache allocated using pcache1Create().
   37794 */
   37795 static void pcache1Destroy(sqlite3_pcache *p){
   37796   PCache1 *pCache = (PCache1 *)p;
   37797   PGroup *pGroup = pCache->pGroup;
   37798   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   37799   pcache1EnterMutex(pGroup);
   37800   pcache1TruncateUnsafe(pCache, 0);
   37801   assert( pGroup->nMaxPage >= pCache->nMax );
   37802   pGroup->nMaxPage -= pCache->nMax;
   37803   assert( pGroup->nMinPage >= pCache->nMin );
   37804   pGroup->nMinPage -= pCache->nMin;
   37805   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37806   pcache1EnforceMaxPage(pGroup);
   37807   pcache1LeaveMutex(pGroup);
   37808   sqlite3_free(pCache->apHash);
   37809   sqlite3_free(pCache);
   37810 }
   37811 
   37812 /*
   37813 ** This function is called during initialization (sqlite3_initialize()) to
   37814 ** install the default pluggable cache module, assuming the user has not
   37815 ** already provided an alternative.
   37816 */
   37817 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   37818   static const sqlite3_pcache_methods2 defaultMethods = {
   37819     1,                       /* iVersion */
   37820     0,                       /* pArg */
   37821     pcache1Init,             /* xInit */
   37822     pcache1Shutdown,         /* xShutdown */
   37823     pcache1Create,           /* xCreate */
   37824     pcache1Cachesize,        /* xCachesize */
   37825     pcache1Pagecount,        /* xPagecount */
   37826     pcache1Fetch,            /* xFetch */
   37827     pcache1Unpin,            /* xUnpin */
   37828     pcache1Rekey,            /* xRekey */
   37829     pcache1Truncate,         /* xTruncate */
   37830     pcache1Destroy,          /* xDestroy */
   37831     pcache1Shrink            /* xShrink */
   37832   };
   37833   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   37834 }
   37835 
   37836 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   37837 /*
   37838 ** This function is called to free superfluous dynamically allocated memory
   37839 ** held by the pager system. Memory in use by any SQLite pager allocated
   37840 ** by the current thread may be sqlite3_free()ed.
   37841 **
   37842 ** nReq is the number of bytes of memory required. Once this much has
   37843 ** been released, the function returns. The return value is the total number
   37844 ** of bytes of memory released.
   37845 */
   37846 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   37847   int nFree = 0;
   37848   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   37849   assert( sqlite3_mutex_notheld(pcache1.mutex) );
   37850   if( pcache1.pStart==0 ){
   37851     PgHdr1 *p;
   37852     pcache1EnterMutex(&pcache1.grp);
   37853     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
   37854       nFree += pcache1MemSize(p->page.pBuf);
   37855 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37856       nFree += sqlite3MemSize(p);
   37857 #endif
   37858       pcache1PinPage(p);
   37859       pcache1RemoveFromHash(p);
   37860       pcache1FreePage(p);
   37861     }
   37862     pcache1LeaveMutex(&pcache1.grp);
   37863   }
   37864   return nFree;
   37865 }
   37866 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   37867 
   37868 #ifdef SQLITE_TEST
   37869 /*
   37870 ** This function is used by test procedures to inspect the internal state
   37871 ** of the global cache.
   37872 */
   37873 SQLITE_PRIVATE void sqlite3PcacheStats(
   37874   int *pnCurrent,      /* OUT: Total number of pages cached */
   37875   int *pnMax,          /* OUT: Global maximum cache size */
   37876   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   37877   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   37878 ){
   37879   PgHdr1 *p;
   37880   int nRecyclable = 0;
   37881   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
   37882     nRecyclable++;
   37883   }
   37884   *pnCurrent = pcache1.grp.nCurrentPage;
   37885   *pnMax = (int)pcache1.grp.nMaxPage;
   37886   *pnMin = (int)pcache1.grp.nMinPage;
   37887   *pnRecyclable = nRecyclable;
   37888 }
   37889 #endif
   37890 
   37891 /************** End of pcache1.c *********************************************/
   37892 /************** Begin file rowset.c ******************************************/
   37893 /*
   37894 ** 2008 December 3
   37895 **
   37896 ** The author disclaims copyright to this source code.  In place of
   37897 ** a legal notice, here is a blessing:
   37898 **
   37899 **    May you do good and not evil.
   37900 **    May you find forgiveness for yourself and forgive others.
   37901 **    May you share freely, never taking more than you give.
   37902 **
   37903 *************************************************************************
   37904 **
   37905 ** This module implements an object we call a "RowSet".
   37906 **
   37907 ** The RowSet object is a collection of rowids.  Rowids
   37908 ** are inserted into the RowSet in an arbitrary order.  Inserts
   37909 ** can be intermixed with tests to see if a given rowid has been
   37910 ** previously inserted into the RowSet.
   37911 **
   37912 ** After all inserts are finished, it is possible to extract the
   37913 ** elements of the RowSet in sorted order.  Once this extraction
   37914 ** process has started, no new elements may be inserted.
   37915 **
   37916 ** Hence, the primitive operations for a RowSet are:
   37917 **
   37918 **    CREATE
   37919 **    INSERT
   37920 **    TEST
   37921 **    SMALLEST
   37922 **    DESTROY
   37923 **
   37924 ** The CREATE and DESTROY primitives are the constructor and destructor,
   37925 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   37926 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   37927 ** extracts the least value from the RowSet.
   37928 **
   37929 ** The INSERT primitive might allocate additional memory.  Memory is
   37930 ** allocated in chunks so most INSERTs do no allocation.  There is an
   37931 ** upper bound on the size of allocated memory.  No memory is freed
   37932 ** until DESTROY.
   37933 **
   37934 ** The TEST primitive includes a "batch" number.  The TEST primitive
   37935 ** will only see elements that were inserted before the last change
   37936 ** in the batch number.  In other words, if an INSERT occurs between
   37937 ** two TESTs where the TESTs have the same batch nubmer, then the
   37938 ** value added by the INSERT will not be visible to the second TEST.
   37939 ** The initial batch number is zero, so if the very first TEST contains
   37940 ** a non-zero batch number, it will see all prior INSERTs.
   37941 **
   37942 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   37943 ** that is attempted.
   37944 **
   37945 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   37946 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   37947 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   37948 ** The cost of a TEST using the same batch number is O(logN).  The cost
   37949 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   37950 ** primitives are constant time.  The cost of DESTROY is O(N).
   37951 **
   37952 ** There is an added cost of O(N) when switching between TEST and
   37953 ** SMALLEST primitives.
   37954 */
   37955 
   37956 
   37957 /*
   37958 ** Target size for allocation chunks.
   37959 */
   37960 #define ROWSET_ALLOCATION_SIZE 1024
   37961 
   37962 /*
   37963 ** The number of rowset entries per allocation chunk.
   37964 */
   37965 #define ROWSET_ENTRY_PER_CHUNK  \
   37966                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   37967 
   37968 /*
   37969 ** Each entry in a RowSet is an instance of the following object.
   37970 */
   37971 struct RowSetEntry {
   37972   i64 v;                        /* ROWID value for this entry */
   37973   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   37974   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   37975 };
   37976 
   37977 /*
   37978 ** RowSetEntry objects are allocated in large chunks (instances of the
   37979 ** following structure) to reduce memory allocation overhead.  The
   37980 ** chunks are kept on a linked list so that they can be deallocated
   37981 ** when the RowSet is destroyed.
   37982 */
   37983 struct RowSetChunk {
   37984   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   37985   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   37986 };
   37987 
   37988 /*
   37989 ** A RowSet in an instance of the following structure.
   37990 **
   37991 ** A typedef of this structure if found in sqliteInt.h.
   37992 */
   37993 struct RowSet {
   37994   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   37995   sqlite3 *db;                   /* The database connection */
   37996   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   37997   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   37998   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   37999   struct RowSetEntry *pTree;     /* Binary tree of entries */
   38000   u16 nFresh;                    /* Number of objects on pFresh */
   38001   u8 isSorted;                   /* True if pEntry is sorted */
   38002   u8 iBatch;                     /* Current insert batch */
   38003 };
   38004 
   38005 /*
   38006 ** Turn bulk memory into a RowSet object.  N bytes of memory
   38007 ** are available at pSpace.  The db pointer is used as a memory context
   38008 ** for any subsequent allocations that need to occur.
   38009 ** Return a pointer to the new RowSet object.
   38010 **
   38011 ** It must be the case that N is sufficient to make a Rowset.  If not
   38012 ** an assertion fault occurs.
   38013 **
   38014 ** If N is larger than the minimum, use the surplus as an initial
   38015 ** allocation of entries available to be filled.
   38016 */
   38017 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   38018   RowSet *p;
   38019   assert( N >= ROUND8(sizeof(*p)) );
   38020   p = pSpace;
   38021   p->pChunk = 0;
   38022   p->db = db;
   38023   p->pEntry = 0;
   38024   p->pLast = 0;
   38025   p->pTree = 0;
   38026   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   38027   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   38028   p->isSorted = 1;
   38029   p->iBatch = 0;
   38030   return p;
   38031 }
   38032 
   38033 /*
   38034 ** Deallocate all chunks from a RowSet.  This frees all memory that
   38035 ** the RowSet has allocated over its lifetime.  This routine is
   38036 ** the destructor for the RowSet.
   38037 */
   38038 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   38039   struct RowSetChunk *pChunk, *pNextChunk;
   38040   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   38041     pNextChunk = pChunk->pNextChunk;
   38042     sqlite3DbFree(p->db, pChunk);
   38043   }
   38044   p->pChunk = 0;
   38045   p->nFresh = 0;
   38046   p->pEntry = 0;
   38047   p->pLast = 0;
   38048   p->pTree = 0;
   38049   p->isSorted = 1;
   38050 }
   38051 
   38052 /*
   38053 ** Insert a new value into a RowSet.
   38054 **
   38055 ** The mallocFailed flag of the database connection is set if a
   38056 ** memory allocation fails.
   38057 */
   38058 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   38059   struct RowSetEntry *pEntry;  /* The new entry */
   38060   struct RowSetEntry *pLast;   /* The last prior entry */
   38061   assert( p!=0 );
   38062   if( p->nFresh==0 ){
   38063     struct RowSetChunk *pNew;
   38064     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   38065     if( pNew==0 ){
   38066       return;
   38067     }
   38068     pNew->pNextChunk = p->pChunk;
   38069     p->pChunk = pNew;
   38070     p->pFresh = pNew->aEntry;
   38071     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   38072   }
   38073   pEntry = p->pFresh++;
   38074   p->nFresh--;
   38075   pEntry->v = rowid;
   38076   pEntry->pRight = 0;
   38077   pLast = p->pLast;
   38078   if( pLast ){
   38079     if( p->isSorted && rowid<=pLast->v ){
   38080       p->isSorted = 0;
   38081     }
   38082     pLast->pRight = pEntry;
   38083   }else{
   38084     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
   38085     p->pEntry = pEntry;
   38086   }
   38087   p->pLast = pEntry;
   38088 }
   38089 
   38090 /*
   38091 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   38092 **
   38093 ** The input lists are connected via pRight pointers and are
   38094 ** assumed to each already be in sorted order.
   38095 */
   38096 static struct RowSetEntry *rowSetMerge(
   38097   struct RowSetEntry *pA,    /* First sorted list to be merged */
   38098   struct RowSetEntry *pB     /* Second sorted list to be merged */
   38099 ){
   38100   struct RowSetEntry head;
   38101   struct RowSetEntry *pTail;
   38102 
   38103   pTail = &head;
   38104   while( pA && pB ){
   38105     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   38106     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   38107     if( pA->v<pB->v ){
   38108       pTail->pRight = pA;
   38109       pA = pA->pRight;
   38110       pTail = pTail->pRight;
   38111     }else if( pB->v<pA->v ){
   38112       pTail->pRight = pB;
   38113       pB = pB->pRight;
   38114       pTail = pTail->pRight;
   38115     }else{
   38116       pA = pA->pRight;
   38117     }
   38118   }
   38119   if( pA ){
   38120     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   38121     pTail->pRight = pA;
   38122   }else{
   38123     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   38124     pTail->pRight = pB;
   38125   }
   38126   return head.pRight;
   38127 }
   38128 
   38129 /*
   38130 ** Sort all elements on the pEntry list of the RowSet into ascending order.
   38131 */
   38132 static void rowSetSort(RowSet *p){
   38133   unsigned int i;
   38134   struct RowSetEntry *pEntry;
   38135   struct RowSetEntry *aBucket[40];
   38136 
   38137   assert( p->isSorted==0 );
   38138   memset(aBucket, 0, sizeof(aBucket));
   38139   while( p->pEntry ){
   38140     pEntry = p->pEntry;
   38141     p->pEntry = pEntry->pRight;
   38142     pEntry->pRight = 0;
   38143     for(i=0; aBucket[i]; i++){
   38144       pEntry = rowSetMerge(aBucket[i], pEntry);
   38145       aBucket[i] = 0;
   38146     }
   38147     aBucket[i] = pEntry;
   38148   }
   38149   pEntry = 0;
   38150   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   38151     pEntry = rowSetMerge(pEntry, aBucket[i]);
   38152   }
   38153   p->pEntry = pEntry;
   38154   p->pLast = 0;
   38155   p->isSorted = 1;
   38156 }
   38157 
   38158 
   38159 /*
   38160 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   38161 ** Convert this tree into a linked list connected by the pRight pointers
   38162 ** and return pointers to the first and last elements of the new list.
   38163 */
   38164 static void rowSetTreeToList(
   38165   struct RowSetEntry *pIn,         /* Root of the input tree */
   38166   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   38167   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   38168 ){
   38169   assert( pIn!=0 );
   38170   if( pIn->pLeft ){
   38171     struct RowSetEntry *p;
   38172     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   38173     p->pRight = pIn;
   38174   }else{
   38175     *ppFirst = pIn;
   38176   }
   38177   if( pIn->pRight ){
   38178     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   38179   }else{
   38180     *ppLast = pIn;
   38181   }
   38182   assert( (*ppLast)->pRight==0 );
   38183 }
   38184 
   38185 
   38186 /*
   38187 ** Convert a sorted list of elements (connected by pRight) into a binary
   38188 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   38189 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   38190 ** three nodes.  And so forth.
   38191 **
   38192 ** Use as many entries from the input list as required and update the
   38193 ** *ppList to point to the unused elements of the list.  If the input
   38194 ** list contains too few elements, then construct an incomplete tree
   38195 ** and leave *ppList set to NULL.
   38196 **
   38197 ** Return a pointer to the root of the constructed binary tree.
   38198 */
   38199 static struct RowSetEntry *rowSetNDeepTree(
   38200   struct RowSetEntry **ppList,
   38201   int iDepth
   38202 ){
   38203   struct RowSetEntry *p;         /* Root of the new tree */
   38204   struct RowSetEntry *pLeft;     /* Left subtree */
   38205   if( *ppList==0 ){
   38206     return 0;
   38207   }
   38208   if( iDepth==1 ){
   38209     p = *ppList;
   38210     *ppList = p->pRight;
   38211     p->pLeft = p->pRight = 0;
   38212     return p;
   38213   }
   38214   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   38215   p = *ppList;
   38216   if( p==0 ){
   38217     return pLeft;
   38218   }
   38219   p->pLeft = pLeft;
   38220   *ppList = p->pRight;
   38221   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   38222   return p;
   38223 }
   38224 
   38225 /*
   38226 ** Convert a sorted list of elements into a binary tree. Make the tree
   38227 ** as deep as it needs to be in order to contain the entire list.
   38228 */
   38229 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   38230   int iDepth;           /* Depth of the tree so far */
   38231   struct RowSetEntry *p;       /* Current tree root */
   38232   struct RowSetEntry *pLeft;   /* Left subtree */
   38233 
   38234   assert( pList!=0 );
   38235   p = pList;
   38236   pList = p->pRight;
   38237   p->pLeft = p->pRight = 0;
   38238   for(iDepth=1; pList; iDepth++){
   38239     pLeft = p;
   38240     p = pList;
   38241     pList = p->pRight;
   38242     p->pLeft = pLeft;
   38243     p->pRight = rowSetNDeepTree(&pList, iDepth);
   38244   }
   38245   return p;
   38246 }
   38247 
   38248 /*
   38249 ** Convert the list in p->pEntry into a sorted list if it is not
   38250 ** sorted already.  If there is a binary tree on p->pTree, then
   38251 ** convert it into a list too and merge it into the p->pEntry list.
   38252 */
   38253 static void rowSetToList(RowSet *p){
   38254   if( !p->isSorted ){
   38255     rowSetSort(p);
   38256   }
   38257   if( p->pTree ){
   38258     struct RowSetEntry *pHead, *pTail;
   38259     rowSetTreeToList(p->pTree, &pHead, &pTail);
   38260     p->pTree = 0;
   38261     p->pEntry = rowSetMerge(p->pEntry, pHead);
   38262   }
   38263 }
   38264 
   38265 /*
   38266 ** Extract the smallest element from the RowSet.
   38267 ** Write the element into *pRowid.  Return 1 on success.  Return
   38268 ** 0 if the RowSet is already empty.
   38269 **
   38270 ** After this routine has been called, the sqlite3RowSetInsert()
   38271 ** routine may not be called again.
   38272 */
   38273 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   38274   rowSetToList(p);
   38275   if( p->pEntry ){
   38276     *pRowid = p->pEntry->v;
   38277     p->pEntry = p->pEntry->pRight;
   38278     if( p->pEntry==0 ){
   38279       sqlite3RowSetClear(p);
   38280     }
   38281     return 1;
   38282   }else{
   38283     return 0;
   38284   }
   38285 }
   38286 
   38287 /*
   38288 ** Check to see if element iRowid was inserted into the the rowset as
   38289 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   38290 */
   38291 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
   38292   struct RowSetEntry *p;
   38293   if( iBatch!=pRowSet->iBatch ){
   38294     if( pRowSet->pEntry ){
   38295       rowSetToList(pRowSet);
   38296       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
   38297       pRowSet->pEntry = 0;
   38298       pRowSet->pLast = 0;
   38299     }
   38300     pRowSet->iBatch = iBatch;
   38301   }
   38302   p = pRowSet->pTree;
   38303   while( p ){
   38304     if( p->v<iRowid ){
   38305       p = p->pRight;
   38306     }else if( p->v>iRowid ){
   38307       p = p->pLeft;
   38308     }else{
   38309       return 1;
   38310     }
   38311   }
   38312   return 0;
   38313 }
   38314 
   38315 /************** End of rowset.c **********************************************/
   38316 /************** Begin file pager.c *******************************************/
   38317 /*
   38318 ** 2001 September 15
   38319 **
   38320 ** The author disclaims copyright to this source code.  In place of
   38321 ** a legal notice, here is a blessing:
   38322 **
   38323 **    May you do good and not evil.
   38324 **    May you find forgiveness for yourself and forgive others.
   38325 **    May you share freely, never taking more than you give.
   38326 **
   38327 *************************************************************************
   38328 ** This is the implementation of the page cache subsystem or "pager".
   38329 **
   38330 ** The pager is used to access a database disk file.  It implements
   38331 ** atomic commit and rollback through the use of a journal file that
   38332 ** is separate from the database file.  The pager also implements file
   38333 ** locking to prevent two processes from writing the same database
   38334 ** file simultaneously, or one process from reading the database while
   38335 ** another is writing.
   38336 */
   38337 #ifndef SQLITE_OMIT_DISKIO
   38338 /************** Include wal.h in the middle of pager.c ***********************/
   38339 /************** Begin file wal.h *********************************************/
   38340 /*
   38341 ** 2010 February 1
   38342 **
   38343 ** The author disclaims copyright to this source code.  In place of
   38344 ** a legal notice, here is a blessing:
   38345 **
   38346 **    May you do good and not evil.
   38347 **    May you find forgiveness for yourself and forgive others.
   38348 **    May you share freely, never taking more than you give.
   38349 **
   38350 *************************************************************************
   38351 ** This header file defines the interface to the write-ahead logging
   38352 ** system. Refer to the comments below and the header comment attached to
   38353 ** the implementation of each function in log.c for further details.
   38354 */
   38355 
   38356 #ifndef _WAL_H_
   38357 #define _WAL_H_
   38358 
   38359 
   38360 /* Additional values that can be added to the sync_flags argument of
   38361 ** sqlite3WalFrames():
   38362 */
   38363 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
   38364 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
   38365 
   38366 #ifdef SQLITE_OMIT_WAL
   38367 # define sqlite3WalOpen(x,y,z)                   0
   38368 # define sqlite3WalLimit(x,y)
   38369 # define sqlite3WalClose(w,x,y,z)                0
   38370 # define sqlite3WalBeginReadTransaction(y,z)     0
   38371 # define sqlite3WalEndReadTransaction(z)
   38372 # define sqlite3WalRead(v,w,x,y,z)               0
   38373 # define sqlite3WalDbsize(y)                     0
   38374 # define sqlite3WalBeginWriteTransaction(y)      0
   38375 # define sqlite3WalEndWriteTransaction(x)        0
   38376 # define sqlite3WalUndo(x,y,z)                   0
   38377 # define sqlite3WalSavepoint(y,z)
   38378 # define sqlite3WalSavepointUndo(y,z)            0
   38379 # define sqlite3WalFrames(u,v,w,x,y,z)           0
   38380 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
   38381 # define sqlite3WalCallback(z)                   0
   38382 # define sqlite3WalExclusiveMode(y,z)            0
   38383 # define sqlite3WalHeapMemory(z)                 0
   38384 # define sqlite3WalFramesize(z)                  0
   38385 #else
   38386 
   38387 #define WAL_SAVEPOINT_NDATA 4
   38388 
   38389 /* Connection to a write-ahead log (WAL) file.
   38390 ** There is one object of this type for each pager.
   38391 */
   38392 typedef struct Wal Wal;
   38393 
   38394 /* Open and close a connection to a write-ahead log. */
   38395 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
   38396 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
   38397 
   38398 /* Set the limiting size of a WAL file. */
   38399 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
   38400 
   38401 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   38402 ** snapshot is like a read-transaction.  It is the state of the database
   38403 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   38404 ** preserves the current state even if the other threads or processes
   38405 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   38406 ** transaction and releases the lock.
   38407 */
   38408 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   38409 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   38410 
   38411 /* Read a page from the write-ahead log, if it is present. */
   38412 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
   38413 
   38414 /* If the WAL is not empty, return the size of the database. */
   38415 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   38416 
   38417 /* Obtain or release the WRITER lock. */
   38418 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   38419 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   38420 
   38421 /* Undo any frames written (but not committed) to the log */
   38422 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   38423 
   38424 /* Return an integer that records the current (uncommitted) write
   38425 ** position in the WAL */
   38426 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   38427 
   38428 /* Move the write position of the WAL back to iFrame.  Called in
   38429 ** response to a ROLLBACK TO command. */
   38430 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   38431 
   38432 /* Write a frame or frames to the log. */
   38433 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   38434 
   38435 /* Copy pages from the log to the database file */
   38436 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   38437   Wal *pWal,                      /* Write-ahead log connection */
   38438   int eMode,                      /* One of PASSIVE, FULL and RESTART */
   38439   int (*xBusy)(void*),            /* Function to call when busy */
   38440   void *pBusyArg,                 /* Context argument for xBusyHandler */
   38441   int sync_flags,                 /* Flags to sync db file with (or 0) */
   38442   int nBuf,                       /* Size of buffer nBuf */
   38443   u8 *zBuf,                       /* Temporary buffer to use */
   38444   int *pnLog,                     /* OUT: Number of frames in WAL */
   38445   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   38446 );
   38447 
   38448 /* Return the value to pass to a sqlite3_wal_hook callback, the
   38449 ** number of frames in the WAL at the point of the last commit since
   38450 ** sqlite3WalCallback() was called.  If no commits have occurred since
   38451 ** the last call, then return 0.
   38452 */
   38453 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   38454 
   38455 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   38456 ** by the pager layer on the database file.
   38457 */
   38458 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   38459 
   38460 /* Return true if the argument is non-NULL and the WAL module is using
   38461 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   38462 ** WAL module is using shared-memory, return false.
   38463 */
   38464 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   38465 
   38466 #ifdef SQLITE_ENABLE_ZIPVFS
   38467 /* If the WAL file is not empty, return the number of bytes of content
   38468 ** stored in each frame (i.e. the db page-size when the WAL was created).
   38469 */
   38470 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
   38471 #endif
   38472 
   38473 #endif /* ifndef SQLITE_OMIT_WAL */
   38474 #endif /* _WAL_H_ */
   38475 
   38476 /************** End of wal.h *************************************************/
   38477 /************** Continuing where we left off in pager.c **********************/
   38478 
   38479 
   38480 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   38481 **
   38482 ** This comment block describes invariants that hold when using a rollback
   38483 ** journal.  These invariants do not apply for journal_mode=WAL,
   38484 ** journal_mode=MEMORY, or journal_mode=OFF.
   38485 **
   38486 ** Within this comment block, a page is deemed to have been synced
   38487 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   38488 ** Otherwise, the page is not synced until the xSync method of the VFS
   38489 ** is called successfully on the file containing the page.
   38490 **
   38491 ** Definition:  A page of the database file is said to be "overwriteable" if
   38492 ** one or more of the following are true about the page:
   38493 **
   38494 **     (a)  The original content of the page as it was at the beginning of
   38495 **          the transaction has been written into the rollback journal and
   38496 **          synced.
   38497 **
   38498 **     (b)  The page was a freelist leaf page at the start of the transaction.
   38499 **
   38500 **     (c)  The page number is greater than the largest page that existed in
   38501 **          the database file at the start of the transaction.
   38502 **
   38503 ** (1) A page of the database file is never overwritten unless one of the
   38504 **     following are true:
   38505 **
   38506 **     (a) The page and all other pages on the same sector are overwriteable.
   38507 **
   38508 **     (b) The atomic page write optimization is enabled, and the entire
   38509 **         transaction other than the update of the transaction sequence
   38510 **         number consists of a single page change.
   38511 **
   38512 ** (2) The content of a page written into the rollback journal exactly matches
   38513 **     both the content in the database when the rollback journal was written
   38514 **     and the content in the database at the beginning of the current
   38515 **     transaction.
   38516 **
   38517 ** (3) Writes to the database file are an integer multiple of the page size
   38518 **     in length and are aligned on a page boundary.
   38519 **
   38520 ** (4) Reads from the database file are either aligned on a page boundary and
   38521 **     an integer multiple of the page size in length or are taken from the
   38522 **     first 100 bytes of the database file.
   38523 **
   38524 ** (5) All writes to the database file are synced prior to the rollback journal
   38525 **     being deleted, truncated, or zeroed.
   38526 **
   38527 ** (6) If a master journal file is used, then all writes to the database file
   38528 **     are synced prior to the master journal being deleted.
   38529 **
   38530 ** Definition: Two databases (or the same database at two points it time)
   38531 ** are said to be "logically equivalent" if they give the same answer to
   38532 ** all queries.  Note in particular the the content of freelist leaf
   38533 ** pages can be changed arbitarily without effecting the logical equivalence
   38534 ** of the database.
   38535 **
   38536 ** (7) At any time, if any subset, including the empty set and the total set,
   38537 **     of the unsynced changes to a rollback journal are removed and the
   38538 **     journal is rolled back, the resulting database file will be logical
   38539 **     equivalent to the database file at the beginning of the transaction.
   38540 **
   38541 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   38542 **     is called to restore the database file to the same size it was at
   38543 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   38544 **     method is a no-op, but that does not change the fact the SQLite will
   38545 **     invoke it.)
   38546 **
   38547 ** (9) Whenever the database file is modified, at least one bit in the range
   38548 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   38549 **     the EXCLUSIVE lock, thus signaling other connections on the same
   38550 **     database to flush their caches.
   38551 **
   38552 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   38553 **      than one billion transactions.
   38554 **
   38555 ** (11) A database file is well-formed at the beginning and at the conclusion
   38556 **      of every transaction.
   38557 **
   38558 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   38559 **      the database file.
   38560 **
   38561 ** (13) A SHARED lock is held on the database file while reading any
   38562 **      content out of the database file.
   38563 **
   38564 ******************************************************************************/
   38565 
   38566 /*
   38567 ** Macros for troubleshooting.  Normally turned off
   38568 */
   38569 #if 0
   38570 int sqlite3PagerTrace=1;  /* True to enable tracing */
   38571 #define sqlite3DebugPrintf printf
   38572 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   38573 #else
   38574 #define PAGERTRACE(X)
   38575 #endif
   38576 
   38577 /*
   38578 ** The following two macros are used within the PAGERTRACE() macros above
   38579 ** to print out file-descriptors.
   38580 **
   38581 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   38582 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   38583 ** struct as its argument.
   38584 */
   38585 #define PAGERID(p) ((int)(p->fd))
   38586 #define FILEHANDLEID(fd) ((int)fd)
   38587 
   38588 /*
   38589 ** The Pager.eState variable stores the current 'state' of a pager. A
   38590 ** pager may be in any one of the seven states shown in the following
   38591 ** state diagram.
   38592 **
   38593 **                            OPEN <------+------+
   38594 **                              |         |      |
   38595 **                              V         |      |
   38596 **               +---------> READER-------+      |
   38597 **               |              |                |
   38598 **               |              V                |
   38599 **               |<-------WRITER_LOCKED------> ERROR
   38600 **               |              |                ^
   38601 **               |              V                |
   38602 **               |<------WRITER_CACHEMOD-------->|
   38603 **               |              |                |
   38604 **               |              V                |
   38605 **               |<-------WRITER_DBMOD---------->|
   38606 **               |              |                |
   38607 **               |              V                |
   38608 **               +<------WRITER_FINISHED-------->+
   38609 **
   38610 **
   38611 ** List of state transitions and the C [function] that performs each:
   38612 **
   38613 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   38614 **   READER            -> OPEN                [pager_unlock]
   38615 **
   38616 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   38617 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   38618 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   38619 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   38620 **   WRITER_***        -> READER              [pager_end_transaction]
   38621 **
   38622 **   WRITER_***        -> ERROR               [pager_error]
   38623 **   ERROR             -> OPEN                [pager_unlock]
   38624 **
   38625 **
   38626 **  OPEN:
   38627 **
   38628 **    The pager starts up in this state. Nothing is guaranteed in this
   38629 **    state - the file may or may not be locked and the database size is
   38630 **    unknown. The database may not be read or written.
   38631 **
   38632 **    * No read or write transaction is active.
   38633 **    * Any lock, or no lock at all, may be held on the database file.
   38634 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   38635 **
   38636 **  READER:
   38637 **
   38638 **    In this state all the requirements for reading the database in
   38639 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   38640 **    was) in exclusive-locking mode, a user-level read transaction is
   38641 **    open. The database size is known in this state.
   38642 **
   38643 **    A connection running with locking_mode=normal enters this state when
   38644 **    it opens a read-transaction on the database and returns to state
   38645 **    OPEN after the read-transaction is completed. However a connection
   38646 **    running in locking_mode=exclusive (including temp databases) remains in
   38647 **    this state even after the read-transaction is closed. The only way
   38648 **    a locking_mode=exclusive connection can transition from READER to OPEN
   38649 **    is via the ERROR state (see below).
   38650 **
   38651 **    * A read transaction may be active (but a write-transaction cannot).
   38652 **    * A SHARED or greater lock is held on the database file.
   38653 **    * The dbSize variable may be trusted (even if a user-level read
   38654 **      transaction is not active). The dbOrigSize and dbFileSize variables
   38655 **      may not be trusted at this point.
   38656 **    * If the database is a WAL database, then the WAL connection is open.
   38657 **    * Even if a read-transaction is not open, it is guaranteed that
   38658 **      there is no hot-journal in the file-system.
   38659 **
   38660 **  WRITER_LOCKED:
   38661 **
   38662 **    The pager moves to this state from READER when a write-transaction
   38663 **    is first opened on the database. In WRITER_LOCKED state, all locks
   38664 **    required to start a write-transaction are held, but no actual
   38665 **    modifications to the cache or database have taken place.
   38666 **
   38667 **    In rollback mode, a RESERVED or (if the transaction was opened with
   38668 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   38669 **    moving to this state, but the journal file is not written to or opened
   38670 **    to in this state. If the transaction is committed or rolled back while
   38671 **    in WRITER_LOCKED state, all that is required is to unlock the database
   38672 **    file.
   38673 **
   38674 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   38675 **    If the connection is running with locking_mode=exclusive, an attempt
   38676 **    is made to obtain an EXCLUSIVE lock on the database file.
   38677 **
   38678 **    * A write transaction is active.
   38679 **    * If the connection is open in rollback-mode, a RESERVED or greater
   38680 **      lock is held on the database file.
   38681 **    * If the connection is open in WAL-mode, a WAL write transaction
   38682 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   38683 **      called).
   38684 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   38685 **    * The contents of the pager cache have not been modified.
   38686 **    * The journal file may or may not be open.
   38687 **    * Nothing (not even the first header) has been written to the journal.
   38688 **
   38689 **  WRITER_CACHEMOD:
   38690 **
   38691 **    A pager moves from WRITER_LOCKED state to this state when a page is
   38692 **    first modified by the upper layer. In rollback mode the journal file
   38693 **    is opened (if it is not already open) and a header written to the
   38694 **    start of it. The database file on disk has not been modified.
   38695 **
   38696 **    * A write transaction is active.
   38697 **    * A RESERVED or greater lock is held on the database file.
   38698 **    * The journal file is open and the first header has been written
   38699 **      to it, but the header has not been synced to disk.
   38700 **    * The contents of the page cache have been modified.
   38701 **
   38702 **  WRITER_DBMOD:
   38703 **
   38704 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   38705 **    when it modifies the contents of the database file. WAL connections
   38706 **    never enter this state (since they do not modify the database file,
   38707 **    just the log file).
   38708 **
   38709 **    * A write transaction is active.
   38710 **    * An EXCLUSIVE or greater lock is held on the database file.
   38711 **    * The journal file is open and the first header has been written
   38712 **      and synced to disk.
   38713 **    * The contents of the page cache have been modified (and possibly
   38714 **      written to disk).
   38715 **
   38716 **  WRITER_FINISHED:
   38717 **
   38718 **    It is not possible for a WAL connection to enter this state.
   38719 **
   38720 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   38721 **    state after the entire transaction has been successfully written into the
   38722 **    database file. In this state the transaction may be committed simply
   38723 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   38724 **    not possible to modify the database further. At this point, the upper
   38725 **    layer must either commit or rollback the transaction.
   38726 **
   38727 **    * A write transaction is active.
   38728 **    * An EXCLUSIVE or greater lock is held on the database file.
   38729 **    * All writing and syncing of journal and database data has finished.
   38730 **      If no error occured, all that remains is to finalize the journal to
   38731 **      commit the transaction. If an error did occur, the caller will need
   38732 **      to rollback the transaction.
   38733 **
   38734 **  ERROR:
   38735 **
   38736 **    The ERROR state is entered when an IO or disk-full error (including
   38737 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   38738 **    difficult to be sure that the in-memory pager state (cache contents,
   38739 **    db size etc.) are consistent with the contents of the file-system.
   38740 **
   38741 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   38742 **    cannot.
   38743 **
   38744 **    For example, if an IO error occurs while performing a rollback,
   38745 **    the contents of the page-cache may be left in an inconsistent state.
   38746 **    At this point it would be dangerous to change back to READER state
   38747 **    (as usually happens after a rollback). Any subsequent readers might
   38748 **    report database corruption (due to the inconsistent cache), and if
   38749 **    they upgrade to writers, they may inadvertently corrupt the database
   38750 **    file. To avoid this hazard, the pager switches into the ERROR state
   38751 **    instead of READER following such an error.
   38752 **
   38753 **    Once it has entered the ERROR state, any attempt to use the pager
   38754 **    to read or write data returns an error. Eventually, once all
   38755 **    outstanding transactions have been abandoned, the pager is able to
   38756 **    transition back to OPEN state, discarding the contents of the
   38757 **    page-cache and any other in-memory state at the same time. Everything
   38758 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   38759 **    when a read-transaction is next opened on the pager (transitioning
   38760 **    the pager into READER state). At that point the system has recovered
   38761 **    from the error.
   38762 **
   38763 **    Specifically, the pager jumps into the ERROR state if:
   38764 **
   38765 **      1. An error occurs while attempting a rollback. This happens in
   38766 **         function sqlite3PagerRollback().
   38767 **
   38768 **      2. An error occurs while attempting to finalize a journal file
   38769 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   38770 **
   38771 **      3. An error occurs while attempting to write to the journal or
   38772 **         database file in function pagerStress() in order to free up
   38773 **         memory.
   38774 **
   38775 **    In other cases, the error is returned to the b-tree layer. The b-tree
   38776 **    layer then attempts a rollback operation. If the error condition
   38777 **    persists, the pager enters the ERROR state via condition (1) above.
   38778 **
   38779 **    Condition (3) is necessary because it can be triggered by a read-only
   38780 **    statement executed within a transaction. In this case, if the error
   38781 **    code were simply returned to the user, the b-tree layer would not
   38782 **    automatically attempt a rollback, as it assumes that an error in a
   38783 **    read-only statement cannot leave the pager in an internally inconsistent
   38784 **    state.
   38785 **
   38786 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   38787 **    * There are one or more outstanding references to pages (after the
   38788 **      last reference is dropped the pager should move back to OPEN state).
   38789 **    * The pager is not an in-memory pager.
   38790 **
   38791 **
   38792 ** Notes:
   38793 **
   38794 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   38795 **     connection is open in WAL mode. A WAL connection is always in one
   38796 **     of the first four states.
   38797 **
   38798 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   38799 **     state. There are two exceptions: immediately after exclusive-mode has
   38800 **     been turned on (and before any read or write transactions are
   38801 **     executed), and when the pager is leaving the "error state".
   38802 **
   38803 **   * See also: assert_pager_state().
   38804 */
   38805 #define PAGER_OPEN                  0
   38806 #define PAGER_READER                1
   38807 #define PAGER_WRITER_LOCKED         2
   38808 #define PAGER_WRITER_CACHEMOD       3
   38809 #define PAGER_WRITER_DBMOD          4
   38810 #define PAGER_WRITER_FINISHED       5
   38811 #define PAGER_ERROR                 6
   38812 
   38813 /*
   38814 ** The Pager.eLock variable is almost always set to one of the
   38815 ** following locking-states, according to the lock currently held on
   38816 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   38817 ** This variable is kept up to date as locks are taken and released by
   38818 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   38819 **
   38820 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   38821 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   38822 ** the operation was successful. In these circumstances pagerLockDb() and
   38823 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   38824 ** when unlocking the file, and only updated when locking the file if the
   38825 ** VFS call is successful. This way, the Pager.eLock variable may be set
   38826 ** to a less exclusive (lower) value than the lock that is actually held
   38827 ** at the system level, but it is never set to a more exclusive value.
   38828 **
   38829 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   38830 ** be a few redundant xLock() calls or a lock may be held for longer than
   38831 ** required, but nothing really goes wrong.
   38832 **
   38833 ** The exception is when the database file is unlocked as the pager moves
   38834 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   38835 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
   38836 ** transition, by the same pager or any other). If the call to xUnlock()
   38837 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   38838 ** can confuse the call to xCheckReservedLock() call made later as part
   38839 ** of hot-journal detection.
   38840 **
   38841 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   38842 ** lock held by this process or any others". So xCheckReservedLock may
   38843 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   38844 ** doesn't know it because of a previous error in xUnlock). If this happens
   38845 ** a hot-journal may be mistaken for a journal being created by an active
   38846 ** transaction in another process, causing SQLite to read from the database
   38847 ** without rolling it back.
   38848 **
   38849 ** To work around this, if a call to xUnlock() fails when unlocking the
   38850 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   38851 ** is only changed back to a real locking state after a successful call
   38852 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   38853 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   38854 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   38855 ** lock on the database file before attempting to roll it back. See function
   38856 ** PagerSharedLock() for more detail.
   38857 **
   38858 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   38859 ** PAGER_OPEN state.
   38860 */
   38861 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   38862 
   38863 /*
   38864 ** A macro used for invoking the codec if there is one
   38865 */
   38866 #ifdef SQLITE_HAS_CODEC
   38867 # define CODEC1(P,D,N,X,E) \
   38868     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   38869 # define CODEC2(P,D,N,X,E,O) \
   38870     if( P->xCodec==0 ){ O=(char*)D; }else \
   38871     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   38872 #else
   38873 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   38874 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   38875 #endif
   38876 
   38877 /*
   38878 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   38879 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   38880 ** This could conceivably cause corruption following a power failure on
   38881 ** such a system. This is currently an undocumented limit.
   38882 */
   38883 #define MAX_SECTOR_SIZE 0x10000
   38884 
   38885 /*
   38886 ** An instance of the following structure is allocated for each active
   38887 ** savepoint and statement transaction in the system. All such structures
   38888 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   38889 ** resized using sqlite3Realloc().
   38890 **
   38891 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   38892 ** set to 0. If a journal-header is written into the main journal while
   38893 ** the savepoint is active, then iHdrOffset is set to the byte offset
   38894 ** immediately following the last journal record written into the main
   38895 ** journal before the journal-header. This is required during savepoint
   38896 ** rollback (see pagerPlaybackSavepoint()).
   38897 */
   38898 typedef struct PagerSavepoint PagerSavepoint;
   38899 struct PagerSavepoint {
   38900   i64 iOffset;                 /* Starting offset in main journal */
   38901   i64 iHdrOffset;              /* See above */
   38902   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   38903   Pgno nOrig;                  /* Original number of pages in file */
   38904   Pgno iSubRec;                /* Index of first record in sub-journal */
   38905 #ifndef SQLITE_OMIT_WAL
   38906   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   38907 #endif
   38908 };
   38909 
   38910 /*
   38911 ** A open page cache is an instance of struct Pager. A description of
   38912 ** some of the more important member variables follows:
   38913 **
   38914 ** eState
   38915 **
   38916 **   The current 'state' of the pager object. See the comment and state
   38917 **   diagram above for a description of the pager state.
   38918 **
   38919 ** eLock
   38920 **
   38921 **   For a real on-disk database, the current lock held on the database file -
   38922 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   38923 **
   38924 **   For a temporary or in-memory database (neither of which require any
   38925 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   38926 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   38927 **   logic into thinking that it already has all the locks it will ever
   38928 **   need (and no reason to release them).
   38929 **
   38930 **   In some (obscure) circumstances, this variable may also be set to
   38931 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   38932 **   details.
   38933 **
   38934 ** changeCountDone
   38935 **
   38936 **   This boolean variable is used to make sure that the change-counter
   38937 **   (the 4-byte header field at byte offset 24 of the database file) is
   38938 **   not updated more often than necessary.
   38939 **
   38940 **   It is set to true when the change-counter field is updated, which
   38941 **   can only happen if an exclusive lock is held on the database file.
   38942 **   It is cleared (set to false) whenever an exclusive lock is
   38943 **   relinquished on the database file. Each time a transaction is committed,
   38944 **   The changeCountDone flag is inspected. If it is true, the work of
   38945 **   updating the change-counter is omitted for the current transaction.
   38946 **
   38947 **   This mechanism means that when running in exclusive mode, a connection
   38948 **   need only update the change-counter once, for the first transaction
   38949 **   committed.
   38950 **
   38951 ** setMaster
   38952 **
   38953 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   38954 **   (or may not) specify a master-journal name to be written into the
   38955 **   journal file before it is synced to disk.
   38956 **
   38957 **   Whether or not a journal file contains a master-journal pointer affects
   38958 **   the way in which the journal file is finalized after the transaction is
   38959 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   38960 **   If a journal file does not contain a master-journal pointer, it is
   38961 **   finalized by overwriting the first journal header with zeroes. If
   38962 **   it does contain a master-journal pointer the journal file is finalized
   38963 **   by truncating it to zero bytes, just as if the connection were
   38964 **   running in "journal_mode=truncate" mode.
   38965 **
   38966 **   Journal files that contain master journal pointers cannot be finalized
   38967 **   simply by overwriting the first journal-header with zeroes, as the
   38968 **   master journal pointer could interfere with hot-journal rollback of any
   38969 **   subsequently interrupted transaction that reuses the journal file.
   38970 **
   38971 **   The flag is cleared as soon as the journal file is finalized (either
   38972 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   38973 **   journal file from being successfully finalized, the setMaster flag
   38974 **   is cleared anyway (and the pager will move to ERROR state).
   38975 **
   38976 ** doNotSpill, doNotSyncSpill
   38977 **
   38978 **   These two boolean variables control the behaviour of cache-spills
   38979 **   (calls made by the pcache module to the pagerStress() routine to
   38980 **   write cached data to the file-system in order to free up memory).
   38981 **
   38982 **   When doNotSpill is non-zero, writing to the database from pagerStress()
   38983 **   is disabled altogether. This is done in a very obscure case that
   38984 **   comes up during savepoint rollback that requires the pcache module
   38985 **   to allocate a new page to prevent the journal file from being written
   38986 **   while it is being traversed by code in pager_playback().
   38987 **
   38988 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
   38989 **   is permitted, but syncing the journal file is not. This flag is set
   38990 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
   38991 **   the database page-size in order to prevent a journal sync from happening
   38992 **   in between the journalling of two pages on the same sector.
   38993 **
   38994 ** subjInMemory
   38995 **
   38996 **   This is a boolean variable. If true, then any required sub-journal
   38997 **   is opened as an in-memory journal file. If false, then in-memory
   38998 **   sub-journals are only used for in-memory pager files.
   38999 **
   39000 **   This variable is updated by the upper layer each time a new
   39001 **   write-transaction is opened.
   39002 **
   39003 ** dbSize, dbOrigSize, dbFileSize
   39004 **
   39005 **   Variable dbSize is set to the number of pages in the database file.
   39006 **   It is valid in PAGER_READER and higher states (all states except for
   39007 **   OPEN and ERROR).
   39008 **
   39009 **   dbSize is set based on the size of the database file, which may be
   39010 **   larger than the size of the database (the value stored at offset
   39011 **   28 of the database header by the btree). If the size of the file
   39012 **   is not an integer multiple of the page-size, the value stored in
   39013 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   39014 **   Except, any file that is greater than 0 bytes in size is considered
   39015 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   39016 **   to dbSize==1).
   39017 **
   39018 **   During a write-transaction, if pages with page-numbers greater than
   39019 **   dbSize are modified in the cache, dbSize is updated accordingly.
   39020 **   Similarly, if the database is truncated using PagerTruncateImage(),
   39021 **   dbSize is updated.
   39022 **
   39023 **   Variables dbOrigSize and dbFileSize are valid in states
   39024 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   39025 **   variable at the start of the transaction. It is used during rollback,
   39026 **   and to determine whether or not pages need to be journalled before
   39027 **   being modified.
   39028 **
   39029 **   Throughout a write-transaction, dbFileSize contains the size of
   39030 **   the file on disk in pages. It is set to a copy of dbSize when the
   39031 **   write-transaction is first opened, and updated when VFS calls are made
   39032 **   to write or truncate the database file on disk.
   39033 **
   39034 **   The only reason the dbFileSize variable is required is to suppress
   39035 **   unnecessary calls to xTruncate() after committing a transaction. If,
   39036 **   when a transaction is committed, the dbFileSize variable indicates
   39037 **   that the database file is larger than the database image (Pager.dbSize),
   39038 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   39039 **   to measure the database file on disk, and then truncates it if required.
   39040 **   dbFileSize is not used when rolling back a transaction. In this case
   39041 **   pager_truncate() is called unconditionally (which means there may be
   39042 **   a call to xFilesize() that is not strictly required). In either case,
   39043 **   pager_truncate() may cause the file to become smaller or larger.
   39044 **
   39045 ** dbHintSize
   39046 **
   39047 **   The dbHintSize variable is used to limit the number of calls made to
   39048 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   39049 **
   39050 **   dbHintSize is set to a copy of the dbSize variable when a
   39051 **   write-transaction is opened (at the same time as dbFileSize and
   39052 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   39053 **   dbHintSize is increased to the number of pages that correspond to the
   39054 **   size-hint passed to the method call. See pager_write_pagelist() for
   39055 **   details.
   39056 **
   39057 ** errCode
   39058 **
   39059 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   39060 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   39061 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   39062 **   sub-codes.
   39063 */
   39064 struct Pager {
   39065   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   39066   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   39067   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   39068   u8 useJournal;              /* Use a rollback journal on this file */
   39069   u8 noSync;                  /* Do not sync the journal if true */
   39070   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   39071   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
   39072   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
   39073   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   39074   u8 tempFile;                /* zFilename is a temporary file */
   39075   u8 readOnly;                /* True for a read-only database */
   39076   u8 memDb;                   /* True to inhibit all file I/O */
   39077 
   39078   /**************************************************************************
   39079   ** The following block contains those class members that change during
   39080   ** routine opertion.  Class members not in this block are either fixed
   39081   ** when the pager is first created or else only change when there is a
   39082   ** significant mode change (such as changing the page_size, locking_mode,
   39083   ** or the journal_mode).  From another view, these class members describe
   39084   ** the "state" of the pager, while other class members describe the
   39085   ** "configuration" of the pager.
   39086   */
   39087   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   39088   u8 eLock;                   /* Current lock held on database file */
   39089   u8 changeCountDone;         /* Set after incrementing the change-counter */
   39090   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   39091   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   39092   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
   39093   u8 subjInMemory;            /* True to use in-memory sub-journals */
   39094   Pgno dbSize;                /* Number of pages in the database */
   39095   Pgno dbOrigSize;            /* dbSize before the current transaction */
   39096   Pgno dbFileSize;            /* Number of pages in the database file */
   39097   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   39098   int errCode;                /* One of several kinds of errors */
   39099   int nRec;                   /* Pages journalled since last j-header written */
   39100   u32 cksumInit;              /* Quasi-random value added to every checksum */
   39101   u32 nSubRec;                /* Number of records written to sub-journal */
   39102   Bitvec *pInJournal;         /* One bit for each page in the database file */
   39103   sqlite3_file *fd;           /* File descriptor for database */
   39104   sqlite3_file *jfd;          /* File descriptor for main journal */
   39105   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   39106   i64 journalOff;             /* Current write offset in the journal file */
   39107   i64 journalHdr;             /* Byte offset to previous journal header */
   39108   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   39109   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   39110   int nSavepoint;             /* Number of elements in aSavepoint[] */
   39111   char dbFileVers[16];        /* Changes whenever database file changes */
   39112   /*
   39113   ** End of the routinely-changing class members
   39114   ***************************************************************************/
   39115 
   39116   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   39117   i16 nReserve;               /* Number of unused bytes at end of each page */
   39118   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   39119   u32 sectorSize;             /* Assumed sector size during rollback */
   39120   int pageSize;               /* Number of bytes in a page */
   39121   Pgno mxPgno;                /* Maximum allowed size of the database */
   39122   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   39123   char *zFilename;            /* Name of the database file */
   39124   char *zJournal;             /* Name of the journal file */
   39125   int (*xBusyHandler)(void*); /* Function to call when busy */
   39126   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   39127   int nHit, nMiss;            /* Total cache hits and misses */
   39128 #ifdef SQLITE_TEST
   39129   int nRead, nWrite;          /* Database pages read/written */
   39130 #endif
   39131   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   39132 #ifdef SQLITE_HAS_CODEC
   39133   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   39134   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   39135   void (*xCodecFree)(void*);             /* Destructor for the codec */
   39136   void *pCodec;               /* First argument to xCodec... methods */
   39137 #endif
   39138   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   39139   PCache *pPCache;            /* Pointer to page cache object */
   39140 #ifndef SQLITE_OMIT_WAL
   39141   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   39142   char *zWal;                 /* File name for write-ahead log */
   39143 #endif
   39144 };
   39145 
   39146 /*
   39147 ** The following global variables hold counters used for
   39148 ** testing purposes only.  These variables do not exist in
   39149 ** a non-testing build.  These variables are not thread-safe.
   39150 */
   39151 #ifdef SQLITE_TEST
   39152 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   39153 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   39154 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   39155 # define PAGER_INCR(v)  v++
   39156 #else
   39157 # define PAGER_INCR(v)
   39158 #endif
   39159 
   39160 
   39161 
   39162 /*
   39163 ** Journal files begin with the following magic string.  The data
   39164 ** was obtained from /dev/random.  It is used only as a sanity check.
   39165 **
   39166 ** Since version 2.8.0, the journal format contains additional sanity
   39167 ** checking information.  If the power fails while the journal is being
   39168 ** written, semi-random garbage data might appear in the journal
   39169 ** file after power is restored.  If an attempt is then made
   39170 ** to roll the journal back, the database could be corrupted.  The additional
   39171 ** sanity checking data is an attempt to discover the garbage in the
   39172 ** journal and ignore it.
   39173 **
   39174 ** The sanity checking information for the new journal format consists
   39175 ** of a 32-bit checksum on each page of data.  The checksum covers both
   39176 ** the page number and the pPager->pageSize bytes of data for the page.
   39177 ** This cksum is initialized to a 32-bit random value that appears in the
   39178 ** journal file right after the header.  The random initializer is important,
   39179 ** because garbage data that appears at the end of a journal is likely
   39180 ** data that was once in other files that have now been deleted.  If the
   39181 ** garbage data came from an obsolete journal file, the checksums might
   39182 ** be correct.  But by initializing the checksum to random value which
   39183 ** is different for every journal, we minimize that risk.
   39184 */
   39185 static const unsigned char aJournalMagic[] = {
   39186   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   39187 };
   39188 
   39189 /*
   39190 ** The size of the of each page record in the journal is given by
   39191 ** the following macro.
   39192 */
   39193 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   39194 
   39195 /*
   39196 ** The journal header size for this pager. This is usually the same
   39197 ** size as a single disk sector. See also setSectorSize().
   39198 */
   39199 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   39200 
   39201 /*
   39202 ** The macro MEMDB is true if we are dealing with an in-memory database.
   39203 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   39204 ** the value of MEMDB will be a constant and the compiler will optimize
   39205 ** out code that would never execute.
   39206 */
   39207 #ifdef SQLITE_OMIT_MEMORYDB
   39208 # define MEMDB 0
   39209 #else
   39210 # define MEMDB pPager->memDb
   39211 #endif
   39212 
   39213 /*
   39214 ** The maximum legal page number is (2^31 - 1).
   39215 */
   39216 #define PAGER_MAX_PGNO 2147483647
   39217 
   39218 /*
   39219 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   39220 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   39221 **
   39222 ** This is so that expressions can be written as:
   39223 **
   39224 **   if( isOpen(pPager->jfd) ){ ...
   39225 **
   39226 ** instead of
   39227 **
   39228 **   if( pPager->jfd->pMethods ){ ...
   39229 */
   39230 #define isOpen(pFd) ((pFd)->pMethods)
   39231 
   39232 /*
   39233 ** Return true if this pager uses a write-ahead log instead of the usual
   39234 ** rollback journal. Otherwise false.
   39235 */
   39236 #ifndef SQLITE_OMIT_WAL
   39237 static int pagerUseWal(Pager *pPager){
   39238   return (pPager->pWal!=0);
   39239 }
   39240 #else
   39241 # define pagerUseWal(x) 0
   39242 # define pagerRollbackWal(x) 0
   39243 # define pagerWalFrames(v,w,x,y) 0
   39244 # define pagerOpenWalIfPresent(z) SQLITE_OK
   39245 # define pagerBeginReadTransaction(z) SQLITE_OK
   39246 #endif
   39247 
   39248 #ifndef NDEBUG
   39249 /*
   39250 ** Usage:
   39251 **
   39252 **   assert( assert_pager_state(pPager) );
   39253 **
   39254 ** This function runs many asserts to try to find inconsistencies in
   39255 ** the internal state of the Pager object.
   39256 */
   39257 static int assert_pager_state(Pager *p){
   39258   Pager *pPager = p;
   39259 
   39260   /* State must be valid. */
   39261   assert( p->eState==PAGER_OPEN
   39262        || p->eState==PAGER_READER
   39263        || p->eState==PAGER_WRITER_LOCKED
   39264        || p->eState==PAGER_WRITER_CACHEMOD
   39265        || p->eState==PAGER_WRITER_DBMOD
   39266        || p->eState==PAGER_WRITER_FINISHED
   39267        || p->eState==PAGER_ERROR
   39268   );
   39269 
   39270   /* Regardless of the current state, a temp-file connection always behaves
   39271   ** as if it has an exclusive lock on the database file. It never updates
   39272   ** the change-counter field, so the changeCountDone flag is always set.
   39273   */
   39274   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   39275   assert( p->tempFile==0 || pPager->changeCountDone );
   39276 
   39277   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   39278   ** And if the journal-mode is "OFF", the journal file must not be open.
   39279   */
   39280   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   39281   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   39282 
   39283   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   39284   ** this means an in-memory pager performs no IO at all, it cannot encounter
   39285   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   39286   ** a journal file. (although the in-memory journal implementation may
   39287   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   39288   ** is therefore not possible for an in-memory pager to enter the ERROR
   39289   ** state.
   39290   */
   39291   if( MEMDB ){
   39292     assert( p->noSync );
   39293     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   39294          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   39295     );
   39296     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   39297     assert( pagerUseWal(p)==0 );
   39298   }
   39299 
   39300   /* If changeCountDone is set, a RESERVED lock or greater must be held
   39301   ** on the file.
   39302   */
   39303   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   39304   assert( p->eLock!=PENDING_LOCK );
   39305 
   39306   switch( p->eState ){
   39307     case PAGER_OPEN:
   39308       assert( !MEMDB );
   39309       assert( pPager->errCode==SQLITE_OK );
   39310       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   39311       break;
   39312 
   39313     case PAGER_READER:
   39314       assert( pPager->errCode==SQLITE_OK );
   39315       assert( p->eLock!=UNKNOWN_LOCK );
   39316       assert( p->eLock>=SHARED_LOCK );
   39317       break;
   39318 
   39319     case PAGER_WRITER_LOCKED:
   39320       assert( p->eLock!=UNKNOWN_LOCK );
   39321       assert( pPager->errCode==SQLITE_OK );
   39322       if( !pagerUseWal(pPager) ){
   39323         assert( p->eLock>=RESERVED_LOCK );
   39324       }
   39325       assert( pPager->dbSize==pPager->dbOrigSize );
   39326       assert( pPager->dbOrigSize==pPager->dbFileSize );
   39327       assert( pPager->dbOrigSize==pPager->dbHintSize );
   39328       assert( pPager->setMaster==0 );
   39329       break;
   39330 
   39331     case PAGER_WRITER_CACHEMOD:
   39332       assert( p->eLock!=UNKNOWN_LOCK );
   39333       assert( pPager->errCode==SQLITE_OK );
   39334       if( !pagerUseWal(pPager) ){
   39335         /* It is possible that if journal_mode=wal here that neither the
   39336         ** journal file nor the WAL file are open. This happens during
   39337         ** a rollback transaction that switches from journal_mode=off
   39338         ** to journal_mode=wal.
   39339         */
   39340         assert( p->eLock>=RESERVED_LOCK );
   39341         assert( isOpen(p->jfd)
   39342              || p->journalMode==PAGER_JOURNALMODE_OFF
   39343              || p->journalMode==PAGER_JOURNALMODE_WAL
   39344         );
   39345       }
   39346       assert( pPager->dbOrigSize==pPager->dbFileSize );
   39347       assert( pPager->dbOrigSize==pPager->dbHintSize );
   39348       break;
   39349 
   39350     case PAGER_WRITER_DBMOD:
   39351       assert( p->eLock==EXCLUSIVE_LOCK );
   39352       assert( pPager->errCode==SQLITE_OK );
   39353       assert( !pagerUseWal(pPager) );
   39354       assert( p->eLock>=EXCLUSIVE_LOCK );
   39355       assert( isOpen(p->jfd)
   39356            || p->journalMode==PAGER_JOURNALMODE_OFF
   39357            || p->journalMode==PAGER_JOURNALMODE_WAL
   39358       );
   39359       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   39360       break;
   39361 
   39362     case PAGER_WRITER_FINISHED:
   39363       assert( p->eLock==EXCLUSIVE_LOCK );
   39364       assert( pPager->errCode==SQLITE_OK );
   39365       assert( !pagerUseWal(pPager) );
   39366       assert( isOpen(p->jfd)
   39367            || p->journalMode==PAGER_JOURNALMODE_OFF
   39368            || p->journalMode==PAGER_JOURNALMODE_WAL
   39369       );
   39370       break;
   39371 
   39372     case PAGER_ERROR:
   39373       /* There must be at least one outstanding reference to the pager if
   39374       ** in ERROR state. Otherwise the pager should have already dropped
   39375       ** back to OPEN state.
   39376       */
   39377       assert( pPager->errCode!=SQLITE_OK );
   39378       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   39379       break;
   39380   }
   39381 
   39382   return 1;
   39383 }
   39384 #endif /* ifndef NDEBUG */
   39385 
   39386 #ifdef SQLITE_DEBUG
   39387 /*
   39388 ** Return a pointer to a human readable string in a static buffer
   39389 ** containing the state of the Pager object passed as an argument. This
   39390 ** is intended to be used within debuggers. For example, as an alternative
   39391 ** to "print *pPager" in gdb:
   39392 **
   39393 ** (gdb) printf "%s", print_pager_state(pPager)
   39394 */
   39395 static char *print_pager_state(Pager *p){
   39396   static char zRet[1024];
   39397 
   39398   sqlite3_snprintf(1024, zRet,
   39399       "Filename:      %s\n"
   39400       "State:         %s errCode=%d\n"
   39401       "Lock:          %s\n"
   39402       "Locking mode:  locking_mode=%s\n"
   39403       "Journal mode:  journal_mode=%s\n"
   39404       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   39405       "Journal:       journalOff=%lld journalHdr=%lld\n"
   39406       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   39407       , p->zFilename
   39408       , p->eState==PAGER_OPEN            ? "OPEN" :
   39409         p->eState==PAGER_READER          ? "READER" :
   39410         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   39411         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   39412         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   39413         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   39414         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   39415       , (int)p->errCode
   39416       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   39417         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   39418         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   39419         p->eLock==SHARED_LOCK     ? "SHARED" :
   39420         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   39421       , p->exclusiveMode ? "exclusive" : "normal"
   39422       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   39423         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   39424         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   39425         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   39426         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   39427         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   39428       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   39429       , p->journalOff, p->journalHdr
   39430       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   39431   );
   39432 
   39433   return zRet;
   39434 }
   39435 #endif
   39436 
   39437 /*
   39438 ** Return true if it is necessary to write page *pPg into the sub-journal.
   39439 ** A page needs to be written into the sub-journal if there exists one
   39440 ** or more open savepoints for which:
   39441 **
   39442 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   39443 **   * The bit corresponding to the page-number is not set in
   39444 **     PagerSavepoint.pInSavepoint.
   39445 */
   39446 static int subjRequiresPage(PgHdr *pPg){
   39447   Pgno pgno = pPg->pgno;
   39448   Pager *pPager = pPg->pPager;
   39449   int i;
   39450   for(i=0; i<pPager->nSavepoint; i++){
   39451     PagerSavepoint *p = &pPager->aSavepoint[i];
   39452     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   39453       return 1;
   39454     }
   39455   }
   39456   return 0;
   39457 }
   39458 
   39459 /*
   39460 ** Return true if the page is already in the journal file.
   39461 */
   39462 static int pageInJournal(PgHdr *pPg){
   39463   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
   39464 }
   39465 
   39466 /*
   39467 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   39468 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   39469 ** error code is something goes wrong.
   39470 **
   39471 ** All values are stored on disk as big-endian.
   39472 */
   39473 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   39474   unsigned char ac[4];
   39475   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   39476   if( rc==SQLITE_OK ){
   39477     *pRes = sqlite3Get4byte(ac);
   39478   }
   39479   return rc;
   39480 }
   39481 
   39482 /*
   39483 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   39484 */
   39485 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   39486 
   39487 
   39488 /*
   39489 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   39490 ** on success or an error code is something goes wrong.
   39491 */
   39492 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   39493   char ac[4];
   39494   put32bits(ac, val);
   39495   return sqlite3OsWrite(fd, ac, 4, offset);
   39496 }
   39497 
   39498 /*
   39499 ** Unlock the database file to level eLock, which must be either NO_LOCK
   39500 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   39501 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   39502 **
   39503 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   39504 ** called, do not modify it. See the comment above the #define of
   39505 ** UNKNOWN_LOCK for an explanation of this.
   39506 */
   39507 static int pagerUnlockDb(Pager *pPager, int eLock){
   39508   int rc = SQLITE_OK;
   39509 
   39510   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   39511   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   39512   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   39513   if( isOpen(pPager->fd) ){
   39514     assert( pPager->eLock>=eLock );
   39515     rc = sqlite3OsUnlock(pPager->fd, eLock);
   39516     if( pPager->eLock!=UNKNOWN_LOCK ){
   39517       pPager->eLock = (u8)eLock;
   39518     }
   39519     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   39520   }
   39521   return rc;
   39522 }
   39523 
   39524 /*
   39525 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   39526 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   39527 ** Pager.eLock variable to the new locking state.
   39528 **
   39529 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   39530 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   39531 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   39532 ** of this.
   39533 */
   39534 static int pagerLockDb(Pager *pPager, int eLock){
   39535   int rc = SQLITE_OK;
   39536 
   39537   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   39538   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   39539     rc = sqlite3OsLock(pPager->fd, eLock);
   39540     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   39541       pPager->eLock = (u8)eLock;
   39542       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   39543     }
   39544   }
   39545   return rc;
   39546 }
   39547 
   39548 /*
   39549 ** This function determines whether or not the atomic-write optimization
   39550 ** can be used with this pager. The optimization can be used if:
   39551 **
   39552 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   39553 **      a database page may be written atomically, and
   39554 **  (b) the value returned by OsSectorSize() is less than or equal
   39555 **      to the page size.
   39556 **
   39557 ** The optimization is also always enabled for temporary files. It is
   39558 ** an error to call this function if pPager is opened on an in-memory
   39559 ** database.
   39560 **
   39561 ** If the optimization cannot be used, 0 is returned. If it can be used,
   39562 ** then the value returned is the size of the journal file when it
   39563 ** contains rollback data for exactly one page.
   39564 */
   39565 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   39566 static int jrnlBufferSize(Pager *pPager){
   39567   assert( !MEMDB );
   39568   if( !pPager->tempFile ){
   39569     int dc;                           /* Device characteristics */
   39570     int nSector;                      /* Sector size */
   39571     int szPage;                       /* Page size */
   39572 
   39573     assert( isOpen(pPager->fd) );
   39574     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   39575     nSector = pPager->sectorSize;
   39576     szPage = pPager->pageSize;
   39577 
   39578     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   39579     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   39580     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   39581       return 0;
   39582     }
   39583   }
   39584 
   39585   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   39586 }
   39587 #endif
   39588 
   39589 /*
   39590 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   39591 ** on the cache using a hash function.  This is used for testing
   39592 ** and debugging only.
   39593 */
   39594 #ifdef SQLITE_CHECK_PAGES
   39595 /*
   39596 ** Return a 32-bit hash of the page data for pPage.
   39597 */
   39598 static u32 pager_datahash(int nByte, unsigned char *pData){
   39599   u32 hash = 0;
   39600   int i;
   39601   for(i=0; i<nByte; i++){
   39602     hash = (hash*1039) + pData[i];
   39603   }
   39604   return hash;
   39605 }
   39606 static u32 pager_pagehash(PgHdr *pPage){
   39607   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   39608 }
   39609 static void pager_set_pagehash(PgHdr *pPage){
   39610   pPage->pageHash = pager_pagehash(pPage);
   39611 }
   39612 
   39613 /*
   39614 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   39615 ** is defined, and NDEBUG is not defined, an assert() statement checks
   39616 ** that the page is either dirty or still matches the calculated page-hash.
   39617 */
   39618 #define CHECK_PAGE(x) checkPage(x)
   39619 static void checkPage(PgHdr *pPg){
   39620   Pager *pPager = pPg->pPager;
   39621   assert( pPager->eState!=PAGER_ERROR );
   39622   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   39623 }
   39624 
   39625 #else
   39626 #define pager_datahash(X,Y)  0
   39627 #define pager_pagehash(X)  0
   39628 #define pager_set_pagehash(X)
   39629 #define CHECK_PAGE(x)
   39630 #endif  /* SQLITE_CHECK_PAGES */
   39631 
   39632 /*
   39633 ** When this is called the journal file for pager pPager must be open.
   39634 ** This function attempts to read a master journal file name from the
   39635 ** end of the file and, if successful, copies it into memory supplied
   39636 ** by the caller. See comments above writeMasterJournal() for the format
   39637 ** used to store a master journal file name at the end of a journal file.
   39638 **
   39639 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   39640 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   39641 ** enough space to write the master journal name). If the master journal
   39642 ** name in the journal is longer than nMaster bytes (including a
   39643 ** nul-terminator), then this is handled as if no master journal name
   39644 ** were present in the journal.
   39645 **
   39646 ** If a master journal file name is present at the end of the journal
   39647 ** file, then it is copied into the buffer pointed to by zMaster. A
   39648 ** nul-terminator byte is appended to the buffer following the master
   39649 ** journal file name.
   39650 **
   39651 ** If it is determined that no master journal file name is present
   39652 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   39653 **
   39654 ** If an error occurs while reading from the journal file, an SQLite
   39655 ** error code is returned.
   39656 */
   39657 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   39658   int rc;                    /* Return code */
   39659   u32 len;                   /* Length in bytes of master journal name */
   39660   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   39661   u32 cksum;                 /* MJ checksum value read from journal */
   39662   u32 u;                     /* Unsigned loop counter */
   39663   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   39664   zMaster[0] = '\0';
   39665 
   39666   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   39667    || szJ<16
   39668    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   39669    || len>=nMaster
   39670    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   39671    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   39672    || memcmp(aMagic, aJournalMagic, 8)
   39673    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   39674   ){
   39675     return rc;
   39676   }
   39677 
   39678   /* See if the checksum matches the master journal name */
   39679   for(u=0; u<len; u++){
   39680     cksum -= zMaster[u];
   39681   }
   39682   if( cksum ){
   39683     /* If the checksum doesn't add up, then one or more of the disk sectors
   39684     ** containing the master journal filename is corrupted. This means
   39685     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   39686     ** master-journal filename.
   39687     */
   39688     len = 0;
   39689   }
   39690   zMaster[len] = '\0';
   39691 
   39692   return SQLITE_OK;
   39693 }
   39694 
   39695 /*
   39696 ** Return the offset of the sector boundary at or immediately
   39697 ** following the value in pPager->journalOff, assuming a sector
   39698 ** size of pPager->sectorSize bytes.
   39699 **
   39700 ** i.e for a sector size of 512:
   39701 **
   39702 **   Pager.journalOff          Return value
   39703 **   ---------------------------------------
   39704 **   0                         0
   39705 **   512                       512
   39706 **   100                       512
   39707 **   2000                      2048
   39708 **
   39709 */
   39710 static i64 journalHdrOffset(Pager *pPager){
   39711   i64 offset = 0;
   39712   i64 c = pPager->journalOff;
   39713   if( c ){
   39714     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   39715   }
   39716   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   39717   assert( offset>=c );
   39718   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   39719   return offset;
   39720 }
   39721 
   39722 /*
   39723 ** The journal file must be open when this function is called.
   39724 **
   39725 ** This function is a no-op if the journal file has not been written to
   39726 ** within the current transaction (i.e. if Pager.journalOff==0).
   39727 **
   39728 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   39729 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   39730 ** zero the 28-byte header at the start of the journal file. In either case,
   39731 ** if the pager is not in no-sync mode, sync the journal file immediately
   39732 ** after writing or truncating it.
   39733 **
   39734 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   39735 ** following the truncation or zeroing described above the size of the
   39736 ** journal file in bytes is larger than this value, then truncate the
   39737 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   39738 ** not need to be synced following this operation.
   39739 **
   39740 ** If an IO error occurs, abandon processing and return the IO error code.
   39741 ** Otherwise, return SQLITE_OK.
   39742 */
   39743 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   39744   int rc = SQLITE_OK;                               /* Return code */
   39745   assert( isOpen(pPager->jfd) );
   39746   if( pPager->journalOff ){
   39747     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   39748 
   39749     IOTRACE(("JZEROHDR %p\n", pPager))
   39750     if( doTruncate || iLimit==0 ){
   39751       rc = sqlite3OsTruncate(pPager->jfd, 0);
   39752     }else{
   39753       static const char zeroHdr[28] = {0};
   39754       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   39755     }
   39756     if( rc==SQLITE_OK && !pPager->noSync ){
   39757       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   39758     }
   39759 
   39760     /* At this point the transaction is committed but the write lock
   39761     ** is still held on the file. If there is a size limit configured for
   39762     ** the persistent journal and the journal file currently consumes more
   39763     ** space than that limit allows for, truncate it now. There is no need
   39764     ** to sync the file following this operation.
   39765     */
   39766     if( rc==SQLITE_OK && iLimit>0 ){
   39767       i64 sz;
   39768       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   39769       if( rc==SQLITE_OK && sz>iLimit ){
   39770         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   39771       }
   39772     }
   39773   }
   39774   return rc;
   39775 }
   39776 
   39777 /*
   39778 ** The journal file must be open when this routine is called. A journal
   39779 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   39780 ** current location.
   39781 **
   39782 ** The format for the journal header is as follows:
   39783 ** - 8 bytes: Magic identifying journal format.
   39784 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   39785 ** - 4 bytes: Random number used for page hash.
   39786 ** - 4 bytes: Initial database page count.
   39787 ** - 4 bytes: Sector size used by the process that wrote this journal.
   39788 ** - 4 bytes: Database page size.
   39789 **
   39790 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   39791 */
   39792 static int writeJournalHdr(Pager *pPager){
   39793   int rc = SQLITE_OK;                 /* Return code */
   39794   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   39795   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   39796   u32 nWrite;                         /* Bytes of header sector written */
   39797   int ii;                             /* Loop counter */
   39798 
   39799   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   39800 
   39801   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   39802     nHeader = JOURNAL_HDR_SZ(pPager);
   39803   }
   39804 
   39805   /* If there are active savepoints and any of them were created
   39806   ** since the most recent journal header was written, update the
   39807   ** PagerSavepoint.iHdrOffset fields now.
   39808   */
   39809   for(ii=0; ii<pPager->nSavepoint; ii++){
   39810     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   39811       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   39812     }
   39813   }
   39814 
   39815   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   39816 
   39817   /*
   39818   ** Write the nRec Field - the number of page records that follow this
   39819   ** journal header. Normally, zero is written to this value at this time.
   39820   ** After the records are added to the journal (and the journal synced,
   39821   ** if in full-sync mode), the zero is overwritten with the true number
   39822   ** of records (see syncJournal()).
   39823   **
   39824   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   39825   ** reading the journal this value tells SQLite to assume that the
   39826   ** rest of the journal file contains valid page records. This assumption
   39827   ** is dangerous, as if a failure occurred whilst writing to the journal
   39828   ** file it may contain some garbage data. There are two scenarios
   39829   ** where this risk can be ignored:
   39830   **
   39831   **   * When the pager is in no-sync mode. Corruption can follow a
   39832   **     power failure in this case anyway.
   39833   **
   39834   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   39835   **     that garbage data is never appended to the journal file.
   39836   */
   39837   assert( isOpen(pPager->fd) || pPager->noSync );
   39838   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   39839    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   39840   ){
   39841     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   39842     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   39843   }else{
   39844     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   39845   }
   39846 
   39847   /* The random check-hash initialiser */
   39848   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   39849   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   39850   /* The initial database size */
   39851   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   39852   /* The assumed sector size for this process */
   39853   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   39854 
   39855   /* The page size */
   39856   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   39857 
   39858   /* Initializing the tail of the buffer is not necessary.  Everything
   39859   ** works find if the following memset() is omitted.  But initializing
   39860   ** the memory prevents valgrind from complaining, so we are willing to
   39861   ** take the performance hit.
   39862   */
   39863   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   39864          nHeader-(sizeof(aJournalMagic)+20));
   39865 
   39866   /* In theory, it is only necessary to write the 28 bytes that the
   39867   ** journal header consumes to the journal file here. Then increment the
   39868   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   39869   ** record is written to the following sector (leaving a gap in the file
   39870   ** that will be implicitly filled in by the OS).
   39871   **
   39872   ** However it has been discovered that on some systems this pattern can
   39873   ** be significantly slower than contiguously writing data to the file,
   39874   ** even if that means explicitly writing data to the block of
   39875   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   39876   ** is done.
   39877   **
   39878   ** The loop is required here in case the sector-size is larger than the
   39879   ** database page size. Since the zHeader buffer is only Pager.pageSize
   39880   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   39881   ** to populate the entire journal header sector.
   39882   */
   39883   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   39884     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   39885     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   39886     assert( pPager->journalHdr <= pPager->journalOff );
   39887     pPager->journalOff += nHeader;
   39888   }
   39889 
   39890   return rc;
   39891 }
   39892 
   39893 /*
   39894 ** The journal file must be open when this is called. A journal header file
   39895 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   39896 ** file. The current location in the journal file is given by
   39897 ** pPager->journalOff. See comments above function writeJournalHdr() for
   39898 ** a description of the journal header format.
   39899 **
   39900 ** If the header is read successfully, *pNRec is set to the number of
   39901 ** page records following this header and *pDbSize is set to the size of the
   39902 ** database before the transaction began, in pages. Also, pPager->cksumInit
   39903 ** is set to the value read from the journal header. SQLITE_OK is returned
   39904 ** in this case.
   39905 **
   39906 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   39907 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   39908 ** cannot be read from the journal file an error code is returned.
   39909 */
   39910 static int readJournalHdr(
   39911   Pager *pPager,               /* Pager object */
   39912   int isHot,
   39913   i64 journalSize,             /* Size of the open journal file in bytes */
   39914   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   39915   u32 *pDbSize                 /* OUT: Value of original database size field */
   39916 ){
   39917   int rc;                      /* Return code */
   39918   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   39919   i64 iHdrOff;                 /* Offset of journal header being read */
   39920 
   39921   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   39922 
   39923   /* Advance Pager.journalOff to the start of the next sector. If the
   39924   ** journal file is too small for there to be a header stored at this
   39925   ** point, return SQLITE_DONE.
   39926   */
   39927   pPager->journalOff = journalHdrOffset(pPager);
   39928   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   39929     return SQLITE_DONE;
   39930   }
   39931   iHdrOff = pPager->journalOff;
   39932 
   39933   /* Read in the first 8 bytes of the journal header. If they do not match
   39934   ** the  magic string found at the start of each journal header, return
   39935   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   39936   ** proceed.
   39937   */
   39938   if( isHot || iHdrOff!=pPager->journalHdr ){
   39939     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   39940     if( rc ){
   39941       return rc;
   39942     }
   39943     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   39944       return SQLITE_DONE;
   39945     }
   39946   }
   39947 
   39948   /* Read the first three 32-bit fields of the journal header: The nRec
   39949   ** field, the checksum-initializer and the database size at the start
   39950   ** of the transaction. Return an error code if anything goes wrong.
   39951   */
   39952   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   39953    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   39954    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   39955   ){
   39956     return rc;
   39957   }
   39958 
   39959   if( pPager->journalOff==0 ){
   39960     u32 iPageSize;               /* Page-size field of journal header */
   39961     u32 iSectorSize;             /* Sector-size field of journal header */
   39962 
   39963     /* Read the page-size and sector-size journal header fields. */
   39964     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   39965      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   39966     ){
   39967       return rc;
   39968     }
   39969 
   39970     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   39971     ** journal header to zero. In this case, assume that the Pager.pageSize
   39972     ** variable is already set to the correct page size.
   39973     */
   39974     if( iPageSize==0 ){
   39975       iPageSize = pPager->pageSize;
   39976     }
   39977 
   39978     /* Check that the values read from the page-size and sector-size fields
   39979     ** are within range. To be 'in range', both values need to be a power
   39980     ** of two greater than or equal to 512 or 32, and not greater than their
   39981     ** respective compile time maximum limits.
   39982     */
   39983     if( iPageSize<512                  || iSectorSize<32
   39984      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   39985      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   39986     ){
   39987       /* If the either the page-size or sector-size in the journal-header is
   39988       ** invalid, then the process that wrote the journal-header must have
   39989       ** crashed before the header was synced. In this case stop reading
   39990       ** the journal file here.
   39991       */
   39992       return SQLITE_DONE;
   39993     }
   39994 
   39995     /* Update the page-size to match the value read from the journal.
   39996     ** Use a testcase() macro to make sure that malloc failure within
   39997     ** PagerSetPagesize() is tested.
   39998     */
   39999     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   40000     testcase( rc!=SQLITE_OK );
   40001 
   40002     /* Update the assumed sector-size to match the value used by
   40003     ** the process that created this journal. If this journal was
   40004     ** created by a process other than this one, then this routine
   40005     ** is being called from within pager_playback(). The local value
   40006     ** of Pager.sectorSize is restored at the end of that routine.
   40007     */
   40008     pPager->sectorSize = iSectorSize;
   40009   }
   40010 
   40011   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   40012   return rc;
   40013 }
   40014 
   40015 
   40016 /*
   40017 ** Write the supplied master journal name into the journal file for pager
   40018 ** pPager at the current location. The master journal name must be the last
   40019 ** thing written to a journal file. If the pager is in full-sync mode, the
   40020 ** journal file descriptor is advanced to the next sector boundary before
   40021 ** anything is written. The format is:
   40022 **
   40023 **   + 4 bytes: PAGER_MJ_PGNO.
   40024 **   + N bytes: Master journal filename in utf-8.
   40025 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   40026 **   + 4 bytes: Master journal name checksum.
   40027 **   + 8 bytes: aJournalMagic[].
   40028 **
   40029 ** The master journal page checksum is the sum of the bytes in the master
   40030 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   40031 **
   40032 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   40033 ** this call is a no-op.
   40034 */
   40035 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   40036   int rc;                          /* Return code */
   40037   int nMaster;                     /* Length of string zMaster */
   40038   i64 iHdrOff;                     /* Offset of header in journal file */
   40039   i64 jrnlSize;                    /* Size of journal file on disk */
   40040   u32 cksum = 0;                   /* Checksum of string zMaster */
   40041 
   40042   assert( pPager->setMaster==0 );
   40043   assert( !pagerUseWal(pPager) );
   40044 
   40045   if( !zMaster
   40046    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   40047    || pPager->journalMode==PAGER_JOURNALMODE_OFF
   40048   ){
   40049     return SQLITE_OK;
   40050   }
   40051   pPager->setMaster = 1;
   40052   assert( isOpen(pPager->jfd) );
   40053   assert( pPager->journalHdr <= pPager->journalOff );
   40054 
   40055   /* Calculate the length in bytes and the checksum of zMaster */
   40056   for(nMaster=0; zMaster[nMaster]; nMaster++){
   40057     cksum += zMaster[nMaster];
   40058   }
   40059 
   40060   /* If in full-sync mode, advance to the next disk sector before writing
   40061   ** the master journal name. This is in case the previous page written to
   40062   ** the journal has already been synced.
   40063   */
   40064   if( pPager->fullSync ){
   40065     pPager->journalOff = journalHdrOffset(pPager);
   40066   }
   40067   iHdrOff = pPager->journalOff;
   40068 
   40069   /* Write the master journal data to the end of the journal file. If
   40070   ** an error occurs, return the error code to the caller.
   40071   */
   40072   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   40073    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   40074    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   40075    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   40076    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   40077   ){
   40078     return rc;
   40079   }
   40080   pPager->journalOff += (nMaster+20);
   40081 
   40082   /* If the pager is in peristent-journal mode, then the physical
   40083   ** journal-file may extend past the end of the master-journal name
   40084   ** and 8 bytes of magic data just written to the file. This is
   40085   ** dangerous because the code to rollback a hot-journal file
   40086   ** will not be able to find the master-journal name to determine
   40087   ** whether or not the journal is hot.
   40088   **
   40089   ** Easiest thing to do in this scenario is to truncate the journal
   40090   ** file to the required size.
   40091   */
   40092   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   40093    && jrnlSize>pPager->journalOff
   40094   ){
   40095     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   40096   }
   40097   return rc;
   40098 }
   40099 
   40100 /*
   40101 ** Find a page in the hash table given its page number. Return
   40102 ** a pointer to the page or NULL if the requested page is not
   40103 ** already in memory.
   40104 */
   40105 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   40106   PgHdr *p;                         /* Return value */
   40107 
   40108   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   40109   ** fail, since no attempt to allocate dynamic memory will be made.
   40110   */
   40111   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   40112   return p;
   40113 }
   40114 
   40115 /*
   40116 ** Discard the entire contents of the in-memory page-cache.
   40117 */
   40118 static void pager_reset(Pager *pPager){
   40119   sqlite3BackupRestart(pPager->pBackup);
   40120   sqlite3PcacheClear(pPager->pPCache);
   40121 }
   40122 
   40123 /*
   40124 ** Free all structures in the Pager.aSavepoint[] array and set both
   40125 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   40126 ** if it is open and the pager is not in exclusive mode.
   40127 */
   40128 static void releaseAllSavepoints(Pager *pPager){
   40129   int ii;               /* Iterator for looping through Pager.aSavepoint */
   40130   for(ii=0; ii<pPager->nSavepoint; ii++){
   40131     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   40132   }
   40133   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   40134     sqlite3OsClose(pPager->sjfd);
   40135   }
   40136   sqlite3_free(pPager->aSavepoint);
   40137   pPager->aSavepoint = 0;
   40138   pPager->nSavepoint = 0;
   40139   pPager->nSubRec = 0;
   40140 }
   40141 
   40142 /*
   40143 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   40144 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   40145 ** or SQLITE_NOMEM if a malloc failure occurs.
   40146 */
   40147 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   40148   int ii;                   /* Loop counter */
   40149   int rc = SQLITE_OK;       /* Result code */
   40150 
   40151   for(ii=0; ii<pPager->nSavepoint; ii++){
   40152     PagerSavepoint *p = &pPager->aSavepoint[ii];
   40153     if( pgno<=p->nOrig ){
   40154       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   40155       testcase( rc==SQLITE_NOMEM );
   40156       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   40157     }
   40158   }
   40159   return rc;
   40160 }
   40161 
   40162 /*
   40163 ** This function is a no-op if the pager is in exclusive mode and not
   40164 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   40165 ** state.
   40166 **
   40167 ** If the pager is not in exclusive-access mode, the database file is
   40168 ** completely unlocked. If the file is unlocked and the file-system does
   40169 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   40170 ** closed (if it is open).
   40171 **
   40172 ** If the pager is in ERROR state when this function is called, the
   40173 ** contents of the pager cache are discarded before switching back to
   40174 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   40175 ** or not, any journal file left in the file-system will be treated
   40176 ** as a hot-journal and rolled back the next time a read-transaction
   40177 ** is opened (by this or by any other connection).
   40178 */
   40179 static void pager_unlock(Pager *pPager){
   40180 
   40181   assert( pPager->eState==PAGER_READER
   40182        || pPager->eState==PAGER_OPEN
   40183        || pPager->eState==PAGER_ERROR
   40184   );
   40185 
   40186   sqlite3BitvecDestroy(pPager->pInJournal);
   40187   pPager->pInJournal = 0;
   40188   releaseAllSavepoints(pPager);
   40189 
   40190   if( pagerUseWal(pPager) ){
   40191     assert( !isOpen(pPager->jfd) );
   40192     sqlite3WalEndReadTransaction(pPager->pWal);
   40193     pPager->eState = PAGER_OPEN;
   40194   }else if( !pPager->exclusiveMode ){
   40195     int rc;                       /* Error code returned by pagerUnlockDb() */
   40196     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   40197 
   40198     /* If the operating system support deletion of open files, then
   40199     ** close the journal file when dropping the database lock.  Otherwise
   40200     ** another connection with journal_mode=delete might delete the file
   40201     ** out from under us.
   40202     */
   40203     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   40204     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   40205     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   40206     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   40207     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   40208     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   40209     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   40210      || 1!=(pPager->journalMode & 5)
   40211     ){
   40212       sqlite3OsClose(pPager->jfd);
   40213     }
   40214 
   40215     /* If the pager is in the ERROR state and the call to unlock the database
   40216     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   40217     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   40218     ** is necessary.
   40219     */
   40220     rc = pagerUnlockDb(pPager, NO_LOCK);
   40221     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   40222       pPager->eLock = UNKNOWN_LOCK;
   40223     }
   40224 
   40225     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   40226     ** without clearing the error code. This is intentional - the error
   40227     ** code is cleared and the cache reset in the block below.
   40228     */
   40229     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   40230     pPager->changeCountDone = 0;
   40231     pPager->eState = PAGER_OPEN;
   40232   }
   40233 
   40234   /* If Pager.errCode is set, the contents of the pager cache cannot be
   40235   ** trusted. Now that there are no outstanding references to the pager,
   40236   ** it can safely move back to PAGER_OPEN state. This happens in both
   40237   ** normal and exclusive-locking mode.
   40238   */
   40239   if( pPager->errCode ){
   40240     assert( !MEMDB );
   40241     pager_reset(pPager);
   40242     pPager->changeCountDone = pPager->tempFile;
   40243     pPager->eState = PAGER_OPEN;
   40244     pPager->errCode = SQLITE_OK;
   40245   }
   40246 
   40247   pPager->journalOff = 0;
   40248   pPager->journalHdr = 0;
   40249   pPager->setMaster = 0;
   40250 }
   40251 
   40252 /*
   40253 ** This function is called whenever an IOERR or FULL error that requires
   40254 ** the pager to transition into the ERROR state may ahve occurred.
   40255 ** The first argument is a pointer to the pager structure, the second
   40256 ** the error-code about to be returned by a pager API function. The
   40257 ** value returned is a copy of the second argument to this function.
   40258 **
   40259 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   40260 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   40261 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   40262 ** all major API calls on the Pager will immediately return Pager.errCode.
   40263 **
   40264 ** The ERROR state indicates that the contents of the pager-cache
   40265 ** cannot be trusted. This state can be cleared by completely discarding
   40266 ** the contents of the pager-cache. If a transaction was active when
   40267 ** the persistent error occurred, then the rollback journal may need
   40268 ** to be replayed to restore the contents of the database file (as if
   40269 ** it were a hot-journal).
   40270 */
   40271 static int pager_error(Pager *pPager, int rc){
   40272   int rc2 = rc & 0xff;
   40273   assert( rc==SQLITE_OK || !MEMDB );
   40274   assert(
   40275        pPager->errCode==SQLITE_FULL ||
   40276        pPager->errCode==SQLITE_OK ||
   40277        (pPager->errCode & 0xff)==SQLITE_IOERR
   40278   );
   40279   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   40280     pPager->errCode = rc;
   40281     pPager->eState = PAGER_ERROR;
   40282   }
   40283   return rc;
   40284 }
   40285 
   40286 /*
   40287 ** This routine ends a transaction. A transaction is usually ended by
   40288 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   40289 ** after rollback of a hot-journal, or if an error occurs while opening
   40290 ** the journal file or writing the very first journal-header of a
   40291 ** database transaction.
   40292 **
   40293 ** This routine is never called in PAGER_ERROR state. If it is called
   40294 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   40295 ** exclusive than a RESERVED lock, it is a no-op.
   40296 **
   40297 ** Otherwise, any active savepoints are released.
   40298 **
   40299 ** If the journal file is open, then it is "finalized". Once a journal
   40300 ** file has been finalized it is not possible to use it to roll back a
   40301 ** transaction. Nor will it be considered to be a hot-journal by this
   40302 ** or any other database connection. Exactly how a journal is finalized
   40303 ** depends on whether or not the pager is running in exclusive mode and
   40304 ** the current journal-mode (Pager.journalMode value), as follows:
   40305 **
   40306 **   journalMode==MEMORY
   40307 **     Journal file descriptor is simply closed. This destroys an
   40308 **     in-memory journal.
   40309 **
   40310 **   journalMode==TRUNCATE
   40311 **     Journal file is truncated to zero bytes in size.
   40312 **
   40313 **   journalMode==PERSIST
   40314 **     The first 28 bytes of the journal file are zeroed. This invalidates
   40315 **     the first journal header in the file, and hence the entire journal
   40316 **     file. An invalid journal file cannot be rolled back.
   40317 **
   40318 **   journalMode==DELETE
   40319 **     The journal file is closed and deleted using sqlite3OsDelete().
   40320 **
   40321 **     If the pager is running in exclusive mode, this method of finalizing
   40322 **     the journal file is never used. Instead, if the journalMode is
   40323 **     DELETE and the pager is in exclusive mode, the method described under
   40324 **     journalMode==PERSIST is used instead.
   40325 **
   40326 ** After the journal is finalized, the pager moves to PAGER_READER state.
   40327 ** If running in non-exclusive rollback mode, the lock on the file is
   40328 ** downgraded to a SHARED_LOCK.
   40329 **
   40330 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   40331 ** any of the IO operations to finalize the journal file or unlock the
   40332 ** database then the IO error code is returned to the user. If the
   40333 ** operation to finalize the journal file fails, then the code still
   40334 ** tries to unlock the database file if not in exclusive mode. If the
   40335 ** unlock operation fails as well, then the first error code related
   40336 ** to the first error encountered (the journal finalization one) is
   40337 ** returned.
   40338 */
   40339 static int pager_end_transaction(Pager *pPager, int hasMaster){
   40340   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   40341   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   40342 
   40343   /* Do nothing if the pager does not have an open write transaction
   40344   ** or at least a RESERVED lock. This function may be called when there
   40345   ** is no write-transaction active but a RESERVED or greater lock is
   40346   ** held under two circumstances:
   40347   **
   40348   **   1. After a successful hot-journal rollback, it is called with
   40349   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   40350   **
   40351   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   40352   **      lock switches back to locking_mode=normal and then executes a
   40353   **      read-transaction, this function is called with eState==PAGER_READER
   40354   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   40355   */
   40356   assert( assert_pager_state(pPager) );
   40357   assert( pPager->eState!=PAGER_ERROR );
   40358   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   40359     return SQLITE_OK;
   40360   }
   40361 
   40362   releaseAllSavepoints(pPager);
   40363   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   40364   if( isOpen(pPager->jfd) ){
   40365     assert( !pagerUseWal(pPager) );
   40366 
   40367     /* Finalize the journal file. */
   40368     if( sqlite3IsMemJournal(pPager->jfd) ){
   40369       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   40370       sqlite3OsClose(pPager->jfd);
   40371     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   40372       if( pPager->journalOff==0 ){
   40373         rc = SQLITE_OK;
   40374       }else{
   40375         rc = sqlite3OsTruncate(pPager->jfd, 0);
   40376       }
   40377       pPager->journalOff = 0;
   40378     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   40379       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   40380     ){
   40381       rc = zeroJournalHdr(pPager, hasMaster);
   40382       pPager->journalOff = 0;
   40383     }else{
   40384       /* This branch may be executed with Pager.journalMode==MEMORY if
   40385       ** a hot-journal was just rolled back. In this case the journal
   40386       ** file should be closed and deleted. If this connection writes to
   40387       ** the database file, it will do so using an in-memory journal.
   40388       */
   40389       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   40390            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   40391            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   40392       );
   40393       sqlite3OsClose(pPager->jfd);
   40394       if( !pPager->tempFile ){
   40395         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   40396       }
   40397     }
   40398   }
   40399 
   40400 #ifdef SQLITE_CHECK_PAGES
   40401   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   40402   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   40403     PgHdr *p = pager_lookup(pPager, 1);
   40404     if( p ){
   40405       p->pageHash = 0;
   40406       sqlite3PagerUnref(p);
   40407     }
   40408   }
   40409 #endif
   40410 
   40411   sqlite3BitvecDestroy(pPager->pInJournal);
   40412   pPager->pInJournal = 0;
   40413   pPager->nRec = 0;
   40414   sqlite3PcacheCleanAll(pPager->pPCache);
   40415   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   40416 
   40417   if( pagerUseWal(pPager) ){
   40418     /* Drop the WAL write-lock, if any. Also, if the connection was in
   40419     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   40420     ** lock held on the database file.
   40421     */
   40422     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   40423     assert( rc2==SQLITE_OK );
   40424   }
   40425   if( !pPager->exclusiveMode
   40426    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   40427   ){
   40428     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   40429     pPager->changeCountDone = 0;
   40430   }
   40431   pPager->eState = PAGER_READER;
   40432   pPager->setMaster = 0;
   40433 
   40434   return (rc==SQLITE_OK?rc2:rc);
   40435 }
   40436 
   40437 /*
   40438 ** Execute a rollback if a transaction is active and unlock the
   40439 ** database file.
   40440 **
   40441 ** If the pager has already entered the ERROR state, do not attempt
   40442 ** the rollback at this time. Instead, pager_unlock() is called. The
   40443 ** call to pager_unlock() will discard all in-memory pages, unlock
   40444 ** the database file and move the pager back to OPEN state. If this
   40445 ** means that there is a hot-journal left in the file-system, the next
   40446 ** connection to obtain a shared lock on the pager (which may be this one)
   40447 ** will roll it back.
   40448 **
   40449 ** If the pager has not already entered the ERROR state, but an IO or
   40450 ** malloc error occurs during a rollback, then this will itself cause
   40451 ** the pager to enter the ERROR state. Which will be cleared by the
   40452 ** call to pager_unlock(), as described above.
   40453 */
   40454 static void pagerUnlockAndRollback(Pager *pPager){
   40455   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   40456     assert( assert_pager_state(pPager) );
   40457     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   40458       sqlite3BeginBenignMalloc();
   40459       sqlite3PagerRollback(pPager);
   40460       sqlite3EndBenignMalloc();
   40461     }else if( !pPager->exclusiveMode ){
   40462       assert( pPager->eState==PAGER_READER );
   40463       pager_end_transaction(pPager, 0);
   40464     }
   40465   }
   40466   pager_unlock(pPager);
   40467 }
   40468 
   40469 /*
   40470 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   40471 ** of data. Compute and return a checksum based ont the contents of the
   40472 ** page of data and the current value of pPager->cksumInit.
   40473 **
   40474 ** This is not a real checksum. It is really just the sum of the
   40475 ** random initial value (pPager->cksumInit) and every 200th byte
   40476 ** of the page data, starting with byte offset (pPager->pageSize%200).
   40477 ** Each byte is interpreted as an 8-bit unsigned integer.
   40478 **
   40479 ** Changing the formula used to compute this checksum results in an
   40480 ** incompatible journal file format.
   40481 **
   40482 ** If journal corruption occurs due to a power failure, the most likely
   40483 ** scenario is that one end or the other of the record will be changed.
   40484 ** It is much less likely that the two ends of the journal record will be
   40485 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   40486 ** though fast and simple, catches the mostly likely kind of corruption.
   40487 */
   40488 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   40489   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   40490   int i = pPager->pageSize-200;          /* Loop counter */
   40491   while( i>0 ){
   40492     cksum += aData[i];
   40493     i -= 200;
   40494   }
   40495   return cksum;
   40496 }
   40497 
   40498 /*
   40499 ** Report the current page size and number of reserved bytes back
   40500 ** to the codec.
   40501 */
   40502 #ifdef SQLITE_HAS_CODEC
   40503 static void pagerReportSize(Pager *pPager){
   40504   if( pPager->xCodecSizeChng ){
   40505     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   40506                            (int)pPager->nReserve);
   40507   }
   40508 }
   40509 #else
   40510 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   40511 #endif
   40512 
   40513 /*
   40514 ** Read a single page from either the journal file (if isMainJrnl==1) or
   40515 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   40516 ** The page begins at offset *pOffset into the file. The *pOffset
   40517 ** value is increased to the start of the next page in the journal.
   40518 **
   40519 ** The main rollback journal uses checksums - the statement journal does
   40520 ** not.
   40521 **
   40522 ** If the page number of the page record read from the (sub-)journal file
   40523 ** is greater than the current value of Pager.dbSize, then playback is
   40524 ** skipped and SQLITE_OK is returned.
   40525 **
   40526 ** If pDone is not NULL, then it is a record of pages that have already
   40527 ** been played back.  If the page at *pOffset has already been played back
   40528 ** (if the corresponding pDone bit is set) then skip the playback.
   40529 ** Make sure the pDone bit corresponding to the *pOffset page is set
   40530 ** prior to returning.
   40531 **
   40532 ** If the page record is successfully read from the (sub-)journal file
   40533 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   40534 ** while reading the record from the (sub-)journal file or while writing
   40535 ** to the database file, then the IO error code is returned. If data
   40536 ** is successfully read from the (sub-)journal file but appears to be
   40537 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   40538 ** two circumstances:
   40539 **
   40540 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   40541 **   * If the record is being rolled back from the main journal file
   40542 **     and the checksum field does not match the record content.
   40543 **
   40544 ** Neither of these two scenarios are possible during a savepoint rollback.
   40545 **
   40546 ** If this is a savepoint rollback, then memory may have to be dynamically
   40547 ** allocated by this function. If this is the case and an allocation fails,
   40548 ** SQLITE_NOMEM is returned.
   40549 */
   40550 static int pager_playback_one_page(
   40551   Pager *pPager,                /* The pager being played back */
   40552   i64 *pOffset,                 /* Offset of record to playback */
   40553   Bitvec *pDone,                /* Bitvec of pages already played back */
   40554   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   40555   int isSavepnt                 /* True for a savepoint rollback */
   40556 ){
   40557   int rc;
   40558   PgHdr *pPg;                   /* An existing page in the cache */
   40559   Pgno pgno;                    /* The page number of a page in journal */
   40560   u32 cksum;                    /* Checksum used for sanity checking */
   40561   char *aData;                  /* Temporary storage for the page */
   40562   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   40563   int isSynced;                 /* True if journal page is synced */
   40564 
   40565   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   40566   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   40567   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   40568   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   40569 
   40570   aData = pPager->pTmpSpace;
   40571   assert( aData );         /* Temp storage must have already been allocated */
   40572   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   40573 
   40574   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   40575   ** or savepoint rollback done at the request of the caller) or this is
   40576   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   40577   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   40578   ** only reads from the main journal, not the sub-journal.
   40579   */
   40580   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   40581        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   40582   );
   40583   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   40584 
   40585   /* Read the page number and page data from the journal or sub-journal
   40586   ** file. Return an error code to the caller if an IO error occurs.
   40587   */
   40588   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   40589   rc = read32bits(jfd, *pOffset, &pgno);
   40590   if( rc!=SQLITE_OK ) return rc;
   40591   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   40592   if( rc!=SQLITE_OK ) return rc;
   40593   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   40594 
   40595   /* Sanity checking on the page.  This is more important that I originally
   40596   ** thought.  If a power failure occurs while the journal is being written,
   40597   ** it could cause invalid data to be written into the journal.  We need to
   40598   ** detect this invalid data (with high probability) and ignore it.
   40599   */
   40600   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   40601     assert( !isSavepnt );
   40602     return SQLITE_DONE;
   40603   }
   40604   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   40605     return SQLITE_OK;
   40606   }
   40607   if( isMainJrnl ){
   40608     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   40609     if( rc ) return rc;
   40610     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   40611       return SQLITE_DONE;
   40612     }
   40613   }
   40614 
   40615   /* If this page has already been played by before during the current
   40616   ** rollback, then don't bother to play it back again.
   40617   */
   40618   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   40619     return rc;
   40620   }
   40621 
   40622   /* When playing back page 1, restore the nReserve setting
   40623   */
   40624   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   40625     pPager->nReserve = ((u8*)aData)[20];
   40626     pagerReportSize(pPager);
   40627   }
   40628 
   40629   /* If the pager is in CACHEMOD state, then there must be a copy of this
   40630   ** page in the pager cache. In this case just update the pager cache,
   40631   ** not the database file. The page is left marked dirty in this case.
   40632   **
   40633   ** An exception to the above rule: If the database is in no-sync mode
   40634   ** and a page is moved during an incremental vacuum then the page may
   40635   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   40636   ** during a Movepage() call, then the page may not be in the cache
   40637   ** either. So the condition described in the above paragraph is not
   40638   ** assert()able.
   40639   **
   40640   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   40641   ** pager cache if it exists and the main file. The page is then marked
   40642   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   40643   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   40644   ** if the pager is in OPEN state.
   40645   **
   40646   ** Ticket #1171:  The statement journal might contain page content that is
   40647   ** different from the page content at the start of the transaction.
   40648   ** This occurs when a page is changed prior to the start of a statement
   40649   ** then changed again within the statement.  When rolling back such a
   40650   ** statement we must not write to the original database unless we know
   40651   ** for certain that original page contents are synced into the main rollback
   40652   ** journal.  Otherwise, a power loss might leave modified data in the
   40653   ** database file without an entry in the rollback journal that can
   40654   ** restore the database to its original form.  Two conditions must be
   40655   ** met before writing to the database files. (1) the database must be
   40656   ** locked.  (2) we know that the original page content is fully synced
   40657   ** in the main journal either because the page is not in cache or else
   40658   ** the page is marked as needSync==0.
   40659   **
   40660   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   40661   ** is possible to fail a statement on a database that does not yet exist.
   40662   ** Do not attempt to write if database file has never been opened.
   40663   */
   40664   if( pagerUseWal(pPager) ){
   40665     pPg = 0;
   40666   }else{
   40667     pPg = pager_lookup(pPager, pgno);
   40668   }
   40669   assert( pPg || !MEMDB );
   40670   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
   40671   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   40672            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   40673            (isMainJrnl?"main-journal":"sub-journal")
   40674   ));
   40675   if( isMainJrnl ){
   40676     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   40677   }else{
   40678     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   40679   }
   40680   if( isOpen(pPager->fd)
   40681    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   40682    && isSynced
   40683   ){
   40684     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   40685     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   40686     assert( !pagerUseWal(pPager) );
   40687     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
   40688     if( pgno>pPager->dbFileSize ){
   40689       pPager->dbFileSize = pgno;
   40690     }
   40691     if( pPager->pBackup ){
   40692       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   40693       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   40694       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   40695     }
   40696   }else if( !isMainJrnl && pPg==0 ){
   40697     /* If this is a rollback of a savepoint and data was not written to
   40698     ** the database and the page is not in-memory, there is a potential
   40699     ** problem. When the page is next fetched by the b-tree layer, it
   40700     ** will be read from the database file, which may or may not be
   40701     ** current.
   40702     **
   40703     ** There are a couple of different ways this can happen. All are quite
   40704     ** obscure. When running in synchronous mode, this can only happen
   40705     ** if the page is on the free-list at the start of the transaction, then
   40706     ** populated, then moved using sqlite3PagerMovepage().
   40707     **
   40708     ** The solution is to add an in-memory page to the cache containing
   40709     ** the data just read from the sub-journal. Mark the page as dirty
   40710     ** and if the pager requires a journal-sync, then mark the page as
   40711     ** requiring a journal-sync before it is written.
   40712     */
   40713     assert( isSavepnt );
   40714     assert( pPager->doNotSpill==0 );
   40715     pPager->doNotSpill++;
   40716     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
   40717     assert( pPager->doNotSpill==1 );
   40718     pPager->doNotSpill--;
   40719     if( rc!=SQLITE_OK ) return rc;
   40720     pPg->flags &= ~PGHDR_NEED_READ;
   40721     sqlite3PcacheMakeDirty(pPg);
   40722   }
   40723   if( pPg ){
   40724     /* No page should ever be explicitly rolled back that is in use, except
   40725     ** for page 1 which is held in use in order to keep the lock on the
   40726     ** database active. However such a page may be rolled back as a result
   40727     ** of an internal error resulting in an automatic call to
   40728     ** sqlite3PagerRollback().
   40729     */
   40730     void *pData;
   40731     pData = pPg->pData;
   40732     memcpy(pData, (u8*)aData, pPager->pageSize);
   40733     pPager->xReiniter(pPg);
   40734     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   40735       /* If the contents of this page were just restored from the main
   40736       ** journal file, then its content must be as they were when the
   40737       ** transaction was first opened. In this case we can mark the page
   40738       ** as clean, since there will be no need to write it out to the
   40739       ** database.
   40740       **
   40741       ** There is one exception to this rule. If the page is being rolled
   40742       ** back as part of a savepoint (or statement) rollback from an
   40743       ** unsynced portion of the main journal file, then it is not safe
   40744       ** to mark the page as clean. This is because marking the page as
   40745       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   40746       ** already in the journal file (recorded in Pager.pInJournal) and
   40747       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   40748       ** again within this transaction, it will be marked as dirty but
   40749       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   40750       ** be written out into the database file before its journal file
   40751       ** segment is synced. If a crash occurs during or following this,
   40752       ** database corruption may ensue.
   40753       */
   40754       assert( !pagerUseWal(pPager) );
   40755       sqlite3PcacheMakeClean(pPg);
   40756     }
   40757     pager_set_pagehash(pPg);
   40758 
   40759     /* If this was page 1, then restore the value of Pager.dbFileVers.
   40760     ** Do this before any decoding. */
   40761     if( pgno==1 ){
   40762       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   40763     }
   40764 
   40765     /* Decode the page just read from disk */
   40766     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   40767     sqlite3PcacheRelease(pPg);
   40768   }
   40769   return rc;
   40770 }
   40771 
   40772 /*
   40773 ** Parameter zMaster is the name of a master journal file. A single journal
   40774 ** file that referred to the master journal file has just been rolled back.
   40775 ** This routine checks if it is possible to delete the master journal file,
   40776 ** and does so if it is.
   40777 **
   40778 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   40779 ** available for use within this function.
   40780 **
   40781 ** When a master journal file is created, it is populated with the names
   40782 ** of all of its child journals, one after another, formatted as utf-8
   40783 ** encoded text. The end of each child journal file is marked with a
   40784 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   40785 ** file for a transaction involving two databases might be:
   40786 **
   40787 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   40788 **
   40789 ** A master journal file may only be deleted once all of its child
   40790 ** journals have been rolled back.
   40791 **
   40792 ** This function reads the contents of the master-journal file into
   40793 ** memory and loops through each of the child journal names. For
   40794 ** each child journal, it checks if:
   40795 **
   40796 **   * if the child journal exists, and if so
   40797 **   * if the child journal contains a reference to master journal
   40798 **     file zMaster
   40799 **
   40800 ** If a child journal can be found that matches both of the criteria
   40801 ** above, this function returns without doing anything. Otherwise, if
   40802 ** no such child journal can be found, file zMaster is deleted from
   40803 ** the file-system using sqlite3OsDelete().
   40804 **
   40805 ** If an IO error within this function, an error code is returned. This
   40806 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   40807 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   40808 ** occur, SQLITE_OK is returned.
   40809 **
   40810 ** TODO: This function allocates a single block of memory to load
   40811 ** the entire contents of the master journal file. This could be
   40812 ** a couple of kilobytes or so - potentially larger than the page
   40813 ** size.
   40814 */
   40815 static int pager_delmaster(Pager *pPager, const char *zMaster){
   40816   sqlite3_vfs *pVfs = pPager->pVfs;
   40817   int rc;                   /* Return code */
   40818   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   40819   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   40820   char *zMasterJournal = 0; /* Contents of master journal file */
   40821   i64 nMasterJournal;       /* Size of master journal file */
   40822   char *zJournal;           /* Pointer to one journal within MJ file */
   40823   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   40824   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   40825 
   40826   /* Allocate space for both the pJournal and pMaster file descriptors.
   40827   ** If successful, open the master journal file for reading.
   40828   */
   40829   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   40830   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   40831   if( !pMaster ){
   40832     rc = SQLITE_NOMEM;
   40833   }else{
   40834     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   40835     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   40836   }
   40837   if( rc!=SQLITE_OK ) goto delmaster_out;
   40838 
   40839   /* Load the entire master journal file into space obtained from
   40840   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   40841   ** sufficient space (in zMasterPtr) to hold the names of master
   40842   ** journal files extracted from regular rollback-journals.
   40843   */
   40844   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   40845   if( rc!=SQLITE_OK ) goto delmaster_out;
   40846   nMasterPtr = pVfs->mxPathname+1;
   40847   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   40848   if( !zMasterJournal ){
   40849     rc = SQLITE_NOMEM;
   40850     goto delmaster_out;
   40851   }
   40852   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   40853   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   40854   if( rc!=SQLITE_OK ) goto delmaster_out;
   40855   zMasterJournal[nMasterJournal] = 0;
   40856 
   40857   zJournal = zMasterJournal;
   40858   while( (zJournal-zMasterJournal)<nMasterJournal ){
   40859     int exists;
   40860     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   40861     if( rc!=SQLITE_OK ){
   40862       goto delmaster_out;
   40863     }
   40864     if( exists ){
   40865       /* One of the journals pointed to by the master journal exists.
   40866       ** Open it and check if it points at the master journal. If
   40867       ** so, return without deleting the master journal file.
   40868       */
   40869       int c;
   40870       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   40871       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   40872       if( rc!=SQLITE_OK ){
   40873         goto delmaster_out;
   40874       }
   40875 
   40876       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   40877       sqlite3OsClose(pJournal);
   40878       if( rc!=SQLITE_OK ){
   40879         goto delmaster_out;
   40880       }
   40881 
   40882       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   40883       if( c ){
   40884         /* We have a match. Do not delete the master journal file. */
   40885         goto delmaster_out;
   40886       }
   40887     }
   40888     zJournal += (sqlite3Strlen30(zJournal)+1);
   40889   }
   40890 
   40891   sqlite3OsClose(pMaster);
   40892   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   40893 
   40894 delmaster_out:
   40895   sqlite3_free(zMasterJournal);
   40896   if( pMaster ){
   40897     sqlite3OsClose(pMaster);
   40898     assert( !isOpen(pJournal) );
   40899     sqlite3_free(pMaster);
   40900   }
   40901   return rc;
   40902 }
   40903 
   40904 
   40905 /*
   40906 ** This function is used to change the actual size of the database
   40907 ** file in the file-system. This only happens when committing a transaction,
   40908 ** or rolling back a transaction (including rolling back a hot-journal).
   40909 **
   40910 ** If the main database file is not open, or the pager is not in either
   40911 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   40912 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   40913 ** If the file on disk is currently larger than nPage pages, then use the VFS
   40914 ** xTruncate() method to truncate it.
   40915 **
   40916 ** Or, it might might be the case that the file on disk is smaller than
   40917 ** nPage pages. Some operating system implementations can get confused if
   40918 ** you try to truncate a file to some size that is larger than it
   40919 ** currently is, so detect this case and write a single zero byte to
   40920 ** the end of the new file instead.
   40921 **
   40922 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   40923 ** the database file, return the error code to the caller.
   40924 */
   40925 static int pager_truncate(Pager *pPager, Pgno nPage){
   40926   int rc = SQLITE_OK;
   40927   assert( pPager->eState!=PAGER_ERROR );
   40928   assert( pPager->eState!=PAGER_READER );
   40929 
   40930   if( isOpen(pPager->fd)
   40931    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   40932   ){
   40933     i64 currentSize, newSize;
   40934     int szPage = pPager->pageSize;
   40935     assert( pPager->eLock==EXCLUSIVE_LOCK );
   40936     /* TODO: Is it safe to use Pager.dbFileSize here? */
   40937     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   40938     newSize = szPage*(i64)nPage;
   40939     if( rc==SQLITE_OK && currentSize!=newSize ){
   40940       if( currentSize>newSize ){
   40941         rc = sqlite3OsTruncate(pPager->fd, newSize);
   40942       }else if( (currentSize+szPage)<=newSize ){
   40943         char *pTmp = pPager->pTmpSpace;
   40944         memset(pTmp, 0, szPage);
   40945         testcase( (newSize-szPage) == currentSize );
   40946         testcase( (newSize-szPage) >  currentSize );
   40947         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
   40948       }
   40949       if( rc==SQLITE_OK ){
   40950         pPager->dbFileSize = nPage;
   40951       }
   40952     }
   40953   }
   40954   return rc;
   40955 }
   40956 
   40957 /*
   40958 ** Set the value of the Pager.sectorSize variable for the given
   40959 ** pager based on the value returned by the xSectorSize method
   40960 ** of the open database file. The sector size will be used used
   40961 ** to determine the size and alignment of journal header and
   40962 ** master journal pointers within created journal files.
   40963 **
   40964 ** For temporary files the effective sector size is always 512 bytes.
   40965 **
   40966 ** Otherwise, for non-temporary files, the effective sector size is
   40967 ** the value returned by the xSectorSize() method rounded up to 32 if
   40968 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   40969 ** is greater than MAX_SECTOR_SIZE.
   40970 **
   40971 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
   40972 ** the effective sector size to its minimum value (512).  The purpose of
   40973 ** pPager->sectorSize is to define the "blast radius" of bytes that
   40974 ** might change if a crash occurs while writing to a single byte in
   40975 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
   40976 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
   40977 ** size.  For backwards compatibility of the rollback journal file format,
   40978 ** we cannot reduce the effective sector size below 512.
   40979 */
   40980 static void setSectorSize(Pager *pPager){
   40981   assert( isOpen(pPager->fd) || pPager->tempFile );
   40982 
   40983   if( pPager->tempFile
   40984    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
   40985               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   40986   ){
   40987     /* Sector size doesn't matter for temporary files. Also, the file
   40988     ** may not have been opened yet, in which case the OsSectorSize()
   40989     ** call will segfault. */
   40990     pPager->sectorSize = 512;
   40991   }else{
   40992     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
   40993     if( pPager->sectorSize<32 ){
   40994       pPager->sectorSize = 512;
   40995     }
   40996     if( pPager->sectorSize>MAX_SECTOR_SIZE ){
   40997       assert( MAX_SECTOR_SIZE>=512 );
   40998       pPager->sectorSize = MAX_SECTOR_SIZE;
   40999     }
   41000   }
   41001 }
   41002 
   41003 /*
   41004 ** Playback the journal and thus restore the database file to
   41005 ** the state it was in before we started making changes.
   41006 **
   41007 ** The journal file format is as follows:
   41008 **
   41009 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   41010 **  (2)  4 byte big-endian integer which is the number of valid page records
   41011 **       in the journal.  If this value is 0xffffffff, then compute the
   41012 **       number of page records from the journal size.
   41013 **  (3)  4 byte big-endian integer which is the initial value for the
   41014 **       sanity checksum.
   41015 **  (4)  4 byte integer which is the number of pages to truncate the
   41016 **       database to during a rollback.
   41017 **  (5)  4 byte big-endian integer which is the sector size.  The header
   41018 **       is this many bytes in size.
   41019 **  (6)  4 byte big-endian integer which is the page size.
   41020 **  (7)  zero padding out to the next sector size.
   41021 **  (8)  Zero or more pages instances, each as follows:
   41022 **        +  4 byte page number.
   41023 **        +  pPager->pageSize bytes of data.
   41024 **        +  4 byte checksum
   41025 **
   41026 ** When we speak of the journal header, we mean the first 7 items above.
   41027 ** Each entry in the journal is an instance of the 8th item.
   41028 **
   41029 ** Call the value from the second bullet "nRec".  nRec is the number of
   41030 ** valid page entries in the journal.  In most cases, you can compute the
   41031 ** value of nRec from the size of the journal file.  But if a power
   41032 ** failure occurred while the journal was being written, it could be the
   41033 ** case that the size of the journal file had already been increased but
   41034 ** the extra entries had not yet made it safely to disk.  In such a case,
   41035 ** the value of nRec computed from the file size would be too large.  For
   41036 ** that reason, we always use the nRec value in the header.
   41037 **
   41038 ** If the nRec value is 0xffffffff it means that nRec should be computed
   41039 ** from the file size.  This value is used when the user selects the
   41040 ** no-sync option for the journal.  A power failure could lead to corruption
   41041 ** in this case.  But for things like temporary table (which will be
   41042 ** deleted when the power is restored) we don't care.
   41043 **
   41044 ** If the file opened as the journal file is not a well-formed
   41045 ** journal file then all pages up to the first corrupted page are rolled
   41046 ** back (or no pages if the journal header is corrupted). The journal file
   41047 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   41048 ** been encountered.
   41049 **
   41050 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   41051 ** and an error code is returned.
   41052 **
   41053 ** The isHot parameter indicates that we are trying to rollback a journal
   41054 ** that might be a hot journal.  Or, it could be that the journal is
   41055 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   41056 ** If the journal really is hot, reset the pager cache prior rolling
   41057 ** back any content.  If the journal is merely persistent, no reset is
   41058 ** needed.
   41059 */
   41060 static int pager_playback(Pager *pPager, int isHot){
   41061   sqlite3_vfs *pVfs = pPager->pVfs;
   41062   i64 szJ;                 /* Size of the journal file in bytes */
   41063   u32 nRec;                /* Number of Records in the journal */
   41064   u32 u;                   /* Unsigned loop counter */
   41065   Pgno mxPg = 0;           /* Size of the original file in pages */
   41066   int rc;                  /* Result code of a subroutine */
   41067   int res = 1;             /* Value returned by sqlite3OsAccess() */
   41068   char *zMaster = 0;       /* Name of master journal file if any */
   41069   int needPagerReset;      /* True to reset page prior to first page rollback */
   41070 
   41071   /* Figure out how many records are in the journal.  Abort early if
   41072   ** the journal is empty.
   41073   */
   41074   assert( isOpen(pPager->jfd) );
   41075   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   41076   if( rc!=SQLITE_OK ){
   41077     goto end_playback;
   41078   }
   41079 
   41080   /* Read the master journal name from the journal, if it is present.
   41081   ** If a master journal file name is specified, but the file is not
   41082   ** present on disk, then the journal is not hot and does not need to be
   41083   ** played back.
   41084   **
   41085   ** TODO: Technically the following is an error because it assumes that
   41086   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   41087   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   41088   **  mxPathname is 512, which is the same as the minimum allowable value
   41089   ** for pageSize.
   41090   */
   41091   zMaster = pPager->pTmpSpace;
   41092   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   41093   if( rc==SQLITE_OK && zMaster[0] ){
   41094     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   41095   }
   41096   zMaster = 0;
   41097   if( rc!=SQLITE_OK || !res ){
   41098     goto end_playback;
   41099   }
   41100   pPager->journalOff = 0;
   41101   needPagerReset = isHot;
   41102 
   41103   /* This loop terminates either when a readJournalHdr() or
   41104   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   41105   ** occurs.
   41106   */
   41107   while( 1 ){
   41108     /* Read the next journal header from the journal file.  If there are
   41109     ** not enough bytes left in the journal file for a complete header, or
   41110     ** it is corrupted, then a process must have failed while writing it.
   41111     ** This indicates nothing more needs to be rolled back.
   41112     */
   41113     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   41114     if( rc!=SQLITE_OK ){
   41115       if( rc==SQLITE_DONE ){
   41116         rc = SQLITE_OK;
   41117       }
   41118       goto end_playback;
   41119     }
   41120 
   41121     /* If nRec is 0xffffffff, then this journal was created by a process
   41122     ** working in no-sync mode. This means that the rest of the journal
   41123     ** file consists of pages, there are no more journal headers. Compute
   41124     ** the value of nRec based on this assumption.
   41125     */
   41126     if( nRec==0xffffffff ){
   41127       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   41128       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   41129     }
   41130 
   41131     /* If nRec is 0 and this rollback is of a transaction created by this
   41132     ** process and if this is the final header in the journal, then it means
   41133     ** that this part of the journal was being filled but has not yet been
   41134     ** synced to disk.  Compute the number of pages based on the remaining
   41135     ** size of the file.
   41136     **
   41137     ** The third term of the test was added to fix ticket #2565.
   41138     ** When rolling back a hot journal, nRec==0 always means that the next
   41139     ** chunk of the journal contains zero pages to be rolled back.  But
   41140     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   41141     ** the journal, it means that the journal might contain additional
   41142     ** pages that need to be rolled back and that the number of pages
   41143     ** should be computed based on the journal file size.
   41144     */
   41145     if( nRec==0 && !isHot &&
   41146         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   41147       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   41148     }
   41149 
   41150     /* If this is the first header read from the journal, truncate the
   41151     ** database file back to its original size.
   41152     */
   41153     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   41154       rc = pager_truncate(pPager, mxPg);
   41155       if( rc!=SQLITE_OK ){
   41156         goto end_playback;
   41157       }
   41158       pPager->dbSize = mxPg;
   41159     }
   41160 
   41161     /* Copy original pages out of the journal and back into the
   41162     ** database file and/or page cache.
   41163     */
   41164     for(u=0; u<nRec; u++){
   41165       if( needPagerReset ){
   41166         pager_reset(pPager);
   41167         needPagerReset = 0;
   41168       }
   41169       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   41170       if( rc!=SQLITE_OK ){
   41171         if( rc==SQLITE_DONE ){
   41172           pPager->journalOff = szJ;
   41173           break;
   41174         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   41175           /* If the journal has been truncated, simply stop reading and
   41176           ** processing the journal. This might happen if the journal was
   41177           ** not completely written and synced prior to a crash.  In that
   41178           ** case, the database should have never been written in the
   41179           ** first place so it is OK to simply abandon the rollback. */
   41180           rc = SQLITE_OK;
   41181           goto end_playback;
   41182         }else{
   41183           /* If we are unable to rollback, quit and return the error
   41184           ** code.  This will cause the pager to enter the error state
   41185           ** so that no further harm will be done.  Perhaps the next
   41186           ** process to come along will be able to rollback the database.
   41187           */
   41188           goto end_playback;
   41189         }
   41190       }
   41191     }
   41192   }
   41193   /*NOTREACHED*/
   41194   assert( 0 );
   41195 
   41196 end_playback:
   41197   /* Following a rollback, the database file should be back in its original
   41198   ** state prior to the start of the transaction, so invoke the
   41199   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   41200   ** assertion that the transaction counter was modified.
   41201   */
   41202 #ifdef SQLITE_DEBUG
   41203   if( pPager->fd->pMethods ){
   41204     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
   41205   }
   41206 #endif
   41207 
   41208   /* If this playback is happening automatically as a result of an IO or
   41209   ** malloc error that occurred after the change-counter was updated but
   41210   ** before the transaction was committed, then the change-counter
   41211   ** modification may just have been reverted. If this happens in exclusive
   41212   ** mode, then subsequent transactions performed by the connection will not
   41213   ** update the change-counter at all. This may lead to cache inconsistency
   41214   ** problems for other processes at some point in the future. So, just
   41215   ** in case this has happened, clear the changeCountDone flag now.
   41216   */
   41217   pPager->changeCountDone = pPager->tempFile;
   41218 
   41219   if( rc==SQLITE_OK ){
   41220     zMaster = pPager->pTmpSpace;
   41221     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   41222     testcase( rc!=SQLITE_OK );
   41223   }
   41224   if( rc==SQLITE_OK
   41225    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   41226   ){
   41227     rc = sqlite3PagerSync(pPager);
   41228   }
   41229   if( rc==SQLITE_OK ){
   41230     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
   41231     testcase( rc!=SQLITE_OK );
   41232   }
   41233   if( rc==SQLITE_OK && zMaster[0] && res ){
   41234     /* If there was a master journal and this routine will return success,
   41235     ** see if it is possible to delete the master journal.
   41236     */
   41237     rc = pager_delmaster(pPager, zMaster);
   41238     testcase( rc!=SQLITE_OK );
   41239   }
   41240 
   41241   /* The Pager.sectorSize variable may have been updated while rolling
   41242   ** back a journal created by a process with a different sector size
   41243   ** value. Reset it to the correct value for this process.
   41244   */
   41245   setSectorSize(pPager);
   41246   return rc;
   41247 }
   41248 
   41249 
   41250 /*
   41251 ** Read the content for page pPg out of the database file and into
   41252 ** pPg->pData. A shared lock or greater must be held on the database
   41253 ** file before this function is called.
   41254 **
   41255 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   41256 ** the value read from the database file.
   41257 **
   41258 ** If an IO error occurs, then the IO error is returned to the caller.
   41259 ** Otherwise, SQLITE_OK is returned.
   41260 */
   41261 static int readDbPage(PgHdr *pPg){
   41262   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   41263   Pgno pgno = pPg->pgno;       /* Page number to read */
   41264   int rc = SQLITE_OK;          /* Return code */
   41265   int isInWal = 0;             /* True if page is in log file */
   41266   int pgsz = pPager->pageSize; /* Number of bytes to read */
   41267 
   41268   assert( pPager->eState>=PAGER_READER && !MEMDB );
   41269   assert( isOpen(pPager->fd) );
   41270 
   41271   if( NEVER(!isOpen(pPager->fd)) ){
   41272     assert( pPager->tempFile );
   41273     memset(pPg->pData, 0, pPager->pageSize);
   41274     return SQLITE_OK;
   41275   }
   41276 
   41277   if( pagerUseWal(pPager) ){
   41278     /* Try to pull the page from the write-ahead log. */
   41279     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
   41280   }
   41281   if( rc==SQLITE_OK && !isInWal ){
   41282     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
   41283     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
   41284     if( rc==SQLITE_IOERR_SHORT_READ ){
   41285       rc = SQLITE_OK;
   41286     }
   41287   }
   41288 
   41289   if( pgno==1 ){
   41290     if( rc ){
   41291       /* If the read is unsuccessful, set the dbFileVers[] to something
   41292       ** that will never be a valid file version.  dbFileVers[] is a copy
   41293       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   41294       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   41295       ** should be page numbers which are never 0xffffffff.  So filling
   41296       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   41297       **
   41298       ** For an encrypted database, the situation is more complex:  bytes
   41299       ** 24..39 of the database are white noise.  But the probability of
   41300       ** white noising equaling 16 bytes of 0xff is vanishingly small so
   41301       ** we should still be ok.
   41302       */
   41303       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   41304     }else{
   41305       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   41306       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   41307     }
   41308   }
   41309   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   41310 
   41311   PAGER_INCR(sqlite3_pager_readdb_count);
   41312   PAGER_INCR(pPager->nRead);
   41313   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   41314   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   41315                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   41316 
   41317   return rc;
   41318 }
   41319 
   41320 /*
   41321 ** Update the value of the change-counter at offsets 24 and 92 in
   41322 ** the header and the sqlite version number at offset 96.
   41323 **
   41324 ** This is an unconditional update.  See also the pager_incr_changecounter()
   41325 ** routine which only updates the change-counter if the update is actually
   41326 ** needed, as determined by the pPager->changeCountDone state variable.
   41327 */
   41328 static void pager_write_changecounter(PgHdr *pPg){
   41329   u32 change_counter;
   41330 
   41331   /* Increment the value just read and write it back to byte 24. */
   41332   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   41333   put32bits(((char*)pPg->pData)+24, change_counter);
   41334 
   41335   /* Also store the SQLite version number in bytes 96..99 and in
   41336   ** bytes 92..95 store the change counter for which the version number
   41337   ** is valid. */
   41338   put32bits(((char*)pPg->pData)+92, change_counter);
   41339   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   41340 }
   41341 
   41342 #ifndef SQLITE_OMIT_WAL
   41343 /*
   41344 ** This function is invoked once for each page that has already been
   41345 ** written into the log file when a WAL transaction is rolled back.
   41346 ** Parameter iPg is the page number of said page. The pCtx argument
   41347 ** is actually a pointer to the Pager structure.
   41348 **
   41349 ** If page iPg is present in the cache, and has no outstanding references,
   41350 ** it is discarded. Otherwise, if there are one or more outstanding
   41351 ** references, the page content is reloaded from the database. If the
   41352 ** attempt to reload content from the database is required and fails,
   41353 ** return an SQLite error code. Otherwise, SQLITE_OK.
   41354 */
   41355 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   41356   int rc = SQLITE_OK;
   41357   Pager *pPager = (Pager *)pCtx;
   41358   PgHdr *pPg;
   41359 
   41360   pPg = sqlite3PagerLookup(pPager, iPg);
   41361   if( pPg ){
   41362     if( sqlite3PcachePageRefcount(pPg)==1 ){
   41363       sqlite3PcacheDrop(pPg);
   41364     }else{
   41365       rc = readDbPage(pPg);
   41366       if( rc==SQLITE_OK ){
   41367         pPager->xReiniter(pPg);
   41368       }
   41369       sqlite3PagerUnref(pPg);
   41370     }
   41371   }
   41372 
   41373   /* Normally, if a transaction is rolled back, any backup processes are
   41374   ** updated as data is copied out of the rollback journal and into the
   41375   ** database. This is not generally possible with a WAL database, as
   41376   ** rollback involves simply truncating the log file. Therefore, if one
   41377   ** or more frames have already been written to the log (and therefore
   41378   ** also copied into the backup databases) as part of this transaction,
   41379   ** the backups must be restarted.
   41380   */
   41381   sqlite3BackupRestart(pPager->pBackup);
   41382 
   41383   return rc;
   41384 }
   41385 
   41386 /*
   41387 ** This function is called to rollback a transaction on a WAL database.
   41388 */
   41389 static int pagerRollbackWal(Pager *pPager){
   41390   int rc;                         /* Return Code */
   41391   PgHdr *pList;                   /* List of dirty pages to revert */
   41392 
   41393   /* For all pages in the cache that are currently dirty or have already
   41394   ** been written (but not committed) to the log file, do one of the
   41395   ** following:
   41396   **
   41397   **   + Discard the cached page (if refcount==0), or
   41398   **   + Reload page content from the database (if refcount>0).
   41399   */
   41400   pPager->dbSize = pPager->dbOrigSize;
   41401   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   41402   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   41403   while( pList && rc==SQLITE_OK ){
   41404     PgHdr *pNext = pList->pDirty;
   41405     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   41406     pList = pNext;
   41407   }
   41408 
   41409   return rc;
   41410 }
   41411 
   41412 /*
   41413 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   41414 ** the contents of the list of pages headed by pList (connected by pDirty),
   41415 ** this function notifies any active backup processes that the pages have
   41416 ** changed.
   41417 **
   41418 ** The list of pages passed into this routine is always sorted by page number.
   41419 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   41420 */
   41421 static int pagerWalFrames(
   41422   Pager *pPager,                  /* Pager object */
   41423   PgHdr *pList,                   /* List of frames to log */
   41424   Pgno nTruncate,                 /* Database size after this commit */
   41425   int isCommit                    /* True if this is a commit */
   41426 ){
   41427   int rc;                         /* Return code */
   41428 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
   41429   PgHdr *p;                       /* For looping over pages */
   41430 #endif
   41431 
   41432   assert( pPager->pWal );
   41433   assert( pList );
   41434 #ifdef SQLITE_DEBUG
   41435   /* Verify that the page list is in accending order */
   41436   for(p=pList; p && p->pDirty; p=p->pDirty){
   41437     assert( p->pgno < p->pDirty->pgno );
   41438   }
   41439 #endif
   41440 
   41441   if( isCommit ){
   41442     /* If a WAL transaction is being committed, there is no point in writing
   41443     ** any pages with page numbers greater than nTruncate into the WAL file.
   41444     ** They will never be read by any client. So remove them from the pDirty
   41445     ** list here. */
   41446     PgHdr *p;
   41447     PgHdr **ppNext = &pList;
   41448     for(p=pList; (*ppNext = p); p=p->pDirty){
   41449       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
   41450     }
   41451     assert( pList );
   41452   }
   41453 
   41454   if( pList->pgno==1 ) pager_write_changecounter(pList);
   41455   rc = sqlite3WalFrames(pPager->pWal,
   41456       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   41457   );
   41458   if( rc==SQLITE_OK && pPager->pBackup ){
   41459     PgHdr *p;
   41460     for(p=pList; p; p=p->pDirty){
   41461       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   41462     }
   41463   }
   41464 
   41465 #ifdef SQLITE_CHECK_PAGES
   41466   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   41467   for(p=pList; p; p=p->pDirty){
   41468     pager_set_pagehash(p);
   41469   }
   41470 #endif
   41471 
   41472   return rc;
   41473 }
   41474 
   41475 /*
   41476 ** Begin a read transaction on the WAL.
   41477 **
   41478 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   41479 ** makes a snapshot of the database at the current point in time and preserves
   41480 ** that snapshot for use by the reader in spite of concurrently changes by
   41481 ** other writers or checkpointers.
   41482 */
   41483 static int pagerBeginReadTransaction(Pager *pPager){
   41484   int rc;                         /* Return code */
   41485   int changed = 0;                /* True if cache must be reset */
   41486 
   41487   assert( pagerUseWal(pPager) );
   41488   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   41489 
   41490   /* sqlite3WalEndReadTransaction() was not called for the previous
   41491   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   41492   ** are in locking_mode=NORMAL and EndRead() was previously called,
   41493   ** the duplicate call is harmless.
   41494   */
   41495   sqlite3WalEndReadTransaction(pPager->pWal);
   41496 
   41497   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   41498   if( rc!=SQLITE_OK || changed ){
   41499     pager_reset(pPager);
   41500   }
   41501 
   41502   return rc;
   41503 }
   41504 #endif
   41505 
   41506 /*
   41507 ** This function is called as part of the transition from PAGER_OPEN
   41508 ** to PAGER_READER state to determine the size of the database file
   41509 ** in pages (assuming the page size currently stored in Pager.pageSize).
   41510 **
   41511 ** If no error occurs, SQLITE_OK is returned and the size of the database
   41512 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   41513 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   41514 */
   41515 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   41516   Pgno nPage;                     /* Value to return via *pnPage */
   41517 
   41518   /* Query the WAL sub-system for the database size. The WalDbsize()
   41519   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   41520   ** if the database size is not available. The database size is not
   41521   ** available from the WAL sub-system if the log file is empty or
   41522   ** contains no valid committed transactions.
   41523   */
   41524   assert( pPager->eState==PAGER_OPEN );
   41525   assert( pPager->eLock>=SHARED_LOCK );
   41526   nPage = sqlite3WalDbsize(pPager->pWal);
   41527 
   41528   /* If the database size was not available from the WAL sub-system,
   41529   ** determine it based on the size of the database file. If the size
   41530   ** of the database file is not an integer multiple of the page-size,
   41531   ** round down to the nearest page. Except, any file larger than 0
   41532   ** bytes in size is considered to contain at least one page.
   41533   */
   41534   if( nPage==0 ){
   41535     i64 n = 0;                    /* Size of db file in bytes */
   41536     assert( isOpen(pPager->fd) || pPager->tempFile );
   41537     if( isOpen(pPager->fd) ){
   41538       int rc = sqlite3OsFileSize(pPager->fd, &n);
   41539       if( rc!=SQLITE_OK ){
   41540         return rc;
   41541       }
   41542     }
   41543     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
   41544   }
   41545 
   41546   /* If the current number of pages in the file is greater than the
   41547   ** configured maximum pager number, increase the allowed limit so
   41548   ** that the file can be read.
   41549   */
   41550   if( nPage>pPager->mxPgno ){
   41551     pPager->mxPgno = (Pgno)nPage;
   41552   }
   41553 
   41554   *pnPage = nPage;
   41555   return SQLITE_OK;
   41556 }
   41557 
   41558 #ifndef SQLITE_OMIT_WAL
   41559 /*
   41560 ** Check if the *-wal file that corresponds to the database opened by pPager
   41561 ** exists if the database is not empy, or verify that the *-wal file does
   41562 ** not exist (by deleting it) if the database file is empty.
   41563 **
   41564 ** If the database is not empty and the *-wal file exists, open the pager
   41565 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   41566 ** if no error occurs, make sure Pager.journalMode is not set to
   41567 ** PAGER_JOURNALMODE_WAL.
   41568 **
   41569 ** Return SQLITE_OK or an error code.
   41570 **
   41571 ** The caller must hold a SHARED lock on the database file to call this
   41572 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   41573 ** a WAL on a none-empty database, this ensures there is no race condition
   41574 ** between the xAccess() below and an xDelete() being executed by some
   41575 ** other connection.
   41576 */
   41577 static int pagerOpenWalIfPresent(Pager *pPager){
   41578   int rc = SQLITE_OK;
   41579   assert( pPager->eState==PAGER_OPEN );
   41580   assert( pPager->eLock>=SHARED_LOCK );
   41581 
   41582   if( !pPager->tempFile ){
   41583     int isWal;                    /* True if WAL file exists */
   41584     Pgno nPage;                   /* Size of the database file */
   41585 
   41586     rc = pagerPagecount(pPager, &nPage);
   41587     if( rc ) return rc;
   41588     if( nPage==0 ){
   41589       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   41590       isWal = 0;
   41591     }else{
   41592       rc = sqlite3OsAccess(
   41593           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   41594       );
   41595     }
   41596     if( rc==SQLITE_OK ){
   41597       if( isWal ){
   41598         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   41599         rc = sqlite3PagerOpenWal(pPager, 0);
   41600       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   41601         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   41602       }
   41603     }
   41604   }
   41605   return rc;
   41606 }
   41607 #endif
   41608 
   41609 /*
   41610 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   41611 ** the entire master journal file. The case pSavepoint==NULL occurs when
   41612 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   41613 ** savepoint.
   41614 **
   41615 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   41616 ** being rolled back), then the rollback consists of up to three stages,
   41617 ** performed in the order specified:
   41618 **
   41619 **   * Pages are played back from the main journal starting at byte
   41620 **     offset PagerSavepoint.iOffset and continuing to
   41621 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   41622 **     file if PagerSavepoint.iHdrOffset is zero.
   41623 **
   41624 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   41625 **     back starting from the journal header immediately following
   41626 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   41627 **
   41628 **   * Pages are then played back from the sub-journal file, starting
   41629 **     with the PagerSavepoint.iSubRec and continuing to the end of
   41630 **     the journal file.
   41631 **
   41632 ** Throughout the rollback process, each time a page is rolled back, the
   41633 ** corresponding bit is set in a bitvec structure (variable pDone in the
   41634 ** implementation below). This is used to ensure that a page is only
   41635 ** rolled back the first time it is encountered in either journal.
   41636 **
   41637 ** If pSavepoint is NULL, then pages are only played back from the main
   41638 ** journal file. There is no need for a bitvec in this case.
   41639 **
   41640 ** In either case, before playback commences the Pager.dbSize variable
   41641 ** is reset to the value that it held at the start of the savepoint
   41642 ** (or transaction). No page with a page-number greater than this value
   41643 ** is played back. If one is encountered it is simply skipped.
   41644 */
   41645 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   41646   i64 szJ;                 /* Effective size of the main journal */
   41647   i64 iHdrOff;             /* End of first segment of main-journal records */
   41648   int rc = SQLITE_OK;      /* Return code */
   41649   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   41650 
   41651   assert( pPager->eState!=PAGER_ERROR );
   41652   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   41653 
   41654   /* Allocate a bitvec to use to store the set of pages rolled back */
   41655   if( pSavepoint ){
   41656     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   41657     if( !pDone ){
   41658       return SQLITE_NOMEM;
   41659     }
   41660   }
   41661 
   41662   /* Set the database size back to the value it was before the savepoint
   41663   ** being reverted was opened.
   41664   */
   41665   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   41666   pPager->changeCountDone = pPager->tempFile;
   41667 
   41668   if( !pSavepoint && pagerUseWal(pPager) ){
   41669     return pagerRollbackWal(pPager);
   41670   }
   41671 
   41672   /* Use pPager->journalOff as the effective size of the main rollback
   41673   ** journal.  The actual file might be larger than this in
   41674   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   41675   ** past pPager->journalOff is off-limits to us.
   41676   */
   41677   szJ = pPager->journalOff;
   41678   assert( pagerUseWal(pPager)==0 || szJ==0 );
   41679 
   41680   /* Begin by rolling back records from the main journal starting at
   41681   ** PagerSavepoint.iOffset and continuing to the next journal header.
   41682   ** There might be records in the main journal that have a page number
   41683   ** greater than the current database size (pPager->dbSize) but those
   41684   ** will be skipped automatically.  Pages are added to pDone as they
   41685   ** are played back.
   41686   */
   41687   if( pSavepoint && !pagerUseWal(pPager) ){
   41688     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   41689     pPager->journalOff = pSavepoint->iOffset;
   41690     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   41691       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   41692     }
   41693     assert( rc!=SQLITE_DONE );
   41694   }else{
   41695     pPager->journalOff = 0;
   41696   }
   41697 
   41698   /* Continue rolling back records out of the main journal starting at
   41699   ** the first journal header seen and continuing until the effective end
   41700   ** of the main journal file.  Continue to skip out-of-range pages and
   41701   ** continue adding pages rolled back to pDone.
   41702   */
   41703   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   41704     u32 ii;            /* Loop counter */
   41705     u32 nJRec = 0;     /* Number of Journal Records */
   41706     u32 dummy;
   41707     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   41708     assert( rc!=SQLITE_DONE );
   41709 
   41710     /*
   41711     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   41712     ** test is related to ticket #2565.  See the discussion in the
   41713     ** pager_playback() function for additional information.
   41714     */
   41715     if( nJRec==0
   41716      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   41717     ){
   41718       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   41719     }
   41720     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   41721       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   41722     }
   41723     assert( rc!=SQLITE_DONE );
   41724   }
   41725   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   41726 
   41727   /* Finally,  rollback pages from the sub-journal.  Page that were
   41728   ** previously rolled back out of the main journal (and are hence in pDone)
   41729   ** will be skipped.  Out-of-range pages are also skipped.
   41730   */
   41731   if( pSavepoint ){
   41732     u32 ii;            /* Loop counter */
   41733     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
   41734 
   41735     if( pagerUseWal(pPager) ){
   41736       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   41737     }
   41738     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   41739       assert( offset==(i64)ii*(4+pPager->pageSize) );
   41740       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   41741     }
   41742     assert( rc!=SQLITE_DONE );
   41743   }
   41744 
   41745   sqlite3BitvecDestroy(pDone);
   41746   if( rc==SQLITE_OK ){
   41747     pPager->journalOff = szJ;
   41748   }
   41749 
   41750   return rc;
   41751 }
   41752 
   41753 /*
   41754 ** Change the maximum number of in-memory pages that are allowed.
   41755 */
   41756 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   41757   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   41758 }
   41759 
   41760 /*
   41761 ** Free as much memory as possible from the pager.
   41762 */
   41763 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
   41764   sqlite3PcacheShrink(pPager->pPCache);
   41765 }
   41766 
   41767 /*
   41768 ** Adjust the robustness of the database to damage due to OS crashes
   41769 ** or power failures by changing the number of syncs()s when writing
   41770 ** the rollback journal.  There are three levels:
   41771 **
   41772 **    OFF       sqlite3OsSync() is never called.  This is the default
   41773 **              for temporary and transient files.
   41774 **
   41775 **    NORMAL    The journal is synced once before writes begin on the
   41776 **              database.  This is normally adequate protection, but
   41777 **              it is theoretically possible, though very unlikely,
   41778 **              that an inopertune power failure could leave the journal
   41779 **              in a state which would cause damage to the database
   41780 **              when it is rolled back.
   41781 **
   41782 **    FULL      The journal is synced twice before writes begin on the
   41783 **              database (with some additional information - the nRec field
   41784 **              of the journal header - being written in between the two
   41785 **              syncs).  If we assume that writing a
   41786 **              single disk sector is atomic, then this mode provides
   41787 **              assurance that the journal will not be corrupted to the
   41788 **              point of causing damage to the database during rollback.
   41789 **
   41790 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   41791 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   41792 ** prior to the start of checkpoint and that the database file is synced
   41793 ** at the conclusion of the checkpoint if the entire content of the WAL
   41794 ** was written back into the database.  But no sync operations occur for
   41795 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   41796 ** file is synced following each commit operation, in addition to the
   41797 ** syncs associated with NORMAL.
   41798 **
   41799 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   41800 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   41801 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   41802 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   41803 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   41804 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   41805 ** the xSync primitive is called and is relevant to all platforms.
   41806 **
   41807 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   41808 ** and FULL=3.
   41809 */
   41810 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   41811 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
   41812   Pager *pPager,        /* The pager to set safety level for */
   41813   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   41814   int bFullFsync,       /* PRAGMA fullfsync */
   41815   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
   41816 ){
   41817   assert( level>=1 && level<=3 );
   41818   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   41819   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   41820   if( pPager->noSync ){
   41821     pPager->syncFlags = 0;
   41822     pPager->ckptSyncFlags = 0;
   41823   }else if( bFullFsync ){
   41824     pPager->syncFlags = SQLITE_SYNC_FULL;
   41825     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   41826   }else if( bCkptFullFsync ){
   41827     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   41828     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   41829   }else{
   41830     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   41831     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   41832   }
   41833   pPager->walSyncFlags = pPager->syncFlags;
   41834   if( pPager->fullSync ){
   41835     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
   41836   }
   41837 }
   41838 #endif
   41839 
   41840 /*
   41841 ** The following global variable is incremented whenever the library
   41842 ** attempts to open a temporary file.  This information is used for
   41843 ** testing and analysis only.
   41844 */
   41845 #ifdef SQLITE_TEST
   41846 SQLITE_API int sqlite3_opentemp_count = 0;
   41847 #endif
   41848 
   41849 /*
   41850 ** Open a temporary file.
   41851 **
   41852 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   41853 ** or some other error code if we fail. The OS will automatically
   41854 ** delete the temporary file when it is closed.
   41855 **
   41856 ** The flags passed to the VFS layer xOpen() call are those specified
   41857 ** by parameter vfsFlags ORed with the following:
   41858 **
   41859 **     SQLITE_OPEN_READWRITE
   41860 **     SQLITE_OPEN_CREATE
   41861 **     SQLITE_OPEN_EXCLUSIVE
   41862 **     SQLITE_OPEN_DELETEONCLOSE
   41863 */
   41864 static int pagerOpentemp(
   41865   Pager *pPager,        /* The pager object */
   41866   sqlite3_file *pFile,  /* Write the file descriptor here */
   41867   int vfsFlags          /* Flags passed through to the VFS */
   41868 ){
   41869   int rc;               /* Return code */
   41870 
   41871 #ifdef SQLITE_TEST
   41872   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   41873 #endif
   41874 
   41875   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   41876             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   41877   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   41878   assert( rc!=SQLITE_OK || isOpen(pFile) );
   41879   return rc;
   41880 }
   41881 
   41882 /*
   41883 ** Set the busy handler function.
   41884 **
   41885 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   41886 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   41887 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   41888 ** lock. It does *not* invoke the busy handler when upgrading from
   41889 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   41890 ** (which occurs during hot-journal rollback). Summary:
   41891 **
   41892 **   Transition                        | Invokes xBusyHandler
   41893 **   --------------------------------------------------------
   41894 **   NO_LOCK       -> SHARED_LOCK      | Yes
   41895 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   41896 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   41897 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   41898 **
   41899 ** If the busy-handler callback returns non-zero, the lock is
   41900 ** retried. If it returns zero, then the SQLITE_BUSY error is
   41901 ** returned to the caller of the pager API function.
   41902 */
   41903 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   41904   Pager *pPager,                       /* Pager object */
   41905   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   41906   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   41907 ){
   41908   pPager->xBusyHandler = xBusyHandler;
   41909   pPager->pBusyHandlerArg = pBusyHandlerArg;
   41910 }
   41911 
   41912 /*
   41913 ** Change the page size used by the Pager object. The new page size
   41914 ** is passed in *pPageSize.
   41915 **
   41916 ** If the pager is in the error state when this function is called, it
   41917 ** is a no-op. The value returned is the error state error code (i.e.
   41918 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   41919 **
   41920 ** Otherwise, if all of the following are true:
   41921 **
   41922 **   * the new page size (value of *pPageSize) is valid (a power
   41923 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   41924 **
   41925 **   * there are no outstanding page references, and
   41926 **
   41927 **   * the database is either not an in-memory database or it is
   41928 **     an in-memory database that currently consists of zero pages.
   41929 **
   41930 ** then the pager object page size is set to *pPageSize.
   41931 **
   41932 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   41933 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   41934 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   41935 ** In all other cases, SQLITE_OK is returned.
   41936 **
   41937 ** If the page size is not changed, either because one of the enumerated
   41938 ** conditions above is not true, the pager was in error state when this
   41939 ** function was called, or because the memory allocation attempt failed,
   41940 ** then *pPageSize is set to the old, retained page size before returning.
   41941 */
   41942 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   41943   int rc = SQLITE_OK;
   41944 
   41945   /* It is not possible to do a full assert_pager_state() here, as this
   41946   ** function may be called from within PagerOpen(), before the state
   41947   ** of the Pager object is internally consistent.
   41948   **
   41949   ** At one point this function returned an error if the pager was in
   41950   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   41951   ** there is at least one outstanding page reference, this function
   41952   ** is a no-op for that case anyhow.
   41953   */
   41954 
   41955   u32 pageSize = *pPageSize;
   41956   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   41957   if( (pPager->memDb==0 || pPager->dbSize==0)
   41958    && sqlite3PcacheRefCount(pPager->pPCache)==0
   41959    && pageSize && pageSize!=(u32)pPager->pageSize
   41960   ){
   41961     char *pNew = NULL;             /* New temp space */
   41962     i64 nByte = 0;
   41963 
   41964     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   41965       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   41966     }
   41967     if( rc==SQLITE_OK ){
   41968       pNew = (char *)sqlite3PageMalloc(pageSize);
   41969       if( !pNew ) rc = SQLITE_NOMEM;
   41970     }
   41971 
   41972     if( rc==SQLITE_OK ){
   41973       pager_reset(pPager);
   41974       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
   41975       pPager->pageSize = pageSize;
   41976       sqlite3PageFree(pPager->pTmpSpace);
   41977       pPager->pTmpSpace = pNew;
   41978       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   41979     }
   41980   }
   41981 
   41982   *pPageSize = pPager->pageSize;
   41983   if( rc==SQLITE_OK ){
   41984     if( nReserve<0 ) nReserve = pPager->nReserve;
   41985     assert( nReserve>=0 && nReserve<1000 );
   41986     pPager->nReserve = (i16)nReserve;
   41987     pagerReportSize(pPager);
   41988   }
   41989   return rc;
   41990 }
   41991 
   41992 /*
   41993 ** Return a pointer to the "temporary page" buffer held internally
   41994 ** by the pager.  This is a buffer that is big enough to hold the
   41995 ** entire content of a database page.  This buffer is used internally
   41996 ** during rollback and will be overwritten whenever a rollback
   41997 ** occurs.  But other modules are free to use it too, as long as
   41998 ** no rollbacks are happening.
   41999 */
   42000 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   42001   return pPager->pTmpSpace;
   42002 }
   42003 
   42004 /*
   42005 ** Attempt to set the maximum database page count if mxPage is positive.
   42006 ** Make no changes if mxPage is zero or negative.  And never reduce the
   42007 ** maximum page count below the current size of the database.
   42008 **
   42009 ** Regardless of mxPage, return the current maximum page count.
   42010 */
   42011 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   42012   if( mxPage>0 ){
   42013     pPager->mxPgno = mxPage;
   42014   }
   42015   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   42016   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   42017   return pPager->mxPgno;
   42018 }
   42019 
   42020 /*
   42021 ** The following set of routines are used to disable the simulated
   42022 ** I/O error mechanism.  These routines are used to avoid simulated
   42023 ** errors in places where we do not care about errors.
   42024 **
   42025 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   42026 ** and generate no code.
   42027 */
   42028 #ifdef SQLITE_TEST
   42029 SQLITE_API extern int sqlite3_io_error_pending;
   42030 SQLITE_API extern int sqlite3_io_error_hit;
   42031 static int saved_cnt;
   42032 void disable_simulated_io_errors(void){
   42033   saved_cnt = sqlite3_io_error_pending;
   42034   sqlite3_io_error_pending = -1;
   42035 }
   42036 void enable_simulated_io_errors(void){
   42037   sqlite3_io_error_pending = saved_cnt;
   42038 }
   42039 #else
   42040 # define disable_simulated_io_errors()
   42041 # define enable_simulated_io_errors()
   42042 #endif
   42043 
   42044 /*
   42045 ** Read the first N bytes from the beginning of the file into memory
   42046 ** that pDest points to.
   42047 **
   42048 ** If the pager was opened on a transient file (zFilename==""), or
   42049 ** opened on a file less than N bytes in size, the output buffer is
   42050 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   42051 ** function is used to read database headers, and a new transient or
   42052 ** zero sized database has a header than consists entirely of zeroes.
   42053 **
   42054 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   42055 ** the error code is returned to the caller and the contents of the
   42056 ** output buffer undefined.
   42057 */
   42058 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   42059   int rc = SQLITE_OK;
   42060   memset(pDest, 0, N);
   42061   assert( isOpen(pPager->fd) || pPager->tempFile );
   42062 
   42063   /* This routine is only called by btree immediately after creating
   42064   ** the Pager object.  There has not been an opportunity to transition
   42065   ** to WAL mode yet.
   42066   */
   42067   assert( !pagerUseWal(pPager) );
   42068 
   42069   if( isOpen(pPager->fd) ){
   42070     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   42071     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   42072     if( rc==SQLITE_IOERR_SHORT_READ ){
   42073       rc = SQLITE_OK;
   42074     }
   42075   }
   42076   return rc;
   42077 }
   42078 
   42079 /*
   42080 ** This function may only be called when a read-transaction is open on
   42081 ** the pager. It returns the total number of pages in the database.
   42082 **
   42083 ** However, if the file is between 1 and <page-size> bytes in size, then
   42084 ** this is considered a 1 page file.
   42085 */
   42086 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   42087   assert( pPager->eState>=PAGER_READER );
   42088   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   42089   *pnPage = (int)pPager->dbSize;
   42090 }
   42091 
   42092 
   42093 /*
   42094 ** Try to obtain a lock of type locktype on the database file. If
   42095 ** a similar or greater lock is already held, this function is a no-op
   42096 ** (returning SQLITE_OK immediately).
   42097 **
   42098 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   42099 ** the busy callback if the lock is currently not available. Repeat
   42100 ** until the busy callback returns false or until the attempt to
   42101 ** obtain the lock succeeds.
   42102 **
   42103 ** Return SQLITE_OK on success and an error code if we cannot obtain
   42104 ** the lock. If the lock is obtained successfully, set the Pager.state
   42105 ** variable to locktype before returning.
   42106 */
   42107 static int pager_wait_on_lock(Pager *pPager, int locktype){
   42108   int rc;                              /* Return code */
   42109 
   42110   /* Check that this is either a no-op (because the requested lock is
   42111   ** already held, or one of the transistions that the busy-handler
   42112   ** may be invoked during, according to the comment above
   42113   ** sqlite3PagerSetBusyhandler().
   42114   */
   42115   assert( (pPager->eLock>=locktype)
   42116        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   42117        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   42118   );
   42119 
   42120   do {
   42121     rc = pagerLockDb(pPager, locktype);
   42122   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   42123   return rc;
   42124 }
   42125 
   42126 /*
   42127 ** Function assertTruncateConstraint(pPager) checks that one of the
   42128 ** following is true for all dirty pages currently in the page-cache:
   42129 **
   42130 **   a) The page number is less than or equal to the size of the
   42131 **      current database image, in pages, OR
   42132 **
   42133 **   b) if the page content were written at this time, it would not
   42134 **      be necessary to write the current content out to the sub-journal
   42135 **      (as determined by function subjRequiresPage()).
   42136 **
   42137 ** If the condition asserted by this function were not true, and the
   42138 ** dirty page were to be discarded from the cache via the pagerStress()
   42139 ** routine, pagerStress() would not write the current page content to
   42140 ** the database file. If a savepoint transaction were rolled back after
   42141 ** this happened, the correct behaviour would be to restore the current
   42142 ** content of the page. However, since this content is not present in either
   42143 ** the database file or the portion of the rollback journal and
   42144 ** sub-journal rolled back the content could not be restored and the
   42145 ** database image would become corrupt. It is therefore fortunate that
   42146 ** this circumstance cannot arise.
   42147 */
   42148 #if defined(SQLITE_DEBUG)
   42149 static void assertTruncateConstraintCb(PgHdr *pPg){
   42150   assert( pPg->flags&PGHDR_DIRTY );
   42151   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   42152 }
   42153 static void assertTruncateConstraint(Pager *pPager){
   42154   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   42155 }
   42156 #else
   42157 # define assertTruncateConstraint(pPager)
   42158 #endif
   42159 
   42160 /*
   42161 ** Truncate the in-memory database file image to nPage pages. This
   42162 ** function does not actually modify the database file on disk. It
   42163 ** just sets the internal state of the pager object so that the
   42164 ** truncation will be done when the current transaction is committed.
   42165 */
   42166 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   42167   assert( pPager->dbSize>=nPage );
   42168   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   42169   pPager->dbSize = nPage;
   42170   assertTruncateConstraint(pPager);
   42171 }
   42172 
   42173 
   42174 /*
   42175 ** This function is called before attempting a hot-journal rollback. It
   42176 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   42177 ** size of the journal file so that the pager_playback() routine knows
   42178 ** that the entire journal file has been synced.
   42179 **
   42180 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   42181 ** that if a power-failure occurs during the rollback, the process that
   42182 ** attempts rollback following system recovery sees the same journal
   42183 ** content as this process.
   42184 **
   42185 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   42186 ** an SQLite error code.
   42187 */
   42188 static int pagerSyncHotJournal(Pager *pPager){
   42189   int rc = SQLITE_OK;
   42190   if( !pPager->noSync ){
   42191     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   42192   }
   42193   if( rc==SQLITE_OK ){
   42194     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   42195   }
   42196   return rc;
   42197 }
   42198 
   42199 /*
   42200 ** Shutdown the page cache.  Free all memory and close all files.
   42201 **
   42202 ** If a transaction was in progress when this routine is called, that
   42203 ** transaction is rolled back.  All outstanding pages are invalidated
   42204 ** and their memory is freed.  Any attempt to use a page associated
   42205 ** with this page cache after this function returns will likely
   42206 ** result in a coredump.
   42207 **
   42208 ** This function always succeeds. If a transaction is active an attempt
   42209 ** is made to roll it back. If an error occurs during the rollback
   42210 ** a hot journal may be left in the filesystem but no error is returned
   42211 ** to the caller.
   42212 */
   42213 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   42214   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   42215 
   42216   assert( assert_pager_state(pPager) );
   42217   disable_simulated_io_errors();
   42218   sqlite3BeginBenignMalloc();
   42219   /* pPager->errCode = 0; */
   42220   pPager->exclusiveMode = 0;
   42221 #ifndef SQLITE_OMIT_WAL
   42222   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
   42223   pPager->pWal = 0;
   42224 #endif
   42225   pager_reset(pPager);
   42226   if( MEMDB ){
   42227     pager_unlock(pPager);
   42228   }else{
   42229     /* If it is open, sync the journal file before calling UnlockAndRollback.
   42230     ** If this is not done, then an unsynced portion of the open journal
   42231     ** file may be played back into the database. If a power failure occurs
   42232     ** while this is happening, the database could become corrupt.
   42233     **
   42234     ** If an error occurs while trying to sync the journal, shift the pager
   42235     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   42236     ** database and close the journal file without attempting to roll it
   42237     ** back or finalize it. The next database user will have to do hot-journal
   42238     ** rollback before accessing the database file.
   42239     */
   42240     if( isOpen(pPager->jfd) ){
   42241       pager_error(pPager, pagerSyncHotJournal(pPager));
   42242     }
   42243     pagerUnlockAndRollback(pPager);
   42244   }
   42245   sqlite3EndBenignMalloc();
   42246   enable_simulated_io_errors();
   42247   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   42248   IOTRACE(("CLOSE %p\n", pPager))
   42249   sqlite3OsClose(pPager->jfd);
   42250   sqlite3OsClose(pPager->fd);
   42251   sqlite3PageFree(pTmp);
   42252   sqlite3PcacheClose(pPager->pPCache);
   42253 
   42254 #ifdef SQLITE_HAS_CODEC
   42255   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   42256 #endif
   42257 
   42258   assert( !pPager->aSavepoint && !pPager->pInJournal );
   42259   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   42260 
   42261   sqlite3_free(pPager);
   42262   return SQLITE_OK;
   42263 }
   42264 
   42265 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   42266 /*
   42267 ** Return the page number for page pPg.
   42268 */
   42269 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   42270   return pPg->pgno;
   42271 }
   42272 #endif
   42273 
   42274 /*
   42275 ** Increment the reference count for page pPg.
   42276 */
   42277 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   42278   sqlite3PcacheRef(pPg);
   42279 }
   42280 
   42281 /*
   42282 ** Sync the journal. In other words, make sure all the pages that have
   42283 ** been written to the journal have actually reached the surface of the
   42284 ** disk and can be restored in the event of a hot-journal rollback.
   42285 **
   42286 ** If the Pager.noSync flag is set, then this function is a no-op.
   42287 ** Otherwise, the actions required depend on the journal-mode and the
   42288 ** device characteristics of the the file-system, as follows:
   42289 **
   42290 **   * If the journal file is an in-memory journal file, no action need
   42291 **     be taken.
   42292 **
   42293 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   42294 **     then the nRec field of the most recently written journal header
   42295 **     is updated to contain the number of journal records that have
   42296 **     been written following it. If the pager is operating in full-sync
   42297 **     mode, then the journal file is synced before this field is updated.
   42298 **
   42299 **   * If the device does not support the SEQUENTIAL property, then
   42300 **     journal file is synced.
   42301 **
   42302 ** Or, in pseudo-code:
   42303 **
   42304 **   if( NOT <in-memory journal> ){
   42305 **     if( NOT SAFE_APPEND ){
   42306 **       if( <full-sync mode> ) xSync(<journal file>);
   42307 **       <update nRec field>
   42308 **     }
   42309 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   42310 **   }
   42311 **
   42312 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   42313 ** page currently held in memory before returning SQLITE_OK. If an IO
   42314 ** error is encountered, then the IO error code is returned to the caller.
   42315 */
   42316 static int syncJournal(Pager *pPager, int newHdr){
   42317   int rc;                         /* Return code */
   42318 
   42319   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   42320        || pPager->eState==PAGER_WRITER_DBMOD
   42321   );
   42322   assert( assert_pager_state(pPager) );
   42323   assert( !pagerUseWal(pPager) );
   42324 
   42325   rc = sqlite3PagerExclusiveLock(pPager);
   42326   if( rc!=SQLITE_OK ) return rc;
   42327 
   42328   if( !pPager->noSync ){
   42329     assert( !pPager->tempFile );
   42330     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   42331       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   42332       assert( isOpen(pPager->jfd) );
   42333 
   42334       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   42335         /* This block deals with an obscure problem. If the last connection
   42336         ** that wrote to this database was operating in persistent-journal
   42337         ** mode, then the journal file may at this point actually be larger
   42338         ** than Pager.journalOff bytes. If the next thing in the journal
   42339         ** file happens to be a journal-header (written as part of the
   42340         ** previous connection's transaction), and a crash or power-failure
   42341         ** occurs after nRec is updated but before this connection writes
   42342         ** anything else to the journal file (or commits/rolls back its
   42343         ** transaction), then SQLite may become confused when doing the
   42344         ** hot-journal rollback following recovery. It may roll back all
   42345         ** of this connections data, then proceed to rolling back the old,
   42346         ** out-of-date data that follows it. Database corruption.
   42347         **
   42348         ** To work around this, if the journal file does appear to contain
   42349         ** a valid header following Pager.journalOff, then write a 0x00
   42350         ** byte to the start of it to prevent it from being recognized.
   42351         **
   42352         ** Variable iNextHdrOffset is set to the offset at which this
   42353         ** problematic header will occur, if it exists. aMagic is used
   42354         ** as a temporary buffer to inspect the first couple of bytes of
   42355         ** the potential journal header.
   42356         */
   42357         i64 iNextHdrOffset;
   42358         u8 aMagic[8];
   42359         u8 zHeader[sizeof(aJournalMagic)+4];
   42360 
   42361         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   42362         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   42363 
   42364         iNextHdrOffset = journalHdrOffset(pPager);
   42365         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   42366         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   42367           static const u8 zerobyte = 0;
   42368           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   42369         }
   42370         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   42371           return rc;
   42372         }
   42373 
   42374         /* Write the nRec value into the journal file header. If in
   42375         ** full-synchronous mode, sync the journal first. This ensures that
   42376         ** all data has really hit the disk before nRec is updated to mark
   42377         ** it as a candidate for rollback.
   42378         **
   42379         ** This is not required if the persistent media supports the
   42380         ** SAFE_APPEND property. Because in this case it is not possible
   42381         ** for garbage data to be appended to the file, the nRec field
   42382         ** is populated with 0xFFFFFFFF when the journal header is written
   42383         ** and never needs to be updated.
   42384         */
   42385         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   42386           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   42387           IOTRACE(("JSYNC %p\n", pPager))
   42388           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   42389           if( rc!=SQLITE_OK ) return rc;
   42390         }
   42391         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   42392         rc = sqlite3OsWrite(
   42393             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   42394         );
   42395         if( rc!=SQLITE_OK ) return rc;
   42396       }
   42397       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   42398         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   42399         IOTRACE(("JSYNC %p\n", pPager))
   42400         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   42401           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   42402         );
   42403         if( rc!=SQLITE_OK ) return rc;
   42404       }
   42405 
   42406       pPager->journalHdr = pPager->journalOff;
   42407       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   42408         pPager->nRec = 0;
   42409         rc = writeJournalHdr(pPager);
   42410         if( rc!=SQLITE_OK ) return rc;
   42411       }
   42412     }else{
   42413       pPager->journalHdr = pPager->journalOff;
   42414     }
   42415   }
   42416 
   42417   /* Unless the pager is in noSync mode, the journal file was just
   42418   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   42419   ** all pages.
   42420   */
   42421   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   42422   pPager->eState = PAGER_WRITER_DBMOD;
   42423   assert( assert_pager_state(pPager) );
   42424   return SQLITE_OK;
   42425 }
   42426 
   42427 /*
   42428 ** The argument is the first in a linked list of dirty pages connected
   42429 ** by the PgHdr.pDirty pointer. This function writes each one of the
   42430 ** in-memory pages in the list to the database file. The argument may
   42431 ** be NULL, representing an empty list. In this case this function is
   42432 ** a no-op.
   42433 **
   42434 ** The pager must hold at least a RESERVED lock when this function
   42435 ** is called. Before writing anything to the database file, this lock
   42436 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   42437 ** SQLITE_BUSY is returned and no data is written to the database file.
   42438 **
   42439 ** If the pager is a temp-file pager and the actual file-system file
   42440 ** is not yet open, it is created and opened before any data is
   42441 ** written out.
   42442 **
   42443 ** Once the lock has been upgraded and, if necessary, the file opened,
   42444 ** the pages are written out to the database file in list order. Writing
   42445 ** a page is skipped if it meets either of the following criteria:
   42446 **
   42447 **   * The page number is greater than Pager.dbSize, or
   42448 **   * The PGHDR_DONT_WRITE flag is set on the page.
   42449 **
   42450 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   42451 ** is updated accordingly. If page 1 is written out, then the value cached
   42452 ** in Pager.dbFileVers[] is updated to match the new value stored in
   42453 ** the database file.
   42454 **
   42455 ** If everything is successful, SQLITE_OK is returned. If an IO error
   42456 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   42457 ** be obtained, SQLITE_BUSY is returned.
   42458 */
   42459 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   42460   int rc = SQLITE_OK;                  /* Return code */
   42461 
   42462   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   42463   assert( !pagerUseWal(pPager) );
   42464   assert( pPager->eState==PAGER_WRITER_DBMOD );
   42465   assert( pPager->eLock==EXCLUSIVE_LOCK );
   42466 
   42467   /* If the file is a temp-file has not yet been opened, open it now. It
   42468   ** is not possible for rc to be other than SQLITE_OK if this branch
   42469   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   42470   */
   42471   if( !isOpen(pPager->fd) ){
   42472     assert( pPager->tempFile && rc==SQLITE_OK );
   42473     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   42474   }
   42475 
   42476   /* Before the first write, give the VFS a hint of what the final
   42477   ** file size will be.
   42478   */
   42479   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   42480   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
   42481     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   42482     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   42483     pPager->dbHintSize = pPager->dbSize;
   42484   }
   42485 
   42486   while( rc==SQLITE_OK && pList ){
   42487     Pgno pgno = pList->pgno;
   42488 
   42489     /* If there are dirty pages in the page cache with page numbers greater
   42490     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   42491     ** make the file smaller (presumably by auto-vacuum code). Do not write
   42492     ** any such pages to the file.
   42493     **
   42494     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   42495     ** set (set by sqlite3PagerDontWrite()).
   42496     */
   42497     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   42498       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   42499       char *pData;                                   /* Data to write */
   42500 
   42501       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   42502       if( pList->pgno==1 ) pager_write_changecounter(pList);
   42503 
   42504       /* Encode the database */
   42505       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   42506 
   42507       /* Write out the page data. */
   42508       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   42509 
   42510       /* If page 1 was just written, update Pager.dbFileVers to match
   42511       ** the value now stored in the database file. If writing this
   42512       ** page caused the database file to grow, update dbFileSize.
   42513       */
   42514       if( pgno==1 ){
   42515         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   42516       }
   42517       if( pgno>pPager->dbFileSize ){
   42518         pPager->dbFileSize = pgno;
   42519       }
   42520 
   42521       /* Update any backup objects copying the contents of this pager. */
   42522       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   42523 
   42524       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   42525                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   42526       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   42527       PAGER_INCR(sqlite3_pager_writedb_count);
   42528       PAGER_INCR(pPager->nWrite);
   42529     }else{
   42530       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   42531     }
   42532     pager_set_pagehash(pList);
   42533     pList = pList->pDirty;
   42534   }
   42535 
   42536   return rc;
   42537 }
   42538 
   42539 /*
   42540 ** Ensure that the sub-journal file is open. If it is already open, this
   42541 ** function is a no-op.
   42542 **
   42543 ** SQLITE_OK is returned if everything goes according to plan. An
   42544 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   42545 ** fails.
   42546 */
   42547 static int openSubJournal(Pager *pPager){
   42548   int rc = SQLITE_OK;
   42549   if( !isOpen(pPager->sjfd) ){
   42550     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   42551       sqlite3MemJournalOpen(pPager->sjfd);
   42552     }else{
   42553       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   42554     }
   42555   }
   42556   return rc;
   42557 }
   42558 
   42559 /*
   42560 ** Append a record of the current state of page pPg to the sub-journal.
   42561 ** It is the callers responsibility to use subjRequiresPage() to check
   42562 ** that it is really required before calling this function.
   42563 **
   42564 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   42565 ** for all open savepoints before returning.
   42566 **
   42567 ** This function returns SQLITE_OK if everything is successful, an IO
   42568 ** error code if the attempt to write to the sub-journal fails, or
   42569 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   42570 ** bitvec.
   42571 */
   42572 static int subjournalPage(PgHdr *pPg){
   42573   int rc = SQLITE_OK;
   42574   Pager *pPager = pPg->pPager;
   42575   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   42576 
   42577     /* Open the sub-journal, if it has not already been opened */
   42578     assert( pPager->useJournal );
   42579     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   42580     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   42581     assert( pagerUseWal(pPager)
   42582          || pageInJournal(pPg)
   42583          || pPg->pgno>pPager->dbOrigSize
   42584     );
   42585     rc = openSubJournal(pPager);
   42586 
   42587     /* If the sub-journal was opened successfully (or was already open),
   42588     ** write the journal record into the file.  */
   42589     if( rc==SQLITE_OK ){
   42590       void *pData = pPg->pData;
   42591       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
   42592       char *pData2;
   42593 
   42594       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   42595       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   42596       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   42597       if( rc==SQLITE_OK ){
   42598         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   42599       }
   42600     }
   42601   }
   42602   if( rc==SQLITE_OK ){
   42603     pPager->nSubRec++;
   42604     assert( pPager->nSavepoint>0 );
   42605     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   42606   }
   42607   return rc;
   42608 }
   42609 
   42610 /*
   42611 ** This function is called by the pcache layer when it has reached some
   42612 ** soft memory limit. The first argument is a pointer to a Pager object
   42613 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   42614 ** database). The second argument is a reference to a page that is
   42615 ** currently dirty but has no outstanding references. The page
   42616 ** is always associated with the Pager object passed as the first
   42617 ** argument.
   42618 **
   42619 ** The job of this function is to make pPg clean by writing its contents
   42620 ** out to the database file, if possible. This may involve syncing the
   42621 ** journal file.
   42622 **
   42623 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   42624 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   42625 ** page clean, the IO error code is returned. If the page cannot be
   42626 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   42627 ** is returned by sqlite3PcacheMakeClean() is not called.
   42628 */
   42629 static int pagerStress(void *p, PgHdr *pPg){
   42630   Pager *pPager = (Pager *)p;
   42631   int rc = SQLITE_OK;
   42632 
   42633   assert( pPg->pPager==pPager );
   42634   assert( pPg->flags&PGHDR_DIRTY );
   42635 
   42636   /* The doNotSyncSpill flag is set during times when doing a sync of
   42637   ** journal (and adding a new header) is not allowed.  This occurs
   42638   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   42639   ** pages belonging to the same sector.
   42640   **
   42641   ** The doNotSpill flag inhibits all cache spilling regardless of whether
   42642   ** or not a sync is required.  This is set during a rollback.
   42643   **
   42644   ** Spilling is also prohibited when in an error state since that could
   42645   ** lead to database corruption.   In the current implementaton it
   42646   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
   42647   ** while in the error state, hence it is impossible for this routine to
   42648   ** be called in the error state.  Nevertheless, we include a NEVER()
   42649   ** test for the error state as a safeguard against future changes.
   42650   */
   42651   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   42652   if( pPager->doNotSpill ) return SQLITE_OK;
   42653   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
   42654     return SQLITE_OK;
   42655   }
   42656 
   42657   pPg->pDirty = 0;
   42658   if( pagerUseWal(pPager) ){
   42659     /* Write a single frame for this page to the log. */
   42660     if( subjRequiresPage(pPg) ){
   42661       rc = subjournalPage(pPg);
   42662     }
   42663     if( rc==SQLITE_OK ){
   42664       rc = pagerWalFrames(pPager, pPg, 0, 0);
   42665     }
   42666   }else{
   42667 
   42668     /* Sync the journal file if required. */
   42669     if( pPg->flags&PGHDR_NEED_SYNC
   42670      || pPager->eState==PAGER_WRITER_CACHEMOD
   42671     ){
   42672       rc = syncJournal(pPager, 1);
   42673     }
   42674 
   42675     /* If the page number of this page is larger than the current size of
   42676     ** the database image, it may need to be written to the sub-journal.
   42677     ** This is because the call to pager_write_pagelist() below will not
   42678     ** actually write data to the file in this case.
   42679     **
   42680     ** Consider the following sequence of events:
   42681     **
   42682     **   BEGIN;
   42683     **     <journal page X>
   42684     **     <modify page X>
   42685     **     SAVEPOINT sp;
   42686     **       <shrink database file to Y pages>
   42687     **       pagerStress(page X)
   42688     **     ROLLBACK TO sp;
   42689     **
   42690     ** If (X>Y), then when pagerStress is called page X will not be written
   42691     ** out to the database file, but will be dropped from the cache. Then,
   42692     ** following the "ROLLBACK TO sp" statement, reading page X will read
   42693     ** data from the database file. This will be the copy of page X as it
   42694     ** was when the transaction started, not as it was when "SAVEPOINT sp"
   42695     ** was executed.
   42696     **
   42697     ** The solution is to write the current data for page X into the
   42698     ** sub-journal file now (if it is not already there), so that it will
   42699     ** be restored to its current value when the "ROLLBACK TO sp" is
   42700     ** executed.
   42701     */
   42702     if( NEVER(
   42703         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   42704     ) ){
   42705       rc = subjournalPage(pPg);
   42706     }
   42707 
   42708     /* Write the contents of the page out to the database file. */
   42709     if( rc==SQLITE_OK ){
   42710       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   42711       rc = pager_write_pagelist(pPager, pPg);
   42712     }
   42713   }
   42714 
   42715   /* Mark the page as clean. */
   42716   if( rc==SQLITE_OK ){
   42717     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   42718     sqlite3PcacheMakeClean(pPg);
   42719   }
   42720 
   42721   return pager_error(pPager, rc);
   42722 }
   42723 
   42724 
   42725 /*
   42726 ** Allocate and initialize a new Pager object and put a pointer to it
   42727 ** in *ppPager. The pager should eventually be freed by passing it
   42728 ** to sqlite3PagerClose().
   42729 **
   42730 ** The zFilename argument is the path to the database file to open.
   42731 ** If zFilename is NULL then a randomly-named temporary file is created
   42732 ** and used as the file to be cached. Temporary files are be deleted
   42733 ** automatically when they are closed. If zFilename is ":memory:" then
   42734 ** all information is held in cache. It is never written to disk.
   42735 ** This can be used to implement an in-memory database.
   42736 **
   42737 ** The nExtra parameter specifies the number of bytes of space allocated
   42738 ** along with each page reference. This space is available to the user
   42739 ** via the sqlite3PagerGetExtra() API.
   42740 **
   42741 ** The flags argument is used to specify properties that affect the
   42742 ** operation of the pager. It should be passed some bitwise combination
   42743 ** of the PAGER_* flags.
   42744 **
   42745 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   42746 ** of the xOpen() method of the supplied VFS when opening files.
   42747 **
   42748 ** If the pager object is allocated and the specified file opened
   42749 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   42750 ** the new pager object. If an error occurs, *ppPager is set to NULL
   42751 ** and error code returned. This function may return SQLITE_NOMEM
   42752 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   42753 ** various SQLITE_IO_XXX errors.
   42754 */
   42755 SQLITE_PRIVATE int sqlite3PagerOpen(
   42756   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   42757   Pager **ppPager,         /* OUT: Return the Pager structure here */
   42758   const char *zFilename,   /* Name of the database file to open */
   42759   int nExtra,              /* Extra bytes append to each in-memory page */
   42760   int flags,               /* flags controlling this file */
   42761   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   42762   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   42763 ){
   42764   u8 *pPtr;
   42765   Pager *pPager = 0;       /* Pager object to allocate and return */
   42766   int rc = SQLITE_OK;      /* Return code */
   42767   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   42768   int memDb = 0;           /* True if this is an in-memory file */
   42769   int readOnly = 0;        /* True if this is a read-only file */
   42770   int journalFileSize;     /* Bytes to allocate for each journal fd */
   42771   char *zPathname = 0;     /* Full path to database file */
   42772   int nPathname = 0;       /* Number of bytes in zPathname */
   42773   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   42774   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   42775   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   42776   const char *zUri = 0;    /* URI args to copy */
   42777   int nUri = 0;            /* Number of bytes of URI args at *zUri */
   42778 
   42779   /* Figure out how much space is required for each journal file-handle
   42780   ** (there are two of them, the main journal and the sub-journal). This
   42781   ** is the maximum space required for an in-memory journal file handle
   42782   ** and a regular journal file-handle. Note that a "regular journal-handle"
   42783   ** may be a wrapper capable of caching the first portion of the journal
   42784   ** file in memory to implement the atomic-write optimization (see
   42785   ** source file journal.c).
   42786   */
   42787   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   42788     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   42789   }else{
   42790     journalFileSize = ROUND8(sqlite3MemJournalSize());
   42791   }
   42792 
   42793   /* Set the output variable to NULL in case an error occurs. */
   42794   *ppPager = 0;
   42795 
   42796 #ifndef SQLITE_OMIT_MEMORYDB
   42797   if( flags & PAGER_MEMORY ){
   42798     memDb = 1;
   42799     zFilename = 0;
   42800   }
   42801 #endif
   42802 
   42803   /* Compute and store the full pathname in an allocated buffer pointed
   42804   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   42805   ** leave both nPathname and zPathname set to 0.
   42806   */
   42807   if( zFilename && zFilename[0] ){
   42808     const char *z;
   42809     nPathname = pVfs->mxPathname+1;
   42810     zPathname = sqlite3Malloc(nPathname*2);
   42811     if( zPathname==0 ){
   42812       return SQLITE_NOMEM;
   42813     }
   42814     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   42815     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   42816     nPathname = sqlite3Strlen30(zPathname);
   42817     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
   42818     while( *z ){
   42819       z += sqlite3Strlen30(z)+1;
   42820       z += sqlite3Strlen30(z)+1;
   42821     }
   42822     nUri = (int)(&z[1] - zUri);
   42823     assert( nUri>=0 );
   42824     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   42825       /* This branch is taken when the journal path required by
   42826       ** the database being opened will be more than pVfs->mxPathname
   42827       ** bytes in length. This means the database cannot be opened,
   42828       ** as it will not be possible to open the journal file or even
   42829       ** check for a hot-journal before reading.
   42830       */
   42831       rc = SQLITE_CANTOPEN_BKPT;
   42832     }
   42833     if( rc!=SQLITE_OK ){
   42834       sqlite3_free(zPathname);
   42835       return rc;
   42836     }
   42837   }
   42838 
   42839   /* Allocate memory for the Pager structure, PCache object, the
   42840   ** three file descriptors, the database file name and the journal
   42841   ** file name. The layout in memory is as follows:
   42842   **
   42843   **     Pager object                    (sizeof(Pager) bytes)
   42844   **     PCache object                   (sqlite3PcacheSize() bytes)
   42845   **     Database file handle            (pVfs->szOsFile bytes)
   42846   **     Sub-journal file handle         (journalFileSize bytes)
   42847   **     Main journal file handle        (journalFileSize bytes)
   42848   **     Database file name              (nPathname+1 bytes)
   42849   **     Journal file name               (nPathname+8+1 bytes)
   42850   */
   42851   pPtr = (u8 *)sqlite3MallocZero(
   42852     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   42853     ROUND8(pcacheSize) +           /* PCache object */
   42854     ROUND8(pVfs->szOsFile) +       /* The main db file */
   42855     journalFileSize * 2 +          /* The two journal files */
   42856     nPathname + 1 + nUri +         /* zFilename */
   42857     nPathname + 8 + 2              /* zJournal */
   42858 #ifndef SQLITE_OMIT_WAL
   42859     + nPathname + 4 + 2            /* zWal */
   42860 #endif
   42861   );
   42862   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   42863   if( !pPtr ){
   42864     sqlite3_free(zPathname);
   42865     return SQLITE_NOMEM;
   42866   }
   42867   pPager =              (Pager*)(pPtr);
   42868   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   42869   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   42870   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   42871   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   42872   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   42873   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   42874 
   42875   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   42876   if( zPathname ){
   42877     assert( nPathname>0 );
   42878     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
   42879     memcpy(pPager->zFilename, zPathname, nPathname);
   42880     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
   42881     memcpy(pPager->zJournal, zPathname, nPathname);
   42882     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
   42883     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
   42884 #ifndef SQLITE_OMIT_WAL
   42885     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   42886     memcpy(pPager->zWal, zPathname, nPathname);
   42887     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
   42888     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
   42889 #endif
   42890     sqlite3_free(zPathname);
   42891   }
   42892   pPager->pVfs = pVfs;
   42893   pPager->vfsFlags = vfsFlags;
   42894 
   42895   /* Open the pager file.
   42896   */
   42897   if( zFilename && zFilename[0] ){
   42898     int fout = 0;                    /* VFS flags returned by xOpen() */
   42899     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   42900     assert( !memDb );
   42901     readOnly = (fout&SQLITE_OPEN_READONLY);
   42902 
   42903     /* If the file was successfully opened for read/write access,
   42904     ** choose a default page size in case we have to create the
   42905     ** database file. The default page size is the maximum of:
   42906     **
   42907     **    + SQLITE_DEFAULT_PAGE_SIZE,
   42908     **    + The value returned by sqlite3OsSectorSize()
   42909     **    + The largest page size that can be written atomically.
   42910     */
   42911     if( rc==SQLITE_OK && !readOnly ){
   42912       setSectorSize(pPager);
   42913       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   42914       if( szPageDflt<pPager->sectorSize ){
   42915         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   42916           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   42917         }else{
   42918           szPageDflt = (u32)pPager->sectorSize;
   42919         }
   42920       }
   42921 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   42922       {
   42923         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   42924         int ii;
   42925         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   42926         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   42927         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   42928         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   42929           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   42930             szPageDflt = ii;
   42931           }
   42932         }
   42933       }
   42934 #endif
   42935     }
   42936   }else{
   42937     /* If a temporary file is requested, it is not opened immediately.
   42938     ** In this case we accept the default page size and delay actually
   42939     ** opening the file until the first call to OsWrite().
   42940     **
   42941     ** This branch is also run for an in-memory database. An in-memory
   42942     ** database is the same as a temp-file that is never written out to
   42943     ** disk and uses an in-memory rollback journal.
   42944     */
   42945     tempFile = 1;
   42946     pPager->eState = PAGER_READER;
   42947     pPager->eLock = EXCLUSIVE_LOCK;
   42948     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   42949   }
   42950 
   42951   /* The following call to PagerSetPagesize() serves to set the value of
   42952   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   42953   */
   42954   if( rc==SQLITE_OK ){
   42955     assert( pPager->memDb==0 );
   42956     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   42957     testcase( rc!=SQLITE_OK );
   42958   }
   42959 
   42960   /* If an error occurred in either of the blocks above, free the
   42961   ** Pager structure and close the file.
   42962   */
   42963   if( rc!=SQLITE_OK ){
   42964     assert( !pPager->pTmpSpace );
   42965     sqlite3OsClose(pPager->fd);
   42966     sqlite3_free(pPager);
   42967     return rc;
   42968   }
   42969 
   42970   /* Initialize the PCache object. */
   42971   assert( nExtra<1000 );
   42972   nExtra = ROUND8(nExtra);
   42973   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   42974                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   42975 
   42976   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   42977   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   42978 
   42979   pPager->useJournal = (u8)useJournal;
   42980   /* pPager->stmtOpen = 0; */
   42981   /* pPager->stmtInUse = 0; */
   42982   /* pPager->nRef = 0; */
   42983   /* pPager->stmtSize = 0; */
   42984   /* pPager->stmtJSize = 0; */
   42985   /* pPager->nPage = 0; */
   42986   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   42987   /* pPager->state = PAGER_UNLOCK; */
   42988 #if 0
   42989   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
   42990 #endif
   42991   /* pPager->errMask = 0; */
   42992   pPager->tempFile = (u8)tempFile;
   42993   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   42994           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   42995   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   42996   pPager->exclusiveMode = (u8)tempFile;
   42997   pPager->changeCountDone = pPager->tempFile;
   42998   pPager->memDb = (u8)memDb;
   42999   pPager->readOnly = (u8)readOnly;
   43000   assert( useJournal || pPager->tempFile );
   43001   pPager->noSync = pPager->tempFile;
   43002   if( pPager->noSync ){
   43003     assert( pPager->fullSync==0 );
   43004     assert( pPager->syncFlags==0 );
   43005     assert( pPager->walSyncFlags==0 );
   43006     assert( pPager->ckptSyncFlags==0 );
   43007   }else{
   43008     pPager->fullSync = 1;
   43009     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   43010     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
   43011     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   43012   }
   43013   /* pPager->pFirst = 0; */
   43014   /* pPager->pFirstSynced = 0; */
   43015   /* pPager->pLast = 0; */
   43016   pPager->nExtra = (u16)nExtra;
   43017   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   43018   assert( isOpen(pPager->fd) || tempFile );
   43019   setSectorSize(pPager);
   43020   if( !useJournal ){
   43021     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   43022   }else if( memDb ){
   43023     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   43024   }
   43025   /* pPager->xBusyHandler = 0; */
   43026   /* pPager->pBusyHandlerArg = 0; */
   43027   pPager->xReiniter = xReinit;
   43028   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   43029 
   43030   *ppPager = pPager;
   43031   return SQLITE_OK;
   43032 }
   43033 
   43034 
   43035 
   43036 /*
   43037 ** This function is called after transitioning from PAGER_UNLOCK to
   43038 ** PAGER_SHARED state. It tests if there is a hot journal present in
   43039 ** the file-system for the given pager. A hot journal is one that
   43040 ** needs to be played back. According to this function, a hot-journal
   43041 ** file exists if the following criteria are met:
   43042 **
   43043 **   * The journal file exists in the file system, and
   43044 **   * No process holds a RESERVED or greater lock on the database file, and
   43045 **   * The database file itself is greater than 0 bytes in size, and
   43046 **   * The first byte of the journal file exists and is not 0x00.
   43047 **
   43048 ** If the current size of the database file is 0 but a journal file
   43049 ** exists, that is probably an old journal left over from a prior
   43050 ** database with the same name. In this case the journal file is
   43051 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   43052 ** is returned.
   43053 **
   43054 ** This routine does not check if there is a master journal filename
   43055 ** at the end of the file. If there is, and that master journal file
   43056 ** does not exist, then the journal file is not really hot. In this
   43057 ** case this routine will return a false-positive. The pager_playback()
   43058 ** routine will discover that the journal file is not really hot and
   43059 ** will not roll it back.
   43060 **
   43061 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   43062 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   43063 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   43064 ** to determine whether or not a hot-journal file exists, the IO error
   43065 ** code is returned and the value of *pExists is undefined.
   43066 */
   43067 static int hasHotJournal(Pager *pPager, int *pExists){
   43068   sqlite3_vfs * const pVfs = pPager->pVfs;
   43069   int rc = SQLITE_OK;           /* Return code */
   43070   int exists = 1;               /* True if a journal file is present */
   43071   int jrnlOpen = !!isOpen(pPager->jfd);
   43072 
   43073   assert( pPager->useJournal );
   43074   assert( isOpen(pPager->fd) );
   43075   assert( pPager->eState==PAGER_OPEN );
   43076 
   43077   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   43078     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   43079   ));
   43080 
   43081   *pExists = 0;
   43082   if( !jrnlOpen ){
   43083     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   43084   }
   43085   if( rc==SQLITE_OK && exists ){
   43086     int locked = 0;             /* True if some process holds a RESERVED lock */
   43087 
   43088     /* Race condition here:  Another process might have been holding the
   43089     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   43090     ** call above, but then delete the journal and drop the lock before
   43091     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   43092     ** is the case, this routine might think there is a hot journal when
   43093     ** in fact there is none.  This results in a false-positive which will
   43094     ** be dealt with by the playback routine.  Ticket #3883.
   43095     */
   43096     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   43097     if( rc==SQLITE_OK && !locked ){
   43098       Pgno nPage;                 /* Number of pages in database file */
   43099 
   43100       /* Check the size of the database file. If it consists of 0 pages,
   43101       ** then delete the journal file. See the header comment above for
   43102       ** the reasoning here.  Delete the obsolete journal file under
   43103       ** a RESERVED lock to avoid race conditions and to avoid violating
   43104       ** [H33020].
   43105       */
   43106       rc = pagerPagecount(pPager, &nPage);
   43107       if( rc==SQLITE_OK ){
   43108         if( nPage==0 ){
   43109           sqlite3BeginBenignMalloc();
   43110           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   43111             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   43112             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   43113           }
   43114           sqlite3EndBenignMalloc();
   43115         }else{
   43116           /* The journal file exists and no other connection has a reserved
   43117           ** or greater lock on the database file. Now check that there is
   43118           ** at least one non-zero bytes at the start of the journal file.
   43119           ** If there is, then we consider this journal to be hot. If not,
   43120           ** it can be ignored.
   43121           */
   43122           if( !jrnlOpen ){
   43123             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   43124             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   43125           }
   43126           if( rc==SQLITE_OK ){
   43127             u8 first = 0;
   43128             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   43129             if( rc==SQLITE_IOERR_SHORT_READ ){
   43130               rc = SQLITE_OK;
   43131             }
   43132             if( !jrnlOpen ){
   43133               sqlite3OsClose(pPager->jfd);
   43134             }
   43135             *pExists = (first!=0);
   43136           }else if( rc==SQLITE_CANTOPEN ){
   43137             /* If we cannot open the rollback journal file in order to see if
   43138             ** its has a zero header, that might be due to an I/O error, or
   43139             ** it might be due to the race condition described above and in
   43140             ** ticket #3883.  Either way, assume that the journal is hot.
   43141             ** This might be a false positive.  But if it is, then the
   43142             ** automatic journal playback and recovery mechanism will deal
   43143             ** with it under an EXCLUSIVE lock where we do not need to
   43144             ** worry so much with race conditions.
   43145             */
   43146             *pExists = 1;
   43147             rc = SQLITE_OK;
   43148           }
   43149         }
   43150       }
   43151     }
   43152   }
   43153 
   43154   return rc;
   43155 }
   43156 
   43157 /*
   43158 ** This function is called to obtain a shared lock on the database file.
   43159 ** It is illegal to call sqlite3PagerAcquire() until after this function
   43160 ** has been successfully called. If a shared-lock is already held when
   43161 ** this function is called, it is a no-op.
   43162 **
   43163 ** The following operations are also performed by this function.
   43164 **
   43165 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   43166 **      on the database file), then an attempt is made to obtain a
   43167 **      SHARED lock on the database file. Immediately after obtaining
   43168 **      the SHARED lock, the file-system is checked for a hot-journal,
   43169 **      which is played back if present. Following any hot-journal
   43170 **      rollback, the contents of the cache are validated by checking
   43171 **      the 'change-counter' field of the database file header and
   43172 **      discarded if they are found to be invalid.
   43173 **
   43174 **   2) If the pager is running in exclusive-mode, and there are currently
   43175 **      no outstanding references to any pages, and is in the error state,
   43176 **      then an attempt is made to clear the error state by discarding
   43177 **      the contents of the page cache and rolling back any open journal
   43178 **      file.
   43179 **
   43180 ** If everything is successful, SQLITE_OK is returned. If an IO error
   43181 ** occurs while locking the database, checking for a hot-journal file or
   43182 ** rolling back a journal file, the IO error code is returned.
   43183 */
   43184 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   43185   int rc = SQLITE_OK;                /* Return code */
   43186 
   43187   /* This routine is only called from b-tree and only when there are no
   43188   ** outstanding pages. This implies that the pager state should either
   43189   ** be OPEN or READER. READER is only possible if the pager is or was in
   43190   ** exclusive access mode.
   43191   */
   43192   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   43193   assert( assert_pager_state(pPager) );
   43194   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   43195   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   43196 
   43197   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   43198     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   43199 
   43200     assert( !MEMDB );
   43201 
   43202     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   43203     if( rc!=SQLITE_OK ){
   43204       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   43205       goto failed;
   43206     }
   43207 
   43208     /* If a journal file exists, and there is no RESERVED lock on the
   43209     ** database file, then it either needs to be played back or deleted.
   43210     */
   43211     if( pPager->eLock<=SHARED_LOCK ){
   43212       rc = hasHotJournal(pPager, &bHotJournal);
   43213     }
   43214     if( rc!=SQLITE_OK ){
   43215       goto failed;
   43216     }
   43217     if( bHotJournal ){
   43218       /* Get an EXCLUSIVE lock on the database file. At this point it is
   43219       ** important that a RESERVED lock is not obtained on the way to the
   43220       ** EXCLUSIVE lock. If it were, another process might open the
   43221       ** database file, detect the RESERVED lock, and conclude that the
   43222       ** database is safe to read while this process is still rolling the
   43223       ** hot-journal back.
   43224       **
   43225       ** Because the intermediate RESERVED lock is not requested, any
   43226       ** other process attempting to access the database file will get to
   43227       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   43228       ** on the database file.
   43229       **
   43230       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   43231       ** downgraded to SHARED_LOCK before this function returns.
   43232       */
   43233       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   43234       if( rc!=SQLITE_OK ){
   43235         goto failed;
   43236       }
   43237 
   43238       /* If it is not already open and the file exists on disk, open the
   43239       ** journal for read/write access. Write access is required because
   43240       ** in exclusive-access mode the file descriptor will be kept open
   43241       ** and possibly used for a transaction later on. Also, write-access
   43242       ** is usually required to finalize the journal in journal_mode=persist
   43243       ** mode (and also for journal_mode=truncate on some systems).
   43244       **
   43245       ** If the journal does not exist, it usually means that some
   43246       ** other connection managed to get in and roll it back before
   43247       ** this connection obtained the exclusive lock above. Or, it
   43248       ** may mean that the pager was in the error-state when this
   43249       ** function was called and the journal file does not exist.
   43250       */
   43251       if( !isOpen(pPager->jfd) ){
   43252         sqlite3_vfs * const pVfs = pPager->pVfs;
   43253         int bExists;              /* True if journal file exists */
   43254         rc = sqlite3OsAccess(
   43255             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   43256         if( rc==SQLITE_OK && bExists ){
   43257           int fout = 0;
   43258           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   43259           assert( !pPager->tempFile );
   43260           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   43261           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   43262           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   43263             rc = SQLITE_CANTOPEN_BKPT;
   43264             sqlite3OsClose(pPager->jfd);
   43265           }
   43266         }
   43267       }
   43268 
   43269       /* Playback and delete the journal.  Drop the database write
   43270       ** lock and reacquire the read lock. Purge the cache before
   43271       ** playing back the hot-journal so that we don't end up with
   43272       ** an inconsistent cache.  Sync the hot journal before playing
   43273       ** it back since the process that crashed and left the hot journal
   43274       ** probably did not sync it and we are required to always sync
   43275       ** the journal before playing it back.
   43276       */
   43277       if( isOpen(pPager->jfd) ){
   43278         assert( rc==SQLITE_OK );
   43279         rc = pagerSyncHotJournal(pPager);
   43280         if( rc==SQLITE_OK ){
   43281           rc = pager_playback(pPager, 1);
   43282           pPager->eState = PAGER_OPEN;
   43283         }
   43284       }else if( !pPager->exclusiveMode ){
   43285         pagerUnlockDb(pPager, SHARED_LOCK);
   43286       }
   43287 
   43288       if( rc!=SQLITE_OK ){
   43289         /* This branch is taken if an error occurs while trying to open
   43290         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   43291         ** pager_unlock() routine will be called before returning to unlock
   43292         ** the file. If the unlock attempt fails, then Pager.eLock must be
   43293         ** set to UNKNOWN_LOCK (see the comment above the #define for
   43294         ** UNKNOWN_LOCK above for an explanation).
   43295         **
   43296         ** In order to get pager_unlock() to do this, set Pager.eState to
   43297         ** PAGER_ERROR now. This is not actually counted as a transition
   43298         ** to ERROR state in the state diagram at the top of this file,
   43299         ** since we know that the same call to pager_unlock() will very
   43300         ** shortly transition the pager object to the OPEN state. Calling
   43301         ** assert_pager_state() would fail now, as it should not be possible
   43302         ** to be in ERROR state when there are zero outstanding page
   43303         ** references.
   43304         */
   43305         pager_error(pPager, rc);
   43306         goto failed;
   43307       }
   43308 
   43309       assert( pPager->eState==PAGER_OPEN );
   43310       assert( (pPager->eLock==SHARED_LOCK)
   43311            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   43312       );
   43313     }
   43314 
   43315     if( !pPager->tempFile
   43316      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
   43317     ){
   43318       /* The shared-lock has just been acquired on the database file
   43319       ** and there are already pages in the cache (from a previous
   43320       ** read or write transaction).  Check to see if the database
   43321       ** has been modified.  If the database has changed, flush the
   43322       ** cache.
   43323       **
   43324       ** Database changes is detected by looking at 15 bytes beginning
   43325       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   43326       ** a 32-bit counter that is incremented with each change.  The
   43327       ** other bytes change randomly with each file change when
   43328       ** a codec is in use.
   43329       **
   43330       ** There is a vanishingly small chance that a change will not be
   43331       ** detected.  The chance of an undetected change is so small that
   43332       ** it can be neglected.
   43333       */
   43334       Pgno nPage = 0;
   43335       char dbFileVers[sizeof(pPager->dbFileVers)];
   43336 
   43337       rc = pagerPagecount(pPager, &nPage);
   43338       if( rc ) goto failed;
   43339 
   43340       if( nPage>0 ){
   43341         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   43342         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   43343         if( rc!=SQLITE_OK ){
   43344           goto failed;
   43345         }
   43346       }else{
   43347         memset(dbFileVers, 0, sizeof(dbFileVers));
   43348       }
   43349 
   43350       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   43351         pager_reset(pPager);
   43352       }
   43353     }
   43354 
   43355     /* If there is a WAL file in the file-system, open this database in WAL
   43356     ** mode. Otherwise, the following function call is a no-op.
   43357     */
   43358     rc = pagerOpenWalIfPresent(pPager);
   43359 #ifndef SQLITE_OMIT_WAL
   43360     assert( pPager->pWal==0 || rc==SQLITE_OK );
   43361 #endif
   43362   }
   43363 
   43364   if( pagerUseWal(pPager) ){
   43365     assert( rc==SQLITE_OK );
   43366     rc = pagerBeginReadTransaction(pPager);
   43367   }
   43368 
   43369   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   43370     rc = pagerPagecount(pPager, &pPager->dbSize);
   43371   }
   43372 
   43373  failed:
   43374   if( rc!=SQLITE_OK ){
   43375     assert( !MEMDB );
   43376     pager_unlock(pPager);
   43377     assert( pPager->eState==PAGER_OPEN );
   43378   }else{
   43379     pPager->eState = PAGER_READER;
   43380   }
   43381   return rc;
   43382 }
   43383 
   43384 /*
   43385 ** If the reference count has reached zero, rollback any active
   43386 ** transaction and unlock the pager.
   43387 **
   43388 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   43389 ** the rollback journal, the unlock is not performed and there is
   43390 ** nothing to rollback, so this routine is a no-op.
   43391 */
   43392 static void pagerUnlockIfUnused(Pager *pPager){
   43393   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
   43394     pagerUnlockAndRollback(pPager);
   43395   }
   43396 }
   43397 
   43398 /*
   43399 ** Acquire a reference to page number pgno in pager pPager (a page
   43400 ** reference has type DbPage*). If the requested reference is
   43401 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   43402 **
   43403 ** If the requested page is already in the cache, it is returned.
   43404 ** Otherwise, a new page object is allocated and populated with data
   43405 ** read from the database file. In some cases, the pcache module may
   43406 ** choose not to allocate a new page object and may reuse an existing
   43407 ** object with no outstanding references.
   43408 **
   43409 ** The extra data appended to a page is always initialized to zeros the
   43410 ** first time a page is loaded into memory. If the page requested is
   43411 ** already in the cache when this function is called, then the extra
   43412 ** data is left as it was when the page object was last used.
   43413 **
   43414 ** If the database image is smaller than the requested page or if a
   43415 ** non-zero value is passed as the noContent parameter and the
   43416 ** requested page is not already stored in the cache, then no
   43417 ** actual disk read occurs. In this case the memory image of the
   43418 ** page is initialized to all zeros.
   43419 **
   43420 ** If noContent is true, it means that we do not care about the contents
   43421 ** of the page. This occurs in two seperate scenarios:
   43422 **
   43423 **   a) When reading a free-list leaf page from the database, and
   43424 **
   43425 **   b) When a savepoint is being rolled back and we need to load
   43426 **      a new page into the cache to be filled with the data read
   43427 **      from the savepoint journal.
   43428 **
   43429 ** If noContent is true, then the data returned is zeroed instead of
   43430 ** being read from the database. Additionally, the bits corresponding
   43431 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   43432 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   43433 ** savepoints are set. This means if the page is made writable at any
   43434 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   43435 ** will not be journaled. This saves IO.
   43436 **
   43437 ** The acquisition might fail for several reasons.  In all cases,
   43438 ** an appropriate error code is returned and *ppPage is set to NULL.
   43439 **
   43440 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   43441 ** to find a page in the in-memory cache first.  If the page is not already
   43442 ** in memory, this routine goes to disk to read it in whereas Lookup()
   43443 ** just returns 0.  This routine acquires a read-lock the first time it
   43444 ** has to go to disk, and could also playback an old journal if necessary.
   43445 ** Since Lookup() never goes to disk, it never has to deal with locks
   43446 ** or journal files.
   43447 */
   43448 SQLITE_PRIVATE int sqlite3PagerAcquire(
   43449   Pager *pPager,      /* The pager open on the database file */
   43450   Pgno pgno,          /* Page number to fetch */
   43451   DbPage **ppPage,    /* Write a pointer to the page here */
   43452   int noContent       /* Do not bother reading content from disk if true */
   43453 ){
   43454   int rc;
   43455   PgHdr *pPg;
   43456 
   43457   assert( pPager->eState>=PAGER_READER );
   43458   assert( assert_pager_state(pPager) );
   43459 
   43460   if( pgno==0 ){
   43461     return SQLITE_CORRUPT_BKPT;
   43462   }
   43463 
   43464   /* If the pager is in the error state, return an error immediately.
   43465   ** Otherwise, request the page from the PCache layer. */
   43466   if( pPager->errCode!=SQLITE_OK ){
   43467     rc = pPager->errCode;
   43468   }else{
   43469     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   43470   }
   43471 
   43472   if( rc!=SQLITE_OK ){
   43473     /* Either the call to sqlite3PcacheFetch() returned an error or the
   43474     ** pager was already in the error-state when this function was called.
   43475     ** Set pPg to 0 and jump to the exception handler.  */
   43476     pPg = 0;
   43477     goto pager_acquire_err;
   43478   }
   43479   assert( (*ppPage)->pgno==pgno );
   43480   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   43481 
   43482   if( (*ppPage)->pPager && !noContent ){
   43483     /* In this case the pcache already contains an initialized copy of
   43484     ** the page. Return without further ado.  */
   43485     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   43486     pPager->nHit++;
   43487     return SQLITE_OK;
   43488 
   43489   }else{
   43490     /* The pager cache has created a new page. Its content needs to
   43491     ** be initialized.  */
   43492 
   43493     pPg = *ppPage;
   43494     pPg->pPager = pPager;
   43495 
   43496     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   43497     ** number greater than this, or the unused locking-page, is requested. */
   43498     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   43499       rc = SQLITE_CORRUPT_BKPT;
   43500       goto pager_acquire_err;
   43501     }
   43502 
   43503     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
   43504       if( pgno>pPager->mxPgno ){
   43505         rc = SQLITE_FULL;
   43506         goto pager_acquire_err;
   43507       }
   43508       if( noContent ){
   43509         /* Failure to set the bits in the InJournal bit-vectors is benign.
   43510         ** It merely means that we might do some extra work to journal a
   43511         ** page that does not need to be journaled.  Nevertheless, be sure
   43512         ** to test the case where a malloc error occurs while trying to set
   43513         ** a bit in a bit vector.
   43514         */
   43515         sqlite3BeginBenignMalloc();
   43516         if( pgno<=pPager->dbOrigSize ){
   43517           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   43518           testcase( rc==SQLITE_NOMEM );
   43519         }
   43520         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   43521         testcase( rc==SQLITE_NOMEM );
   43522         sqlite3EndBenignMalloc();
   43523       }
   43524       memset(pPg->pData, 0, pPager->pageSize);
   43525       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   43526     }else{
   43527       assert( pPg->pPager==pPager );
   43528       pPager->nMiss++;
   43529       rc = readDbPage(pPg);
   43530       if( rc!=SQLITE_OK ){
   43531         goto pager_acquire_err;
   43532       }
   43533     }
   43534     pager_set_pagehash(pPg);
   43535   }
   43536 
   43537   return SQLITE_OK;
   43538 
   43539 pager_acquire_err:
   43540   assert( rc!=SQLITE_OK );
   43541   if( pPg ){
   43542     sqlite3PcacheDrop(pPg);
   43543   }
   43544   pagerUnlockIfUnused(pPager);
   43545 
   43546   *ppPage = 0;
   43547   return rc;
   43548 }
   43549 
   43550 /*
   43551 ** Acquire a page if it is already in the in-memory cache.  Do
   43552 ** not read the page from disk.  Return a pointer to the page,
   43553 ** or 0 if the page is not in cache.
   43554 **
   43555 ** See also sqlite3PagerGet().  The difference between this routine
   43556 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   43557 ** in the page if the page is not already in cache.  This routine
   43558 ** returns NULL if the page is not in cache or if a disk I/O error
   43559 ** has ever happened.
   43560 */
   43561 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   43562   PgHdr *pPg = 0;
   43563   assert( pPager!=0 );
   43564   assert( pgno!=0 );
   43565   assert( pPager->pPCache!=0 );
   43566   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
   43567   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   43568   return pPg;
   43569 }
   43570 
   43571 /*
   43572 ** Release a page reference.
   43573 **
   43574 ** If the number of references to the page drop to zero, then the
   43575 ** page is added to the LRU list.  When all references to all pages
   43576 ** are released, a rollback occurs and the lock on the database is
   43577 ** removed.
   43578 */
   43579 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   43580   if( pPg ){
   43581     Pager *pPager = pPg->pPager;
   43582     sqlite3PcacheRelease(pPg);
   43583     pagerUnlockIfUnused(pPager);
   43584   }
   43585 }
   43586 
   43587 /*
   43588 ** This function is called at the start of every write transaction.
   43589 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   43590 ** file when this routine is called.
   43591 **
   43592 ** Open the journal file for pager pPager and write a journal header
   43593 ** to the start of it. If there are active savepoints, open the sub-journal
   43594 ** as well. This function is only used when the journal file is being
   43595 ** opened to write a rollback log for a transaction. It is not used
   43596 ** when opening a hot journal file to roll it back.
   43597 **
   43598 ** If the journal file is already open (as it may be in exclusive mode),
   43599 ** then this function just writes a journal header to the start of the
   43600 ** already open file.
   43601 **
   43602 ** Whether or not the journal file is opened by this function, the
   43603 ** Pager.pInJournal bitvec structure is allocated.
   43604 **
   43605 ** Return SQLITE_OK if everything is successful. Otherwise, return
   43606 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   43607 ** an IO error code if opening or writing the journal file fails.
   43608 */
   43609 static int pager_open_journal(Pager *pPager){
   43610   int rc = SQLITE_OK;                        /* Return code */
   43611   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   43612 
   43613   assert( pPager->eState==PAGER_WRITER_LOCKED );
   43614   assert( assert_pager_state(pPager) );
   43615   assert( pPager->pInJournal==0 );
   43616 
   43617   /* If already in the error state, this function is a no-op.  But on
   43618   ** the other hand, this routine is never called if we are already in
   43619   ** an error state. */
   43620   if( NEVER(pPager->errCode) ) return pPager->errCode;
   43621 
   43622   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   43623     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   43624     if( pPager->pInJournal==0 ){
   43625       return SQLITE_NOMEM;
   43626     }
   43627 
   43628     /* Open the journal file if it is not already open. */
   43629     if( !isOpen(pPager->jfd) ){
   43630       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   43631         sqlite3MemJournalOpen(pPager->jfd);
   43632       }else{
   43633         const int flags =                   /* VFS flags to open journal file */
   43634           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   43635           (pPager->tempFile ?
   43636             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   43637             (SQLITE_OPEN_MAIN_JOURNAL)
   43638           );
   43639   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   43640         rc = sqlite3JournalOpen(
   43641             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   43642         );
   43643   #else
   43644         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   43645   #endif
   43646       }
   43647       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   43648     }
   43649 
   43650 
   43651     /* Write the first journal header to the journal file and open
   43652     ** the sub-journal if necessary.
   43653     */
   43654     if( rc==SQLITE_OK ){
   43655       /* TODO: Check if all of these are really required. */
   43656       pPager->nRec = 0;
   43657       pPager->journalOff = 0;
   43658       pPager->setMaster = 0;
   43659       pPager->journalHdr = 0;
   43660       rc = writeJournalHdr(pPager);
   43661     }
   43662   }
   43663 
   43664   if( rc!=SQLITE_OK ){
   43665     sqlite3BitvecDestroy(pPager->pInJournal);
   43666     pPager->pInJournal = 0;
   43667   }else{
   43668     assert( pPager->eState==PAGER_WRITER_LOCKED );
   43669     pPager->eState = PAGER_WRITER_CACHEMOD;
   43670   }
   43671 
   43672   return rc;
   43673 }
   43674 
   43675 /*
   43676 ** Begin a write-transaction on the specified pager object. If a
   43677 ** write-transaction has already been opened, this function is a no-op.
   43678 **
   43679 ** If the exFlag argument is false, then acquire at least a RESERVED
   43680 ** lock on the database file. If exFlag is true, then acquire at least
   43681 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   43682 ** functions need be called.
   43683 **
   43684 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   43685 ** within this transaction will be opened as an in-memory file. This
   43686 ** has no effect if the sub-journal is already opened (as it may be when
   43687 ** running in exclusive mode) or if the transaction does not require a
   43688 ** sub-journal. If the subjInMemory argument is zero, then any required
   43689 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   43690 ** or using a temporary file otherwise.
   43691 */
   43692 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   43693   int rc = SQLITE_OK;
   43694 
   43695   if( pPager->errCode ) return pPager->errCode;
   43696   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   43697   pPager->subjInMemory = (u8)subjInMemory;
   43698 
   43699   if( ALWAYS(pPager->eState==PAGER_READER) ){
   43700     assert( pPager->pInJournal==0 );
   43701 
   43702     if( pagerUseWal(pPager) ){
   43703       /* If the pager is configured to use locking_mode=exclusive, and an
   43704       ** exclusive lock on the database is not already held, obtain it now.
   43705       */
   43706       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   43707         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   43708         if( rc!=SQLITE_OK ){
   43709           return rc;
   43710         }
   43711         sqlite3WalExclusiveMode(pPager->pWal, 1);
   43712       }
   43713 
   43714       /* Grab the write lock on the log file. If successful, upgrade to
   43715       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   43716       ** The busy-handler is not invoked if another connection already
   43717       ** holds the write-lock. If possible, the upper layer will call it.
   43718       */
   43719       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   43720     }else{
   43721       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   43722       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   43723       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   43724       ** lock, but not when obtaining the RESERVED lock.
   43725       */
   43726       rc = pagerLockDb(pPager, RESERVED_LOCK);
   43727       if( rc==SQLITE_OK && exFlag ){
   43728         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   43729       }
   43730     }
   43731 
   43732     if( rc==SQLITE_OK ){
   43733       /* Change to WRITER_LOCKED state.
   43734       **
   43735       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   43736       ** when it has an open transaction, but never to DBMOD or FINISHED.
   43737       ** This is because in those states the code to roll back savepoint
   43738       ** transactions may copy data from the sub-journal into the database
   43739       ** file as well as into the page cache. Which would be incorrect in
   43740       ** WAL mode.
   43741       */
   43742       pPager->eState = PAGER_WRITER_LOCKED;
   43743       pPager->dbHintSize = pPager->dbSize;
   43744       pPager->dbFileSize = pPager->dbSize;
   43745       pPager->dbOrigSize = pPager->dbSize;
   43746       pPager->journalOff = 0;
   43747     }
   43748 
   43749     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   43750     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   43751     assert( assert_pager_state(pPager) );
   43752   }
   43753 
   43754   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   43755   return rc;
   43756 }
   43757 
   43758 /*
   43759 ** Mark a single data page as writeable. The page is written into the
   43760 ** main journal or sub-journal as required. If the page is written into
   43761 ** one of the journals, the corresponding bit is set in the
   43762 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   43763 ** of any open savepoints as appropriate.
   43764 */
   43765 static int pager_write(PgHdr *pPg){
   43766   void *pData = pPg->pData;
   43767   Pager *pPager = pPg->pPager;
   43768   int rc = SQLITE_OK;
   43769 
   43770   /* This routine is not called unless a write-transaction has already
   43771   ** been started. The journal file may or may not be open at this point.
   43772   ** It is never called in the ERROR state.
   43773   */
   43774   assert( pPager->eState==PAGER_WRITER_LOCKED
   43775        || pPager->eState==PAGER_WRITER_CACHEMOD
   43776        || pPager->eState==PAGER_WRITER_DBMOD
   43777   );
   43778   assert( assert_pager_state(pPager) );
   43779 
   43780   /* If an error has been previously detected, report the same error
   43781   ** again. This should not happen, but the check provides robustness. */
   43782   if( NEVER(pPager->errCode) )  return pPager->errCode;
   43783 
   43784   /* Higher-level routines never call this function if database is not
   43785   ** writable.  But check anyway, just for robustness. */
   43786   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
   43787 
   43788   CHECK_PAGE(pPg);
   43789 
   43790   /* The journal file needs to be opened. Higher level routines have already
   43791   ** obtained the necessary locks to begin the write-transaction, but the
   43792   ** rollback journal might not yet be open. Open it now if this is the case.
   43793   **
   43794   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   43795   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   43796   ** an error might occur and the pager would end up in WRITER_LOCKED state
   43797   ** with pages marked as dirty in the cache.
   43798   */
   43799   if( pPager->eState==PAGER_WRITER_LOCKED ){
   43800     rc = pager_open_journal(pPager);
   43801     if( rc!=SQLITE_OK ) return rc;
   43802   }
   43803   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   43804   assert( assert_pager_state(pPager) );
   43805 
   43806   /* Mark the page as dirty.  If the page has already been written
   43807   ** to the journal then we can return right away.
   43808   */
   43809   sqlite3PcacheMakeDirty(pPg);
   43810   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
   43811     assert( !pagerUseWal(pPager) );
   43812   }else{
   43813 
   43814     /* The transaction journal now exists and we have a RESERVED or an
   43815     ** EXCLUSIVE lock on the main database file.  Write the current page to
   43816     ** the transaction journal if it is not there already.
   43817     */
   43818     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
   43819       assert( pagerUseWal(pPager)==0 );
   43820       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
   43821         u32 cksum;
   43822         char *pData2;
   43823         i64 iOff = pPager->journalOff;
   43824 
   43825         /* We should never write to the journal file the page that
   43826         ** contains the database locks.  The following assert verifies
   43827         ** that we do not. */
   43828         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   43829 
   43830         assert( pPager->journalHdr<=pPager->journalOff );
   43831         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   43832         cksum = pager_cksum(pPager, (u8*)pData2);
   43833 
   43834         /* Even if an IO or diskfull error occurs while journalling the
   43835         ** page in the block above, set the need-sync flag for the page.
   43836         ** Otherwise, when the transaction is rolled back, the logic in
   43837         ** playback_one_page() will think that the page needs to be restored
   43838         ** in the database file. And if an IO error occurs while doing so,
   43839         ** then corruption may follow.
   43840         */
   43841         pPg->flags |= PGHDR_NEED_SYNC;
   43842 
   43843         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   43844         if( rc!=SQLITE_OK ) return rc;
   43845         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   43846         if( rc!=SQLITE_OK ) return rc;
   43847         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   43848         if( rc!=SQLITE_OK ) return rc;
   43849 
   43850         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   43851                  pPager->journalOff, pPager->pageSize));
   43852         PAGER_INCR(sqlite3_pager_writej_count);
   43853         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   43854              PAGERID(pPager), pPg->pgno,
   43855              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   43856 
   43857         pPager->journalOff += 8 + pPager->pageSize;
   43858         pPager->nRec++;
   43859         assert( pPager->pInJournal!=0 );
   43860         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   43861         testcase( rc==SQLITE_NOMEM );
   43862         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   43863         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   43864         if( rc!=SQLITE_OK ){
   43865           assert( rc==SQLITE_NOMEM );
   43866           return rc;
   43867         }
   43868       }else{
   43869         if( pPager->eState!=PAGER_WRITER_DBMOD ){
   43870           pPg->flags |= PGHDR_NEED_SYNC;
   43871         }
   43872         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   43873                 PAGERID(pPager), pPg->pgno,
   43874                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   43875       }
   43876     }
   43877 
   43878     /* If the statement journal is open and the page is not in it,
   43879     ** then write the current page to the statement journal.  Note that
   43880     ** the statement journal format differs from the standard journal format
   43881     ** in that it omits the checksums and the header.
   43882     */
   43883     if( subjRequiresPage(pPg) ){
   43884       rc = subjournalPage(pPg);
   43885     }
   43886   }
   43887 
   43888   /* Update the database size and return.
   43889   */
   43890   if( pPager->dbSize<pPg->pgno ){
   43891     pPager->dbSize = pPg->pgno;
   43892   }
   43893   return rc;
   43894 }
   43895 
   43896 /*
   43897 ** Mark a data page as writeable. This routine must be called before
   43898 ** making changes to a page. The caller must check the return value
   43899 ** of this function and be careful not to change any page data unless
   43900 ** this routine returns SQLITE_OK.
   43901 **
   43902 ** The difference between this function and pager_write() is that this
   43903 ** function also deals with the special case where 2 or more pages
   43904 ** fit on a single disk sector. In this case all co-resident pages
   43905 ** must have been written to the journal file before returning.
   43906 **
   43907 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   43908 ** as appropriate. Otherwise, SQLITE_OK.
   43909 */
   43910 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   43911   int rc = SQLITE_OK;
   43912 
   43913   PgHdr *pPg = pDbPage;
   43914   Pager *pPager = pPg->pPager;
   43915   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   43916 
   43917   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   43918   assert( pPager->eState!=PAGER_ERROR );
   43919   assert( assert_pager_state(pPager) );
   43920 
   43921   if( nPagePerSector>1 ){
   43922     Pgno nPageCount;          /* Total number of pages in database file */
   43923     Pgno pg1;                 /* First page of the sector pPg is located on. */
   43924     int nPage = 0;            /* Number of pages starting at pg1 to journal */
   43925     int ii;                   /* Loop counter */
   43926     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   43927 
   43928     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
   43929     ** a journal header to be written between the pages journaled by
   43930     ** this function.
   43931     */
   43932     assert( !MEMDB );
   43933     assert( pPager->doNotSyncSpill==0 );
   43934     pPager->doNotSyncSpill++;
   43935 
   43936     /* This trick assumes that both the page-size and sector-size are
   43937     ** an integer power of 2. It sets variable pg1 to the identifier
   43938     ** of the first page of the sector pPg is located on.
   43939     */
   43940     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   43941 
   43942     nPageCount = pPager->dbSize;
   43943     if( pPg->pgno>nPageCount ){
   43944       nPage = (pPg->pgno - pg1)+1;
   43945     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   43946       nPage = nPageCount+1-pg1;
   43947     }else{
   43948       nPage = nPagePerSector;
   43949     }
   43950     assert(nPage>0);
   43951     assert(pg1<=pPg->pgno);
   43952     assert((pg1+nPage)>pPg->pgno);
   43953 
   43954     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   43955       Pgno pg = pg1+ii;
   43956       PgHdr *pPage;
   43957       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   43958         if( pg!=PAGER_MJ_PGNO(pPager) ){
   43959           rc = sqlite3PagerGet(pPager, pg, &pPage);
   43960           if( rc==SQLITE_OK ){
   43961             rc = pager_write(pPage);
   43962             if( pPage->flags&PGHDR_NEED_SYNC ){
   43963               needSync = 1;
   43964             }
   43965             sqlite3PagerUnref(pPage);
   43966           }
   43967         }
   43968       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   43969         if( pPage->flags&PGHDR_NEED_SYNC ){
   43970           needSync = 1;
   43971         }
   43972         sqlite3PagerUnref(pPage);
   43973       }
   43974     }
   43975 
   43976     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   43977     ** starting at pg1, then it needs to be set for all of them. Because
   43978     ** writing to any of these nPage pages may damage the others, the
   43979     ** journal file must contain sync()ed copies of all of them
   43980     ** before any of them can be written out to the database file.
   43981     */
   43982     if( rc==SQLITE_OK && needSync ){
   43983       assert( !MEMDB );
   43984       for(ii=0; ii<nPage; ii++){
   43985         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   43986         if( pPage ){
   43987           pPage->flags |= PGHDR_NEED_SYNC;
   43988           sqlite3PagerUnref(pPage);
   43989         }
   43990       }
   43991     }
   43992 
   43993     assert( pPager->doNotSyncSpill==1 );
   43994     pPager->doNotSyncSpill--;
   43995   }else{
   43996     rc = pager_write(pDbPage);
   43997   }
   43998   return rc;
   43999 }
   44000 
   44001 /*
   44002 ** Return TRUE if the page given in the argument was previously passed
   44003 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   44004 ** to change the content of the page.
   44005 */
   44006 #ifndef NDEBUG
   44007 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   44008   return pPg->flags&PGHDR_DIRTY;
   44009 }
   44010 #endif
   44011 
   44012 /*
   44013 ** A call to this routine tells the pager that it is not necessary to
   44014 ** write the information on page pPg back to the disk, even though
   44015 ** that page might be marked as dirty.  This happens, for example, when
   44016 ** the page has been added as a leaf of the freelist and so its
   44017 ** content no longer matters.
   44018 **
   44019 ** The overlying software layer calls this routine when all of the data
   44020 ** on the given page is unused. The pager marks the page as clean so
   44021 ** that it does not get written to disk.
   44022 **
   44023 ** Tests show that this optimization can quadruple the speed of large
   44024 ** DELETE operations.
   44025 */
   44026 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   44027   Pager *pPager = pPg->pPager;
   44028   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   44029     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   44030     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   44031     pPg->flags |= PGHDR_DONT_WRITE;
   44032     pager_set_pagehash(pPg);
   44033   }
   44034 }
   44035 
   44036 /*
   44037 ** This routine is called to increment the value of the database file
   44038 ** change-counter, stored as a 4-byte big-endian integer starting at
   44039 ** byte offset 24 of the pager file.  The secondary change counter at
   44040 ** 92 is also updated, as is the SQLite version number at offset 96.
   44041 **
   44042 ** But this only happens if the pPager->changeCountDone flag is false.
   44043 ** To avoid excess churning of page 1, the update only happens once.
   44044 ** See also the pager_write_changecounter() routine that does an
   44045 ** unconditional update of the change counters.
   44046 **
   44047 ** If the isDirectMode flag is zero, then this is done by calling
   44048 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   44049 ** page data. In this case the file will be updated when the current
   44050 ** transaction is committed.
   44051 **
   44052 ** The isDirectMode flag may only be non-zero if the library was compiled
   44053 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   44054 ** if isDirect is non-zero, then the database file is updated directly
   44055 ** by writing an updated version of page 1 using a call to the
   44056 ** sqlite3OsWrite() function.
   44057 */
   44058 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   44059   int rc = SQLITE_OK;
   44060 
   44061   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44062        || pPager->eState==PAGER_WRITER_DBMOD
   44063   );
   44064   assert( assert_pager_state(pPager) );
   44065 
   44066   /* Declare and initialize constant integer 'isDirect'. If the
   44067   ** atomic-write optimization is enabled in this build, then isDirect
   44068   ** is initialized to the value passed as the isDirectMode parameter
   44069   ** to this function. Otherwise, it is always set to zero.
   44070   **
   44071   ** The idea is that if the atomic-write optimization is not
   44072   ** enabled at compile time, the compiler can omit the tests of
   44073   ** 'isDirect' below, as well as the block enclosed in the
   44074   ** "if( isDirect )" condition.
   44075   */
   44076 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   44077 # define DIRECT_MODE 0
   44078   assert( isDirectMode==0 );
   44079   UNUSED_PARAMETER(isDirectMode);
   44080 #else
   44081 # define DIRECT_MODE isDirectMode
   44082 #endif
   44083 
   44084   if( !pPager->changeCountDone && pPager->dbSize>0 ){
   44085     PgHdr *pPgHdr;                /* Reference to page 1 */
   44086 
   44087     assert( !pPager->tempFile && isOpen(pPager->fd) );
   44088 
   44089     /* Open page 1 of the file for writing. */
   44090     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   44091     assert( pPgHdr==0 || rc==SQLITE_OK );
   44092 
   44093     /* If page one was fetched successfully, and this function is not
   44094     ** operating in direct-mode, make page 1 writable.  When not in
   44095     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   44096     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   44097     */
   44098     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   44099       rc = sqlite3PagerWrite(pPgHdr);
   44100     }
   44101 
   44102     if( rc==SQLITE_OK ){
   44103       /* Actually do the update of the change counter */
   44104       pager_write_changecounter(pPgHdr);
   44105 
   44106       /* If running in direct mode, write the contents of page 1 to the file. */
   44107       if( DIRECT_MODE ){
   44108         const void *zBuf;
   44109         assert( pPager->dbFileSize>0 );
   44110         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
   44111         if( rc==SQLITE_OK ){
   44112           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   44113         }
   44114         if( rc==SQLITE_OK ){
   44115           pPager->changeCountDone = 1;
   44116         }
   44117       }else{
   44118         pPager->changeCountDone = 1;
   44119       }
   44120     }
   44121 
   44122     /* Release the page reference. */
   44123     sqlite3PagerUnref(pPgHdr);
   44124   }
   44125   return rc;
   44126 }
   44127 
   44128 /*
   44129 ** Sync the database file to disk. This is a no-op for in-memory databases
   44130 ** or pages with the Pager.noSync flag set.
   44131 **
   44132 ** If successful, or if called on a pager for which it is a no-op, this
   44133 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   44134 */
   44135 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
   44136   int rc = SQLITE_OK;
   44137   if( !pPager->noSync ){
   44138     assert( !MEMDB );
   44139     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   44140   }else if( isOpen(pPager->fd) ){
   44141     assert( !MEMDB );
   44142     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
   44143     if( rc==SQLITE_NOTFOUND ){
   44144       rc = SQLITE_OK;
   44145     }
   44146   }
   44147   return rc;
   44148 }
   44149 
   44150 /*
   44151 ** This function may only be called while a write-transaction is active in
   44152 ** rollback. If the connection is in WAL mode, this call is a no-op.
   44153 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   44154 ** the database file, an attempt is made to obtain one.
   44155 **
   44156 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   44157 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   44158 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   44159 ** returned.
   44160 */
   44161 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   44162   int rc = SQLITE_OK;
   44163   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44164        || pPager->eState==PAGER_WRITER_DBMOD
   44165        || pPager->eState==PAGER_WRITER_LOCKED
   44166   );
   44167   assert( assert_pager_state(pPager) );
   44168   if( 0==pagerUseWal(pPager) ){
   44169     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   44170   }
   44171   return rc;
   44172 }
   44173 
   44174 /*
   44175 ** Sync the database file for the pager pPager. zMaster points to the name
   44176 ** of a master journal file that should be written into the individual
   44177 ** journal file. zMaster may be NULL, which is interpreted as no master
   44178 ** journal (a single database transaction).
   44179 **
   44180 ** This routine ensures that:
   44181 **
   44182 **   * The database file change-counter is updated,
   44183 **   * the journal is synced (unless the atomic-write optimization is used),
   44184 **   * all dirty pages are written to the database file,
   44185 **   * the database file is truncated (if required), and
   44186 **   * the database file synced.
   44187 **
   44188 ** The only thing that remains to commit the transaction is to finalize
   44189 ** (delete, truncate or zero the first part of) the journal file (or
   44190 ** delete the master journal file if specified).
   44191 **
   44192 ** Note that if zMaster==NULL, this does not overwrite a previous value
   44193 ** passed to an sqlite3PagerCommitPhaseOne() call.
   44194 **
   44195 ** If the final parameter - noSync - is true, then the database file itself
   44196 ** is not synced. The caller must call sqlite3PagerSync() directly to
   44197 ** sync the database file before calling CommitPhaseTwo() to delete the
   44198 ** journal file in this case.
   44199 */
   44200 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   44201   Pager *pPager,                  /* Pager object */
   44202   const char *zMaster,            /* If not NULL, the master journal name */
   44203   int noSync                      /* True to omit the xSync on the db file */
   44204 ){
   44205   int rc = SQLITE_OK;             /* Return code */
   44206 
   44207   assert( pPager->eState==PAGER_WRITER_LOCKED
   44208        || pPager->eState==PAGER_WRITER_CACHEMOD
   44209        || pPager->eState==PAGER_WRITER_DBMOD
   44210        || pPager->eState==PAGER_ERROR
   44211   );
   44212   assert( assert_pager_state(pPager) );
   44213 
   44214   /* If a prior error occurred, report that error again. */
   44215   if( NEVER(pPager->errCode) ) return pPager->errCode;
   44216 
   44217   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   44218       pPager->zFilename, zMaster, pPager->dbSize));
   44219 
   44220   /* If no database changes have been made, return early. */
   44221   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   44222 
   44223   if( MEMDB ){
   44224     /* If this is an in-memory db, or no pages have been written to, or this
   44225     ** function has already been called, it is mostly a no-op.  However, any
   44226     ** backup in progress needs to be restarted.
   44227     */
   44228     sqlite3BackupRestart(pPager->pBackup);
   44229   }else{
   44230     if( pagerUseWal(pPager) ){
   44231       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   44232       PgHdr *pPageOne = 0;
   44233       if( pList==0 ){
   44234         /* Must have at least one page for the WAL commit flag.
   44235         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
   44236         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
   44237         pList = pPageOne;
   44238         pList->pDirty = 0;
   44239       }
   44240       assert( rc==SQLITE_OK );
   44241       if( ALWAYS(pList) ){
   44242         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
   44243       }
   44244       sqlite3PagerUnref(pPageOne);
   44245       if( rc==SQLITE_OK ){
   44246         sqlite3PcacheCleanAll(pPager->pPCache);
   44247       }
   44248     }else{
   44249       /* The following block updates the change-counter. Exactly how it
   44250       ** does this depends on whether or not the atomic-update optimization
   44251       ** was enabled at compile time, and if this transaction meets the
   44252       ** runtime criteria to use the operation:
   44253       **
   44254       **    * The file-system supports the atomic-write property for
   44255       **      blocks of size page-size, and
   44256       **    * This commit is not part of a multi-file transaction, and
   44257       **    * Exactly one page has been modified and store in the journal file.
   44258       **
   44259       ** If the optimization was not enabled at compile time, then the
   44260       ** pager_incr_changecounter() function is called to update the change
   44261       ** counter in 'indirect-mode'. If the optimization is compiled in but
   44262       ** is not applicable to this transaction, call sqlite3JournalCreate()
   44263       ** to make sure the journal file has actually been created, then call
   44264       ** pager_incr_changecounter() to update the change-counter in indirect
   44265       ** mode.
   44266       **
   44267       ** Otherwise, if the optimization is both enabled and applicable,
   44268       ** then call pager_incr_changecounter() to update the change-counter
   44269       ** in 'direct' mode. In this case the journal file will never be
   44270       ** created for this transaction.
   44271       */
   44272   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   44273       PgHdr *pPg;
   44274       assert( isOpen(pPager->jfd)
   44275            || pPager->journalMode==PAGER_JOURNALMODE_OFF
   44276            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   44277       );
   44278       if( !zMaster && isOpen(pPager->jfd)
   44279        && pPager->journalOff==jrnlBufferSize(pPager)
   44280        && pPager->dbSize>=pPager->dbOrigSize
   44281        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   44282       ){
   44283         /* Update the db file change counter via the direct-write method. The
   44284         ** following call will modify the in-memory representation of page 1
   44285         ** to include the updated change counter and then write page 1
   44286         ** directly to the database file. Because of the atomic-write
   44287         ** property of the host file-system, this is safe.
   44288         */
   44289         rc = pager_incr_changecounter(pPager, 1);
   44290       }else{
   44291         rc = sqlite3JournalCreate(pPager->jfd);
   44292         if( rc==SQLITE_OK ){
   44293           rc = pager_incr_changecounter(pPager, 0);
   44294         }
   44295       }
   44296   #else
   44297       rc = pager_incr_changecounter(pPager, 0);
   44298   #endif
   44299       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44300 
   44301       /* If this transaction has made the database smaller, then all pages
   44302       ** being discarded by the truncation must be written to the journal
   44303       ** file. This can only happen in auto-vacuum mode.
   44304       **
   44305       ** Before reading the pages with page numbers larger than the
   44306       ** current value of Pager.dbSize, set dbSize back to the value
   44307       ** that it took at the start of the transaction. Otherwise, the
   44308       ** calls to sqlite3PagerGet() return zeroed pages instead of
   44309       ** reading data from the database file.
   44310       */
   44311   #ifndef SQLITE_OMIT_AUTOVACUUM
   44312       if( pPager->dbSize<pPager->dbOrigSize
   44313        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
   44314       ){
   44315         Pgno i;                                   /* Iterator variable */
   44316         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
   44317         const Pgno dbSize = pPager->dbSize;       /* Database image size */
   44318         pPager->dbSize = pPager->dbOrigSize;
   44319         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
   44320           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
   44321             PgHdr *pPage;             /* Page to journal */
   44322             rc = sqlite3PagerGet(pPager, i, &pPage);
   44323             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44324             rc = sqlite3PagerWrite(pPage);
   44325             sqlite3PagerUnref(pPage);
   44326             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44327           }
   44328         }
   44329         pPager->dbSize = dbSize;
   44330       }
   44331   #endif
   44332 
   44333       /* Write the master journal name into the journal file. If a master
   44334       ** journal file name has already been written to the journal file,
   44335       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   44336       */
   44337       rc = writeMasterJournal(pPager, zMaster);
   44338       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44339 
   44340       /* Sync the journal file and write all dirty pages to the database.
   44341       ** If the atomic-update optimization is being used, this sync will not
   44342       ** create the journal file or perform any real IO.
   44343       **
   44344       ** Because the change-counter page was just modified, unless the
   44345       ** atomic-update optimization is used it is almost certain that the
   44346       ** journal requires a sync here. However, in locking_mode=exclusive
   44347       ** on a system under memory pressure it is just possible that this is
   44348       ** not the case. In this case it is likely enough that the redundant
   44349       ** xSync() call will be changed to a no-op by the OS anyhow.
   44350       */
   44351       rc = syncJournal(pPager, 0);
   44352       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44353 
   44354       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   44355       if( rc!=SQLITE_OK ){
   44356         assert( rc!=SQLITE_IOERR_BLOCKED );
   44357         goto commit_phase_one_exit;
   44358       }
   44359       sqlite3PcacheCleanAll(pPager->pPCache);
   44360 
   44361       /* If the file on disk is not the same size as the database image,
   44362       ** then use pager_truncate to grow or shrink the file here.
   44363       */
   44364       if( pPager->dbSize!=pPager->dbFileSize ){
   44365         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   44366         assert( pPager->eState==PAGER_WRITER_DBMOD );
   44367         rc = pager_truncate(pPager, nNew);
   44368         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44369       }
   44370 
   44371       /* Finally, sync the database file. */
   44372       if( !noSync ){
   44373         rc = sqlite3PagerSync(pPager);
   44374       }
   44375       IOTRACE(("DBSYNC %p\n", pPager))
   44376     }
   44377   }
   44378 
   44379 commit_phase_one_exit:
   44380   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   44381     pPager->eState = PAGER_WRITER_FINISHED;
   44382   }
   44383   return rc;
   44384 }
   44385 
   44386 
   44387 /*
   44388 ** When this function is called, the database file has been completely
   44389 ** updated to reflect the changes made by the current transaction and
   44390 ** synced to disk. The journal file still exists in the file-system
   44391 ** though, and if a failure occurs at this point it will eventually
   44392 ** be used as a hot-journal and the current transaction rolled back.
   44393 **
   44394 ** This function finalizes the journal file, either by deleting,
   44395 ** truncating or partially zeroing it, so that it cannot be used
   44396 ** for hot-journal rollback. Once this is done the transaction is
   44397 ** irrevocably committed.
   44398 **
   44399 ** If an error occurs, an IO error code is returned and the pager
   44400 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   44401 */
   44402 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   44403   int rc = SQLITE_OK;                  /* Return code */
   44404 
   44405   /* This routine should not be called if a prior error has occurred.
   44406   ** But if (due to a coding error elsewhere in the system) it does get
   44407   ** called, just return the same error code without doing anything. */
   44408   if( NEVER(pPager->errCode) ) return pPager->errCode;
   44409 
   44410   assert( pPager->eState==PAGER_WRITER_LOCKED
   44411        || pPager->eState==PAGER_WRITER_FINISHED
   44412        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   44413   );
   44414   assert( assert_pager_state(pPager) );
   44415 
   44416   /* An optimization. If the database was not actually modified during
   44417   ** this transaction, the pager is running in exclusive-mode and is
   44418   ** using persistent journals, then this function is a no-op.
   44419   **
   44420   ** The start of the journal file currently contains a single journal
   44421   ** header with the nRec field set to 0. If such a journal is used as
   44422   ** a hot-journal during hot-journal rollback, 0 changes will be made
   44423   ** to the database file. So there is no need to zero the journal
   44424   ** header. Since the pager is in exclusive mode, there is no need
   44425   ** to drop any locks either.
   44426   */
   44427   if( pPager->eState==PAGER_WRITER_LOCKED
   44428    && pPager->exclusiveMode
   44429    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   44430   ){
   44431     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   44432     pPager->eState = PAGER_READER;
   44433     return SQLITE_OK;
   44434   }
   44435 
   44436   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   44437   rc = pager_end_transaction(pPager, pPager->setMaster);
   44438   return pager_error(pPager, rc);
   44439 }
   44440 
   44441 /*
   44442 ** If a write transaction is open, then all changes made within the
   44443 ** transaction are reverted and the current write-transaction is closed.
   44444 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   44445 ** state if an error occurs.
   44446 **
   44447 ** If the pager is already in PAGER_ERROR state when this function is called,
   44448 ** it returns Pager.errCode immediately. No work is performed in this case.
   44449 **
   44450 ** Otherwise, in rollback mode, this function performs two functions:
   44451 **
   44452 **   1) It rolls back the journal file, restoring all database file and
   44453 **      in-memory cache pages to the state they were in when the transaction
   44454 **      was opened, and
   44455 **
   44456 **   2) It finalizes the journal file, so that it is not used for hot
   44457 **      rollback at any point in the future.
   44458 **
   44459 ** Finalization of the journal file (task 2) is only performed if the
   44460 ** rollback is successful.
   44461 **
   44462 ** In WAL mode, all cache-entries containing data modified within the
   44463 ** current transaction are either expelled from the cache or reverted to
   44464 ** their pre-transaction state by re-reading data from the database or
   44465 ** WAL files. The WAL transaction is then closed.
   44466 */
   44467 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   44468   int rc = SQLITE_OK;                  /* Return code */
   44469   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   44470 
   44471   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   44472   ** the pager is already in the ERROR state, the rollback is not
   44473   ** attempted here. Instead, the error code is returned to the caller.
   44474   */
   44475   assert( assert_pager_state(pPager) );
   44476   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   44477   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   44478 
   44479   if( pagerUseWal(pPager) ){
   44480     int rc2;
   44481     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   44482     rc2 = pager_end_transaction(pPager, pPager->setMaster);
   44483     if( rc==SQLITE_OK ) rc = rc2;
   44484   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   44485     int eState = pPager->eState;
   44486     rc = pager_end_transaction(pPager, 0);
   44487     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
   44488       /* This can happen using journal_mode=off. Move the pager to the error
   44489       ** state to indicate that the contents of the cache may not be trusted.
   44490       ** Any active readers will get SQLITE_ABORT.
   44491       */
   44492       pPager->errCode = SQLITE_ABORT;
   44493       pPager->eState = PAGER_ERROR;
   44494       return rc;
   44495     }
   44496   }else{
   44497     rc = pager_playback(pPager, 0);
   44498   }
   44499 
   44500   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   44501   assert( rc==SQLITE_OK || rc==SQLITE_FULL
   44502           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
   44503 
   44504   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   44505   ** cache. So call pager_error() on the way out to make any error persistent.
   44506   */
   44507   return pager_error(pPager, rc);
   44508 }
   44509 
   44510 /*
   44511 ** Return TRUE if the database file is opened read-only.  Return FALSE
   44512 ** if the database is (in theory) writable.
   44513 */
   44514 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   44515   return pPager->readOnly;
   44516 }
   44517 
   44518 /*
   44519 ** Return the number of references to the pager.
   44520 */
   44521 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   44522   return sqlite3PcacheRefCount(pPager->pPCache);
   44523 }
   44524 
   44525 /*
   44526 ** Return the approximate number of bytes of memory currently
   44527 ** used by the pager and its associated cache.
   44528 */
   44529 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   44530   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   44531                                      + 5*sizeof(void*);
   44532   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   44533            + sqlite3MallocSize(pPager)
   44534            + pPager->pageSize;
   44535 }
   44536 
   44537 /*
   44538 ** Return the number of references to the specified page.
   44539 */
   44540 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   44541   return sqlite3PcachePageRefcount(pPage);
   44542 }
   44543 
   44544 #ifdef SQLITE_TEST
   44545 /*
   44546 ** This routine is used for testing and analysis only.
   44547 */
   44548 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   44549   static int a[11];
   44550   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   44551   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   44552   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   44553   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   44554   a[4] = pPager->eState;
   44555   a[5] = pPager->errCode;
   44556   a[6] = pPager->nHit;
   44557   a[7] = pPager->nMiss;
   44558   a[8] = 0;  /* Used to be pPager->nOvfl */
   44559   a[9] = pPager->nRead;
   44560   a[10] = pPager->nWrite;
   44561   return a;
   44562 }
   44563 #endif
   44564 
   44565 /*
   44566 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
   44567 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
   44568 ** current cache hit or miss count, according to the value of eStat. If the
   44569 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
   44570 ** returning.
   44571 */
   44572 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
   44573   int *piStat;
   44574 
   44575   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
   44576        || eStat==SQLITE_DBSTATUS_CACHE_MISS
   44577   );
   44578   if( eStat==SQLITE_DBSTATUS_CACHE_HIT ){
   44579     piStat = &pPager->nHit;
   44580   }else{
   44581     piStat = &pPager->nMiss;
   44582   }
   44583 
   44584   *pnVal += *piStat;
   44585   if( reset ){
   44586     *piStat = 0;
   44587   }
   44588 }
   44589 
   44590 /*
   44591 ** Return true if this is an in-memory pager.
   44592 */
   44593 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   44594   return MEMDB;
   44595 }
   44596 
   44597 /*
   44598 ** Check that there are at least nSavepoint savepoints open. If there are
   44599 ** currently less than nSavepoints open, then open one or more savepoints
   44600 ** to make up the difference. If the number of savepoints is already
   44601 ** equal to nSavepoint, then this function is a no-op.
   44602 **
   44603 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   44604 ** occurs while opening the sub-journal file, then an IO error code is
   44605 ** returned. Otherwise, SQLITE_OK.
   44606 */
   44607 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   44608   int rc = SQLITE_OK;                       /* Return code */
   44609   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   44610 
   44611   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   44612   assert( assert_pager_state(pPager) );
   44613 
   44614   if( nSavepoint>nCurrent && pPager->useJournal ){
   44615     int ii;                                 /* Iterator variable */
   44616     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   44617 
   44618     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   44619     ** if the allocation fails. Otherwise, zero the new portion in case a
   44620     ** malloc failure occurs while populating it in the for(...) loop below.
   44621     */
   44622     aNew = (PagerSavepoint *)sqlite3Realloc(
   44623         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   44624     );
   44625     if( !aNew ){
   44626       return SQLITE_NOMEM;
   44627     }
   44628     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   44629     pPager->aSavepoint = aNew;
   44630 
   44631     /* Populate the PagerSavepoint structures just allocated. */
   44632     for(ii=nCurrent; ii<nSavepoint; ii++){
   44633       aNew[ii].nOrig = pPager->dbSize;
   44634       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   44635         aNew[ii].iOffset = pPager->journalOff;
   44636       }else{
   44637         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   44638       }
   44639       aNew[ii].iSubRec = pPager->nSubRec;
   44640       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   44641       if( !aNew[ii].pInSavepoint ){
   44642         return SQLITE_NOMEM;
   44643       }
   44644       if( pagerUseWal(pPager) ){
   44645         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   44646       }
   44647       pPager->nSavepoint = ii+1;
   44648     }
   44649     assert( pPager->nSavepoint==nSavepoint );
   44650     assertTruncateConstraint(pPager);
   44651   }
   44652 
   44653   return rc;
   44654 }
   44655 
   44656 /*
   44657 ** This function is called to rollback or release (commit) a savepoint.
   44658 ** The savepoint to release or rollback need not be the most recently
   44659 ** created savepoint.
   44660 **
   44661 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   44662 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   44663 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   44664 ** that have occurred since the specified savepoint was created.
   44665 **
   44666 ** The savepoint to rollback or release is identified by parameter
   44667 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   44668 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   44669 ** on the most recently created savepoint. If iSavepoint is greater than
   44670 ** (Pager.nSavepoint-1), then this function is a no-op.
   44671 **
   44672 ** If a negative value is passed to this function, then the current
   44673 ** transaction is rolled back. This is different to calling
   44674 ** sqlite3PagerRollback() because this function does not terminate
   44675 ** the transaction or unlock the database, it just restores the
   44676 ** contents of the database to its original state.
   44677 **
   44678 ** In any case, all savepoints with an index greater than iSavepoint
   44679 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   44680 ** then savepoint iSavepoint is also destroyed.
   44681 **
   44682 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   44683 ** or an IO error code if an IO error occurs while rolling back a
   44684 ** savepoint. If no errors occur, SQLITE_OK is returned.
   44685 */
   44686 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   44687   int rc = pPager->errCode;       /* Return code */
   44688 
   44689   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   44690   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   44691 
   44692   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   44693     int ii;            /* Iterator variable */
   44694     int nNew;          /* Number of remaining savepoints after this op. */
   44695 
   44696     /* Figure out how many savepoints will still be active after this
   44697     ** operation. Store this value in nNew. Then free resources associated
   44698     ** with any savepoints that are destroyed by this operation.
   44699     */
   44700     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   44701     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   44702       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   44703     }
   44704     pPager->nSavepoint = nNew;
   44705 
   44706     /* If this is a release of the outermost savepoint, truncate
   44707     ** the sub-journal to zero bytes in size. */
   44708     if( op==SAVEPOINT_RELEASE ){
   44709       if( nNew==0 && isOpen(pPager->sjfd) ){
   44710         /* Only truncate if it is an in-memory sub-journal. */
   44711         if( sqlite3IsMemJournal(pPager->sjfd) ){
   44712           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   44713           assert( rc==SQLITE_OK );
   44714         }
   44715         pPager->nSubRec = 0;
   44716       }
   44717     }
   44718     /* Else this is a rollback operation, playback the specified savepoint.
   44719     ** If this is a temp-file, it is possible that the journal file has
   44720     ** not yet been opened. In this case there have been no changes to
   44721     ** the database file, so the playback operation can be skipped.
   44722     */
   44723     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   44724       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   44725       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   44726       assert(rc!=SQLITE_DONE);
   44727     }
   44728   }
   44729 
   44730   return rc;
   44731 }
   44732 
   44733 /*
   44734 ** Return the full pathname of the database file.
   44735 */
   44736 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
   44737   return pPager->zFilename;
   44738 }
   44739 
   44740 /*
   44741 ** Return the VFS structure for the pager.
   44742 */
   44743 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   44744   return pPager->pVfs;
   44745 }
   44746 
   44747 /*
   44748 ** Return the file handle for the database file associated
   44749 ** with the pager.  This might return NULL if the file has
   44750 ** not yet been opened.
   44751 */
   44752 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   44753   return pPager->fd;
   44754 }
   44755 
   44756 /*
   44757 ** Return the full pathname of the journal file.
   44758 */
   44759 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   44760   return pPager->zJournal;
   44761 }
   44762 
   44763 /*
   44764 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   44765 ** if fsync()s are executed normally.
   44766 */
   44767 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   44768   return pPager->noSync;
   44769 }
   44770 
   44771 #ifdef SQLITE_HAS_CODEC
   44772 /*
   44773 ** Set or retrieve the codec for this pager
   44774 */
   44775 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   44776   Pager *pPager,
   44777   void *(*xCodec)(void*,void*,Pgno,int),
   44778   void (*xCodecSizeChng)(void*,int,int),
   44779   void (*xCodecFree)(void*),
   44780   void *pCodec
   44781 ){
   44782   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   44783   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   44784   pPager->xCodecSizeChng = xCodecSizeChng;
   44785   pPager->xCodecFree = xCodecFree;
   44786   pPager->pCodec = pCodec;
   44787   pagerReportSize(pPager);
   44788 }
   44789 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   44790   return pPager->pCodec;
   44791 }
   44792 #endif
   44793 
   44794 #ifndef SQLITE_OMIT_AUTOVACUUM
   44795 /*
   44796 ** Move the page pPg to location pgno in the file.
   44797 **
   44798 ** There must be no references to the page previously located at
   44799 ** pgno (which we call pPgOld) though that page is allowed to be
   44800 ** in cache.  If the page previously located at pgno is not already
   44801 ** in the rollback journal, it is not put there by by this routine.
   44802 **
   44803 ** References to the page pPg remain valid. Updating any
   44804 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   44805 ** allocated along with the page) is the responsibility of the caller.
   44806 **
   44807 ** A transaction must be active when this routine is called. It used to be
   44808 ** required that a statement transaction was not active, but this restriction
   44809 ** has been removed (CREATE INDEX needs to move a page when a statement
   44810 ** transaction is active).
   44811 **
   44812 ** If the fourth argument, isCommit, is non-zero, then this page is being
   44813 ** moved as part of a database reorganization just before the transaction
   44814 ** is being committed. In this case, it is guaranteed that the database page
   44815 ** pPg refers to will not be written to again within this transaction.
   44816 **
   44817 ** This function may return SQLITE_NOMEM or an IO error code if an error
   44818 ** occurs. Otherwise, it returns SQLITE_OK.
   44819 */
   44820 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   44821   PgHdr *pPgOld;               /* The page being overwritten. */
   44822   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   44823   int rc;                      /* Return code */
   44824   Pgno origPgno;               /* The original page number */
   44825 
   44826   assert( pPg->nRef>0 );
   44827   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44828        || pPager->eState==PAGER_WRITER_DBMOD
   44829   );
   44830   assert( assert_pager_state(pPager) );
   44831 
   44832   /* In order to be able to rollback, an in-memory database must journal
   44833   ** the page we are moving from.
   44834   */
   44835   if( MEMDB ){
   44836     rc = sqlite3PagerWrite(pPg);
   44837     if( rc ) return rc;
   44838   }
   44839 
   44840   /* If the page being moved is dirty and has not been saved by the latest
   44841   ** savepoint, then save the current contents of the page into the
   44842   ** sub-journal now. This is required to handle the following scenario:
   44843   **
   44844   **   BEGIN;
   44845   **     <journal page X, then modify it in memory>
   44846   **     SAVEPOINT one;
   44847   **       <Move page X to location Y>
   44848   **     ROLLBACK TO one;
   44849   **
   44850   ** If page X were not written to the sub-journal here, it would not
   44851   ** be possible to restore its contents when the "ROLLBACK TO one"
   44852   ** statement were is processed.
   44853   **
   44854   ** subjournalPage() may need to allocate space to store pPg->pgno into
   44855   ** one or more savepoint bitvecs. This is the reason this function
   44856   ** may return SQLITE_NOMEM.
   44857   */
   44858   if( pPg->flags&PGHDR_DIRTY
   44859    && subjRequiresPage(pPg)
   44860    && SQLITE_OK!=(rc = subjournalPage(pPg))
   44861   ){
   44862     return rc;
   44863   }
   44864 
   44865   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   44866       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   44867   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   44868 
   44869   /* If the journal needs to be sync()ed before page pPg->pgno can
   44870   ** be written to, store pPg->pgno in local variable needSyncPgno.
   44871   **
   44872   ** If the isCommit flag is set, there is no need to remember that
   44873   ** the journal needs to be sync()ed before database page pPg->pgno
   44874   ** can be written to. The caller has already promised not to write to it.
   44875   */
   44876   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   44877     needSyncPgno = pPg->pgno;
   44878     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
   44879     assert( pPg->flags&PGHDR_DIRTY );
   44880   }
   44881 
   44882   /* If the cache contains a page with page-number pgno, remove it
   44883   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   44884   ** page pgno before the 'move' operation, it needs to be retained
   44885   ** for the page moved there.
   44886   */
   44887   pPg->flags &= ~PGHDR_NEED_SYNC;
   44888   pPgOld = pager_lookup(pPager, pgno);
   44889   assert( !pPgOld || pPgOld->nRef==1 );
   44890   if( pPgOld ){
   44891     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   44892     if( MEMDB ){
   44893       /* Do not discard pages from an in-memory database since we might
   44894       ** need to rollback later.  Just move the page out of the way. */
   44895       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   44896     }else{
   44897       sqlite3PcacheDrop(pPgOld);
   44898     }
   44899   }
   44900 
   44901   origPgno = pPg->pgno;
   44902   sqlite3PcacheMove(pPg, pgno);
   44903   sqlite3PcacheMakeDirty(pPg);
   44904 
   44905   /* For an in-memory database, make sure the original page continues
   44906   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   44907   ** as the original page since it has already been allocated.
   44908   */
   44909   if( MEMDB ){
   44910     assert( pPgOld );
   44911     sqlite3PcacheMove(pPgOld, origPgno);
   44912     sqlite3PagerUnref(pPgOld);
   44913   }
   44914 
   44915   if( needSyncPgno ){
   44916     /* If needSyncPgno is non-zero, then the journal file needs to be
   44917     ** sync()ed before any data is written to database file page needSyncPgno.
   44918     ** Currently, no such page exists in the page-cache and the
   44919     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   44920     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   44921     ** flag.
   44922     **
   44923     ** If the attempt to load the page into the page-cache fails, (due
   44924     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   44925     ** array. Otherwise, if the page is loaded and written again in
   44926     ** this transaction, it may be written to the database file before
   44927     ** it is synced into the journal file. This way, it may end up in
   44928     ** the journal file twice, but that is not a problem.
   44929     */
   44930     PgHdr *pPgHdr;
   44931     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   44932     if( rc!=SQLITE_OK ){
   44933       if( needSyncPgno<=pPager->dbOrigSize ){
   44934         assert( pPager->pTmpSpace!=0 );
   44935         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   44936       }
   44937       return rc;
   44938     }
   44939     pPgHdr->flags |= PGHDR_NEED_SYNC;
   44940     sqlite3PcacheMakeDirty(pPgHdr);
   44941     sqlite3PagerUnref(pPgHdr);
   44942   }
   44943 
   44944   return SQLITE_OK;
   44945 }
   44946 #endif
   44947 
   44948 /*
   44949 ** Return a pointer to the data for the specified page.
   44950 */
   44951 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   44952   assert( pPg->nRef>0 || pPg->pPager->memDb );
   44953   return pPg->pData;
   44954 }
   44955 
   44956 /*
   44957 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   44958 ** allocated along with the specified page.
   44959 */
   44960 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   44961   return pPg->pExtra;
   44962 }
   44963 
   44964 /*
   44965 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   44966 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   44967 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   44968 ** the locking-mode is set to the value specified.
   44969 **
   44970 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   44971 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   44972 ** locking-mode.
   44973 */
   44974 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   44975   assert( eMode==PAGER_LOCKINGMODE_QUERY
   44976             || eMode==PAGER_LOCKINGMODE_NORMAL
   44977             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   44978   assert( PAGER_LOCKINGMODE_QUERY<0 );
   44979   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   44980   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   44981   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   44982     pPager->exclusiveMode = (u8)eMode;
   44983   }
   44984   return (int)pPager->exclusiveMode;
   44985 }
   44986 
   44987 /*
   44988 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   44989 **
   44990 **    PAGER_JOURNALMODE_DELETE
   44991 **    PAGER_JOURNALMODE_TRUNCATE
   44992 **    PAGER_JOURNALMODE_PERSIST
   44993 **    PAGER_JOURNALMODE_OFF
   44994 **    PAGER_JOURNALMODE_MEMORY
   44995 **    PAGER_JOURNALMODE_WAL
   44996 **
   44997 ** The journalmode is set to the value specified if the change is allowed.
   44998 ** The change may be disallowed for the following reasons:
   44999 **
   45000 **   *  An in-memory database can only have its journal_mode set to _OFF
   45001 **      or _MEMORY.
   45002 **
   45003 **   *  Temporary databases cannot have _WAL journalmode.
   45004 **
   45005 ** The returned indicate the current (possibly updated) journal-mode.
   45006 */
   45007 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   45008   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   45009 
   45010 #ifdef SQLITE_DEBUG
   45011   /* The print_pager_state() routine is intended to be used by the debugger
   45012   ** only.  We invoke it once here to suppress a compiler warning. */
   45013   print_pager_state(pPager);
   45014 #endif
   45015 
   45016 
   45017   /* The eMode parameter is always valid */
   45018   assert(      eMode==PAGER_JOURNALMODE_DELETE
   45019             || eMode==PAGER_JOURNALMODE_TRUNCATE
   45020             || eMode==PAGER_JOURNALMODE_PERSIST
   45021             || eMode==PAGER_JOURNALMODE_OFF
   45022             || eMode==PAGER_JOURNALMODE_WAL
   45023             || eMode==PAGER_JOURNALMODE_MEMORY );
   45024 
   45025   /* This routine is only called from the OP_JournalMode opcode, and
   45026   ** the logic there will never allow a temporary file to be changed
   45027   ** to WAL mode.
   45028   */
   45029   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   45030 
   45031   /* Do allow the journalmode of an in-memory database to be set to
   45032   ** anything other than MEMORY or OFF
   45033   */
   45034   if( MEMDB ){
   45035     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   45036     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   45037       eMode = eOld;
   45038     }
   45039   }
   45040 
   45041   if( eMode!=eOld ){
   45042 
   45043     /* Change the journal mode. */
   45044     assert( pPager->eState!=PAGER_ERROR );
   45045     pPager->journalMode = (u8)eMode;
   45046 
   45047     /* When transistioning from TRUNCATE or PERSIST to any other journal
   45048     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   45049     ** delete the journal file.
   45050     */
   45051     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   45052     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   45053     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   45054     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   45055     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   45056     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   45057 
   45058     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   45059     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   45060 
   45061       /* In this case we would like to delete the journal file. If it is
   45062       ** not possible, then that is not a problem. Deleting the journal file
   45063       ** here is an optimization only.
   45064       **
   45065       ** Before deleting the journal file, obtain a RESERVED lock on the
   45066       ** database file. This ensures that the journal file is not deleted
   45067       ** while it is in use by some other client.
   45068       */
   45069       sqlite3OsClose(pPager->jfd);
   45070       if( pPager->eLock>=RESERVED_LOCK ){
   45071         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   45072       }else{
   45073         int rc = SQLITE_OK;
   45074         int state = pPager->eState;
   45075         assert( state==PAGER_OPEN || state==PAGER_READER );
   45076         if( state==PAGER_OPEN ){
   45077           rc = sqlite3PagerSharedLock(pPager);
   45078         }
   45079         if( pPager->eState==PAGER_READER ){
   45080           assert( rc==SQLITE_OK );
   45081           rc = pagerLockDb(pPager, RESERVED_LOCK);
   45082         }
   45083         if( rc==SQLITE_OK ){
   45084           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   45085         }
   45086         if( rc==SQLITE_OK && state==PAGER_READER ){
   45087           pagerUnlockDb(pPager, SHARED_LOCK);
   45088         }else if( state==PAGER_OPEN ){
   45089           pager_unlock(pPager);
   45090         }
   45091         assert( state==pPager->eState );
   45092       }
   45093     }
   45094   }
   45095 
   45096   /* Return the new journal mode */
   45097   return (int)pPager->journalMode;
   45098 }
   45099 
   45100 /*
   45101 ** Return the current journal mode.
   45102 */
   45103 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   45104   return (int)pPager->journalMode;
   45105 }
   45106 
   45107 /*
   45108 ** Return TRUE if the pager is in a state where it is OK to change the
   45109 ** journalmode.  Journalmode changes can only happen when the database
   45110 ** is unmodified.
   45111 */
   45112 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   45113   assert( assert_pager_state(pPager) );
   45114   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   45115   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   45116   return 1;
   45117 }
   45118 
   45119 /*
   45120 ** Get/set the size-limit used for persistent journal files.
   45121 **
   45122 ** Setting the size limit to -1 means no limit is enforced.
   45123 ** An attempt to set a limit smaller than -1 is a no-op.
   45124 */
   45125 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   45126   if( iLimit>=-1 ){
   45127     pPager->journalSizeLimit = iLimit;
   45128     sqlite3WalLimit(pPager->pWal, iLimit);
   45129   }
   45130   return pPager->journalSizeLimit;
   45131 }
   45132 
   45133 /*
   45134 ** Return a pointer to the pPager->pBackup variable. The backup module
   45135 ** in backup.c maintains the content of this variable. This module
   45136 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   45137 ** sqlite3BackupUpdate() only.
   45138 */
   45139 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   45140   return &pPager->pBackup;
   45141 }
   45142 
   45143 #ifndef SQLITE_OMIT_VACUUM
   45144 /*
   45145 ** Unless this is an in-memory or temporary database, clear the pager cache.
   45146 */
   45147 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
   45148   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
   45149 }
   45150 #endif
   45151 
   45152 #ifndef SQLITE_OMIT_WAL
   45153 /*
   45154 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
   45155 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
   45156 ** or wal_blocking_checkpoint() API functions.
   45157 **
   45158 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   45159 */
   45160 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
   45161   int rc = SQLITE_OK;
   45162   if( pPager->pWal ){
   45163     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
   45164         pPager->xBusyHandler, pPager->pBusyHandlerArg,
   45165         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
   45166         pnLog, pnCkpt
   45167     );
   45168   }
   45169   return rc;
   45170 }
   45171 
   45172 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   45173   return sqlite3WalCallback(pPager->pWal);
   45174 }
   45175 
   45176 /*
   45177 ** Return true if the underlying VFS for the given pager supports the
   45178 ** primitives necessary for write-ahead logging.
   45179 */
   45180 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   45181   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   45182   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   45183 }
   45184 
   45185 /*
   45186 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   45187 ** is obtained instead, immediately release it.
   45188 */
   45189 static int pagerExclusiveLock(Pager *pPager){
   45190   int rc;                         /* Return code */
   45191 
   45192   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   45193   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45194   if( rc!=SQLITE_OK ){
   45195     /* If the attempt to grab the exclusive lock failed, release the
   45196     ** pending lock that may have been obtained instead.  */
   45197     pagerUnlockDb(pPager, SHARED_LOCK);
   45198   }
   45199 
   45200   return rc;
   45201 }
   45202 
   45203 /*
   45204 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   45205 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   45206 ** lock on the database file and use heap-memory to store the wal-index
   45207 ** in. Otherwise, use the normal shared-memory.
   45208 */
   45209 static int pagerOpenWal(Pager *pPager){
   45210   int rc = SQLITE_OK;
   45211 
   45212   assert( pPager->pWal==0 && pPager->tempFile==0 );
   45213   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   45214 
   45215   /* If the pager is already in exclusive-mode, the WAL module will use
   45216   ** heap-memory for the wal-index instead of the VFS shared-memory
   45217   ** implementation. Take the exclusive lock now, before opening the WAL
   45218   ** file, to make sure this is safe.
   45219   */
   45220   if( pPager->exclusiveMode ){
   45221     rc = pagerExclusiveLock(pPager);
   45222   }
   45223 
   45224   /* Open the connection to the log file. If this operation fails,
   45225   ** (e.g. due to malloc() failure), return an error code.
   45226   */
   45227   if( rc==SQLITE_OK ){
   45228     rc = sqlite3WalOpen(pPager->pVfs,
   45229         pPager->fd, pPager->zWal, pPager->exclusiveMode,
   45230         pPager->journalSizeLimit, &pPager->pWal
   45231     );
   45232   }
   45233 
   45234   return rc;
   45235 }
   45236 
   45237 
   45238 /*
   45239 ** The caller must be holding a SHARED lock on the database file to call
   45240 ** this function.
   45241 **
   45242 ** If the pager passed as the first argument is open on a real database
   45243 ** file (not a temp file or an in-memory database), and the WAL file
   45244 ** is not already open, make an attempt to open it now. If successful,
   45245 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   45246 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   45247 ** not modified in either case.
   45248 **
   45249 ** If the pager is open on a temp-file (or in-memory database), or if
   45250 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   45251 ** without doing anything.
   45252 */
   45253 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   45254   Pager *pPager,                  /* Pager object */
   45255   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   45256 ){
   45257   int rc = SQLITE_OK;             /* Return code */
   45258 
   45259   assert( assert_pager_state(pPager) );
   45260   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   45261   assert( pPager->eState==PAGER_READER || !pbOpen );
   45262   assert( pbOpen==0 || *pbOpen==0 );
   45263   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   45264 
   45265   if( !pPager->tempFile && !pPager->pWal ){
   45266     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   45267 
   45268     /* Close any rollback journal previously open */
   45269     sqlite3OsClose(pPager->jfd);
   45270 
   45271     rc = pagerOpenWal(pPager);
   45272     if( rc==SQLITE_OK ){
   45273       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   45274       pPager->eState = PAGER_OPEN;
   45275     }
   45276   }else{
   45277     *pbOpen = 1;
   45278   }
   45279 
   45280   return rc;
   45281 }
   45282 
   45283 /*
   45284 ** This function is called to close the connection to the log file prior
   45285 ** to switching from WAL to rollback mode.
   45286 **
   45287 ** Before closing the log file, this function attempts to take an
   45288 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   45289 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   45290 ** If successful, the EXCLUSIVE lock is not released before returning.
   45291 */
   45292 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
   45293   int rc = SQLITE_OK;
   45294 
   45295   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   45296 
   45297   /* If the log file is not already open, but does exist in the file-system,
   45298   ** it may need to be checkpointed before the connection can switch to
   45299   ** rollback mode. Open it now so this can happen.
   45300   */
   45301   if( !pPager->pWal ){
   45302     int logexists = 0;
   45303     rc = pagerLockDb(pPager, SHARED_LOCK);
   45304     if( rc==SQLITE_OK ){
   45305       rc = sqlite3OsAccess(
   45306           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   45307       );
   45308     }
   45309     if( rc==SQLITE_OK && logexists ){
   45310       rc = pagerOpenWal(pPager);
   45311     }
   45312   }
   45313 
   45314   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   45315   ** the database file, the log and log-summary files will be deleted.
   45316   */
   45317   if( rc==SQLITE_OK && pPager->pWal ){
   45318     rc = pagerExclusiveLock(pPager);
   45319     if( rc==SQLITE_OK ){
   45320       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
   45321                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   45322       pPager->pWal = 0;
   45323     }
   45324   }
   45325   return rc;
   45326 }
   45327 
   45328 #ifdef SQLITE_ENABLE_ZIPVFS
   45329 /*
   45330 ** A read-lock must be held on the pager when this function is called. If
   45331 ** the pager is in WAL mode and the WAL file currently contains one or more
   45332 ** frames, return the size in bytes of the page images stored within the
   45333 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
   45334 ** is empty, return 0.
   45335 */
   45336 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
   45337   assert( pPager->eState==PAGER_READER );
   45338   return sqlite3WalFramesize(pPager->pWal);
   45339 }
   45340 #endif
   45341 
   45342 #ifdef SQLITE_HAS_CODEC
   45343 /*
   45344 ** This function is called by the wal module when writing page content
   45345 ** into the log file.
   45346 **
   45347 ** This function returns a pointer to a buffer containing the encrypted
   45348 ** page content. If a malloc fails, this function may return NULL.
   45349 */
   45350 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   45351   void *aData = 0;
   45352   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   45353   return aData;
   45354 }
   45355 #endif /* SQLITE_HAS_CODEC */
   45356 
   45357 #endif /* !SQLITE_OMIT_WAL */
   45358 
   45359 #endif /* SQLITE_OMIT_DISKIO */
   45360 
   45361 /************** End of pager.c ***********************************************/
   45362 /************** Begin file wal.c *********************************************/
   45363 /*
   45364 ** 2010 February 1
   45365 **
   45366 ** The author disclaims copyright to this source code.  In place of
   45367 ** a legal notice, here is a blessing:
   45368 **
   45369 **    May you do good and not evil.
   45370 **    May you find forgiveness for yourself and forgive others.
   45371 **    May you share freely, never taking more than you give.
   45372 **
   45373 *************************************************************************
   45374 **
   45375 ** This file contains the implementation of a write-ahead log (WAL) used in
   45376 ** "journal_mode=WAL" mode.
   45377 **
   45378 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   45379 **
   45380 ** A WAL file consists of a header followed by zero or more "frames".
   45381 ** Each frame records the revised content of a single page from the
   45382 ** database file.  All changes to the database are recorded by writing
   45383 ** frames into the WAL.  Transactions commit when a frame is written that
   45384 ** contains a commit marker.  A single WAL can and usually does record
   45385 ** multiple transactions.  Periodically, the content of the WAL is
   45386 ** transferred back into the database file in an operation called a
   45387 ** "checkpoint".
   45388 **
   45389 ** A single WAL file can be used multiple times.  In other words, the
   45390 ** WAL can fill up with frames and then be checkpointed and then new
   45391 ** frames can overwrite the old ones.  A WAL always grows from beginning
   45392 ** toward the end.  Checksums and counters attached to each frame are
   45393 ** used to determine which frames within the WAL are valid and which
   45394 ** are leftovers from prior checkpoints.
   45395 **
   45396 ** The WAL header is 32 bytes in size and consists of the following eight
   45397 ** big-endian 32-bit unsigned integer values:
   45398 **
   45399 **     0: Magic number.  0x377f0682 or 0x377f0683
   45400 **     4: File format version.  Currently 3007000
   45401 **     8: Database page size.  Example: 1024
   45402 **    12: Checkpoint sequence number
   45403 **    16: Salt-1, random integer incremented with each checkpoint
   45404 **    20: Salt-2, a different random integer changing with each ckpt
   45405 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   45406 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   45407 **
   45408 ** Immediately following the wal-header are zero or more frames. Each
   45409 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   45410 ** of page data. The frame-header is six big-endian 32-bit unsigned
   45411 ** integer values, as follows:
   45412 **
   45413 **     0: Page number.
   45414 **     4: For commit records, the size of the database image in pages
   45415 **        after the commit. For all other records, zero.
   45416 **     8: Salt-1 (copied from the header)
   45417 **    12: Salt-2 (copied from the header)
   45418 **    16: Checksum-1.
   45419 **    20: Checksum-2.
   45420 **
   45421 ** A frame is considered valid if and only if the following conditions are
   45422 ** true:
   45423 **
   45424 **    (1) The salt-1 and salt-2 values in the frame-header match
   45425 **        salt values in the wal-header
   45426 **
   45427 **    (2) The checksum values in the final 8 bytes of the frame-header
   45428 **        exactly match the checksum computed consecutively on the
   45429 **        WAL header and the first 8 bytes and the content of all frames
   45430 **        up to and including the current frame.
   45431 **
   45432 ** The checksum is computed using 32-bit big-endian integers if the
   45433 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   45434 ** is computed using little-endian if the magic number is 0x377f0682.
   45435 ** The checksum values are always stored in the frame header in a
   45436 ** big-endian format regardless of which byte order is used to compute
   45437 ** the checksum.  The checksum is computed by interpreting the input as
   45438 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   45439 ** algorithm used for the checksum is as follows:
   45440 **
   45441 **   for i from 0 to n-1 step 2:
   45442 **     s0 += x[i] + s1;
   45443 **     s1 += x[i+1] + s0;
   45444 **   endfor
   45445 **
   45446 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   45447 ** in reverse order (the largest fibonacci weight occurs on the first element
   45448 ** of the sequence being summed.)  The s1 value spans all 32-bit
   45449 ** terms of the sequence whereas s0 omits the final term.
   45450 **
   45451 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   45452 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   45453 ** The VFS.xSync operations serve as write barriers - all writes launched
   45454 ** before the xSync must complete before any write that launches after the
   45455 ** xSync begins.
   45456 **
   45457 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   45458 ** value is randomized.  This prevents old and new frames in the WAL from
   45459 ** being considered valid at the same time and being checkpointing together
   45460 ** following a crash.
   45461 **
   45462 ** READER ALGORITHM
   45463 **
   45464 ** To read a page from the database (call it page number P), a reader
   45465 ** first checks the WAL to see if it contains page P.  If so, then the
   45466 ** last valid instance of page P that is a followed by a commit frame
   45467 ** or is a commit frame itself becomes the value read.  If the WAL
   45468 ** contains no copies of page P that are valid and which are a commit
   45469 ** frame or are followed by a commit frame, then page P is read from
   45470 ** the database file.
   45471 **
   45472 ** To start a read transaction, the reader records the index of the last
   45473 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   45474 ** for all subsequent read operations.  New transactions can be appended
   45475 ** to the WAL, but as long as the reader uses its original mxFrame value
   45476 ** and ignores the newly appended content, it will see a consistent snapshot
   45477 ** of the database from a single point in time.  This technique allows
   45478 ** multiple concurrent readers to view different versions of the database
   45479 ** content simultaneously.
   45480 **
   45481 ** The reader algorithm in the previous paragraphs works correctly, but
   45482 ** because frames for page P can appear anywhere within the WAL, the
   45483 ** reader has to scan the entire WAL looking for page P frames.  If the
   45484 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   45485 ** and read performance suffers.  To overcome this problem, a separate
   45486 ** data structure called the wal-index is maintained to expedite the
   45487 ** search for frames of a particular page.
   45488 **
   45489 ** WAL-INDEX FORMAT
   45490 **
   45491 ** Conceptually, the wal-index is shared memory, though VFS implementations
   45492 ** might choose to implement the wal-index using a mmapped file.  Because
   45493 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   45494 ** on a network filesystem.  All users of the database must be able to
   45495 ** share memory.
   45496 **
   45497 ** The wal-index is transient.  After a crash, the wal-index can (and should
   45498 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   45499 ** to either truncate or zero the header of the wal-index when the last
   45500 ** connection to it closes.  Because the wal-index is transient, it can
   45501 ** use an architecture-specific format; it does not have to be cross-platform.
   45502 ** Hence, unlike the database and WAL file formats which store all values
   45503 ** as big endian, the wal-index can store multi-byte values in the native
   45504 ** byte order of the host computer.
   45505 **
   45506 ** The purpose of the wal-index is to answer this question quickly:  Given
   45507 ** a page number P, return the index of the last frame for page P in the WAL,
   45508 ** or return NULL if there are no frames for page P in the WAL.
   45509 **
   45510 ** The wal-index consists of a header region, followed by an one or
   45511 ** more index blocks.
   45512 **
   45513 ** The wal-index header contains the total number of frames within the WAL
   45514 ** in the the mxFrame field.
   45515 **
   45516 ** Each index block except for the first contains information on
   45517 ** HASHTABLE_NPAGE frames. The first index block contains information on
   45518 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   45519 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   45520 ** first index block are the same size as all other index blocks in the
   45521 ** wal-index.
   45522 **
   45523 ** Each index block contains two sections, a page-mapping that contains the
   45524 ** database page number associated with each wal frame, and a hash-table
   45525 ** that allows readers to query an index block for a specific page number.
   45526 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   45527 ** for the first index block) 32-bit page numbers. The first entry in the
   45528 ** first index-block contains the database page number corresponding to the
   45529 ** first frame in the WAL file. The first entry in the second index block
   45530 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   45531 ** the log, and so on.
   45532 **
   45533 ** The last index block in a wal-index usually contains less than the full
   45534 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   45535 ** depending on the contents of the WAL file. This does not change the
   45536 ** allocated size of the page-mapping array - the page-mapping array merely
   45537 ** contains unused entries.
   45538 **
   45539 ** Even without using the hash table, the last frame for page P
   45540 ** can be found by scanning the page-mapping sections of each index block
   45541 ** starting with the last index block and moving toward the first, and
   45542 ** within each index block, starting at the end and moving toward the
   45543 ** beginning.  The first entry that equals P corresponds to the frame
   45544 ** holding the content for that page.
   45545 **
   45546 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   45547 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   45548 ** hash table for each page number in the mapping section, so the hash
   45549 ** table is never more than half full.  The expected number of collisions
   45550 ** prior to finding a match is 1.  Each entry of the hash table is an
   45551 ** 1-based index of an entry in the mapping section of the same
   45552 ** index block.   Let K be the 1-based index of the largest entry in
   45553 ** the mapping section.  (For index blocks other than the last, K will
   45554 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   45555 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   45556 ** contain a value of 0.
   45557 **
   45558 ** To look for page P in the hash table, first compute a hash iKey on
   45559 ** P as follows:
   45560 **
   45561 **      iKey = (P * 383) % HASHTABLE_NSLOT
   45562 **
   45563 ** Then start scanning entries of the hash table, starting with iKey
   45564 ** (wrapping around to the beginning when the end of the hash table is
   45565 ** reached) until an unused hash slot is found. Let the first unused slot
   45566 ** be at index iUnused.  (iUnused might be less than iKey if there was
   45567 ** wrap-around.) Because the hash table is never more than half full,
   45568 ** the search is guaranteed to eventually hit an unused entry.  Let
   45569 ** iMax be the value between iKey and iUnused, closest to iUnused,
   45570 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   45571 ** no hash slot such that aHash[i]==p) then page P is not in the
   45572 ** current index block.  Otherwise the iMax-th mapping entry of the
   45573 ** current index block corresponds to the last entry that references
   45574 ** page P.
   45575 **
   45576 ** A hash search begins with the last index block and moves toward the
   45577 ** first index block, looking for entries corresponding to page P.  On
   45578 ** average, only two or three slots in each index block need to be
   45579 ** examined in order to either find the last entry for page P, or to
   45580 ** establish that no such entry exists in the block.  Each index block
   45581 ** holds over 4000 entries.  So two or three index blocks are sufficient
   45582 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   45583 ** comparisons (on average) suffice to either locate a frame in the
   45584 ** WAL or to establish that the frame does not exist in the WAL.  This
   45585 ** is much faster than scanning the entire 10MB WAL.
   45586 **
   45587 ** Note that entries are added in order of increasing K.  Hence, one
   45588 ** reader might be using some value K0 and a second reader that started
   45589 ** at a later time (after additional transactions were added to the WAL
   45590 ** and to the wal-index) might be using a different value K1, where K1>K0.
   45591 ** Both readers can use the same hash table and mapping section to get
   45592 ** the correct result.  There may be entries in the hash table with
   45593 ** K>K0 but to the first reader, those entries will appear to be unused
   45594 ** slots in the hash table and so the first reader will get an answer as
   45595 ** if no values greater than K0 had ever been inserted into the hash table
   45596 ** in the first place - which is what reader one wants.  Meanwhile, the
   45597 ** second reader using K1 will see additional values that were inserted
   45598 ** later, which is exactly what reader two wants.
   45599 **
   45600 ** When a rollback occurs, the value of K is decreased. Hash table entries
   45601 ** that correspond to frames greater than the new K value are removed
   45602 ** from the hash table at this point.
   45603 */
   45604 #ifndef SQLITE_OMIT_WAL
   45605 
   45606 
   45607 /*
   45608 ** Trace output macros
   45609 */
   45610 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   45611 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   45612 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   45613 #else
   45614 # define WALTRACE(X)
   45615 #endif
   45616 
   45617 /*
   45618 ** The maximum (and only) versions of the wal and wal-index formats
   45619 ** that may be interpreted by this version of SQLite.
   45620 **
   45621 ** If a client begins recovering a WAL file and finds that (a) the checksum
   45622 ** values in the wal-header are correct and (b) the version field is not
   45623 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   45624 **
   45625 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   45626 ** checksum test is successful) and finds that the version field is not
   45627 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   45628 ** returns SQLITE_CANTOPEN.
   45629 */
   45630 #define WAL_MAX_VERSION      3007000
   45631 #define WALINDEX_MAX_VERSION 3007000
   45632 
   45633 /*
   45634 ** Indices of various locking bytes.   WAL_NREADER is the number
   45635 ** of available reader locks and should be at least 3.
   45636 */
   45637 #define WAL_WRITE_LOCK         0
   45638 #define WAL_ALL_BUT_WRITE      1
   45639 #define WAL_CKPT_LOCK          1
   45640 #define WAL_RECOVER_LOCK       2
   45641 #define WAL_READ_LOCK(I)       (3+(I))
   45642 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   45643 
   45644 
   45645 /* Object declarations */
   45646 typedef struct WalIndexHdr WalIndexHdr;
   45647 typedef struct WalIterator WalIterator;
   45648 typedef struct WalCkptInfo WalCkptInfo;
   45649 
   45650 
   45651 /*
   45652 ** The following object holds a copy of the wal-index header content.
   45653 **
   45654 ** The actual header in the wal-index consists of two copies of this
   45655 ** object.
   45656 **
   45657 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   45658 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   45659 ** added in 3.7.1 when support for 64K pages was added.
   45660 */
   45661 struct WalIndexHdr {
   45662   u32 iVersion;                   /* Wal-index version */
   45663   u32 unused;                     /* Unused (padding) field */
   45664   u32 iChange;                    /* Counter incremented each transaction */
   45665   u8 isInit;                      /* 1 when initialized */
   45666   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   45667   u16 szPage;                     /* Database page size in bytes. 1==64K */
   45668   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   45669   u32 nPage;                      /* Size of database in pages */
   45670   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   45671   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   45672   u32 aCksum[2];                  /* Checksum over all prior fields */
   45673 };
   45674 
   45675 /*
   45676 ** A copy of the following object occurs in the wal-index immediately
   45677 ** following the second copy of the WalIndexHdr.  This object stores
   45678 ** information used by checkpoint.
   45679 **
   45680 ** nBackfill is the number of frames in the WAL that have been written
   45681 ** back into the database. (We call the act of moving content from WAL to
   45682 ** database "backfilling".)  The nBackfill number is never greater than
   45683 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   45684 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   45685 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   45686 ** mxFrame back to zero when the WAL is reset.
   45687 **
   45688 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   45689 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   45690 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   45691 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   45692 ** a special case; its value is never used and it exists as a place-holder
   45693 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   45694 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   45695 ** directly from the database.
   45696 **
   45697 ** The value of aReadMark[K] may only be changed by a thread that
   45698 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   45699 ** aReadMark[K] cannot changed while there is a reader is using that mark
   45700 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   45701 **
   45702 ** The checkpointer may only transfer frames from WAL to database where
   45703 ** the frame numbers are less than or equal to every aReadMark[] that is
   45704 ** in use (that is, every aReadMark[j] for which there is a corresponding
   45705 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   45706 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   45707 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   45708 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   45709 ** in the WAL has been backfilled into the database) then new readers
   45710 ** will choose aReadMark[0] which has value 0 and hence such reader will
   45711 ** get all their all content directly from the database file and ignore
   45712 ** the WAL.
   45713 **
   45714 ** Writers normally append new frames to the end of the WAL.  However,
   45715 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   45716 ** written back into the database) and if no readers are using the WAL
   45717 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   45718 ** the writer will first "reset" the WAL back to the beginning and start
   45719 ** writing new content beginning at frame 1.
   45720 **
   45721 ** We assume that 32-bit loads are atomic and so no locks are needed in
   45722 ** order to read from any aReadMark[] entries.
   45723 */
   45724 struct WalCkptInfo {
   45725   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   45726   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   45727 };
   45728 #define READMARK_NOT_USED  0xffffffff
   45729 
   45730 
   45731 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   45732 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   45733 ** only support mandatory file-locks, we do not read or write data
   45734 ** from the region of the file on which locks are applied.
   45735 */
   45736 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
   45737 #define WALINDEX_LOCK_RESERVED 16
   45738 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
   45739 
   45740 /* Size of header before each frame in wal */
   45741 #define WAL_FRAME_HDRSIZE 24
   45742 
   45743 /* Size of write ahead log header, including checksum. */
   45744 /* #define WAL_HDRSIZE 24 */
   45745 #define WAL_HDRSIZE 32
   45746 
   45747 /* WAL magic value. Either this value, or the same value with the least
   45748 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   45749 ** big-endian format in the first 4 bytes of a WAL file.
   45750 **
   45751 ** If the LSB is set, then the checksums for each frame within the WAL
   45752 ** file are calculated by treating all data as an array of 32-bit
   45753 ** big-endian words. Otherwise, they are calculated by interpreting
   45754 ** all data as 32-bit little-endian words.
   45755 */
   45756 #define WAL_MAGIC 0x377f0682
   45757 
   45758 /*
   45759 ** Return the offset of frame iFrame in the write-ahead log file,
   45760 ** assuming a database page size of szPage bytes. The offset returned
   45761 ** is to the start of the write-ahead log frame-header.
   45762 */
   45763 #define walFrameOffset(iFrame, szPage) (                               \
   45764   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   45765 )
   45766 
   45767 /*
   45768 ** An open write-ahead log file is represented by an instance of the
   45769 ** following object.
   45770 */
   45771 struct Wal {
   45772   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   45773   sqlite3_file *pDbFd;       /* File handle for the database file */
   45774   sqlite3_file *pWalFd;      /* File handle for WAL file */
   45775   u32 iCallback;             /* Value to pass to log callback (or 0) */
   45776   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
   45777   int nWiData;               /* Size of array apWiData */
   45778   int szFirstBlock;          /* Size of first block written to WAL file */
   45779   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   45780   u32 szPage;                /* Database page size */
   45781   i16 readLock;              /* Which read lock is being held.  -1 for none */
   45782   u8 syncFlags;              /* Flags to use to sync header writes */
   45783   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   45784   u8 writeLock;              /* True if in a write transaction */
   45785   u8 ckptLock;               /* True if holding a checkpoint lock */
   45786   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
   45787   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
   45788   u8 syncHeader;             /* Fsync the WAL header if true */
   45789   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
   45790   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   45791   const char *zWalName;      /* Name of WAL file */
   45792   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   45793 #ifdef SQLITE_DEBUG
   45794   u8 lockError;              /* True if a locking error has occurred */
   45795 #endif
   45796 };
   45797 
   45798 /*
   45799 ** Candidate values for Wal.exclusiveMode.
   45800 */
   45801 #define WAL_NORMAL_MODE     0
   45802 #define WAL_EXCLUSIVE_MODE  1
   45803 #define WAL_HEAPMEMORY_MODE 2
   45804 
   45805 /*
   45806 ** Possible values for WAL.readOnly
   45807 */
   45808 #define WAL_RDWR        0    /* Normal read/write connection */
   45809 #define WAL_RDONLY      1    /* The WAL file is readonly */
   45810 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
   45811 
   45812 /*
   45813 ** Each page of the wal-index mapping contains a hash-table made up of
   45814 ** an array of HASHTABLE_NSLOT elements of the following type.
   45815 */
   45816 typedef u16 ht_slot;
   45817 
   45818 /*
   45819 ** This structure is used to implement an iterator that loops through
   45820 ** all frames in the WAL in database page order. Where two or more frames
   45821 ** correspond to the same database page, the iterator visits only the
   45822 ** frame most recently written to the WAL (in other words, the frame with
   45823 ** the largest index).
   45824 **
   45825 ** The internals of this structure are only accessed by:
   45826 **
   45827 **   walIteratorInit() - Create a new iterator,
   45828 **   walIteratorNext() - Step an iterator,
   45829 **   walIteratorFree() - Free an iterator.
   45830 **
   45831 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   45832 */
   45833 struct WalIterator {
   45834   int iPrior;                     /* Last result returned from the iterator */
   45835   int nSegment;                   /* Number of entries in aSegment[] */
   45836   struct WalSegment {
   45837     int iNext;                    /* Next slot in aIndex[] not yet returned */
   45838     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   45839     u32 *aPgno;                   /* Array of page numbers. */
   45840     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
   45841     int iZero;                    /* Frame number associated with aPgno[0] */
   45842   } aSegment[1];                  /* One for every 32KB page in the wal-index */
   45843 };
   45844 
   45845 /*
   45846 ** Define the parameters of the hash tables in the wal-index file. There
   45847 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   45848 ** wal-index.
   45849 **
   45850 ** Changing any of these constants will alter the wal-index format and
   45851 ** create incompatibilities.
   45852 */
   45853 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   45854 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   45855 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   45856 
   45857 /*
   45858 ** The block of page numbers associated with the first hash-table in a
   45859 ** wal-index is smaller than usual. This is so that there is a complete
   45860 ** hash-table on each aligned 32KB page of the wal-index.
   45861 */
   45862 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   45863 
   45864 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   45865 #define WALINDEX_PGSZ   (                                         \
   45866     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   45867 )
   45868 
   45869 /*
   45870 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   45871 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   45872 ** numbered from zero.
   45873 **
   45874 ** If this call is successful, *ppPage is set to point to the wal-index
   45875 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   45876 ** then an SQLite error code is returned and *ppPage is set to 0.
   45877 */
   45878 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   45879   int rc = SQLITE_OK;
   45880 
   45881   /* Enlarge the pWal->apWiData[] array if required */
   45882   if( pWal->nWiData<=iPage ){
   45883     int nByte = sizeof(u32*)*(iPage+1);
   45884     volatile u32 **apNew;
   45885     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
   45886     if( !apNew ){
   45887       *ppPage = 0;
   45888       return SQLITE_NOMEM;
   45889     }
   45890     memset((void*)&apNew[pWal->nWiData], 0,
   45891            sizeof(u32*)*(iPage+1-pWal->nWiData));
   45892     pWal->apWiData = apNew;
   45893     pWal->nWiData = iPage+1;
   45894   }
   45895 
   45896   /* Request a pointer to the required page from the VFS */
   45897   if( pWal->apWiData[iPage]==0 ){
   45898     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   45899       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   45900       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
   45901     }else{
   45902       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   45903           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   45904       );
   45905       if( rc==SQLITE_READONLY ){
   45906         pWal->readOnly |= WAL_SHM_RDONLY;
   45907         rc = SQLITE_OK;
   45908       }
   45909     }
   45910   }
   45911 
   45912   *ppPage = pWal->apWiData[iPage];
   45913   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   45914   return rc;
   45915 }
   45916 
   45917 /*
   45918 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   45919 */
   45920 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   45921   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   45922   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   45923 }
   45924 
   45925 /*
   45926 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   45927 */
   45928 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   45929   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   45930   return (volatile WalIndexHdr*)pWal->apWiData[0];
   45931 }
   45932 
   45933 /*
   45934 ** The argument to this macro must be of type u32. On a little-endian
   45935 ** architecture, it returns the u32 value that results from interpreting
   45936 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   45937 ** returns the value that would be produced by intepreting the 4 bytes
   45938 ** of the input value as a little-endian integer.
   45939 */
   45940 #define BYTESWAP32(x) ( \
   45941     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   45942   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   45943 )
   45944 
   45945 /*
   45946 ** Generate or extend an 8 byte checksum based on the data in
   45947 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   45948 ** initial values of 0 and 0 if aIn==NULL).
   45949 **
   45950 ** The checksum is written back into aOut[] before returning.
   45951 **
   45952 ** nByte must be a positive multiple of 8.
   45953 */
   45954 static void walChecksumBytes(
   45955   int nativeCksum, /* True for native byte-order, false for non-native */
   45956   u8 *a,           /* Content to be checksummed */
   45957   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   45958   const u32 *aIn,  /* Initial checksum value input */
   45959   u32 *aOut        /* OUT: Final checksum value output */
   45960 ){
   45961   u32 s1, s2;
   45962   u32 *aData = (u32 *)a;
   45963   u32 *aEnd = (u32 *)&a[nByte];
   45964 
   45965   if( aIn ){
   45966     s1 = aIn[0];
   45967     s2 = aIn[1];
   45968   }else{
   45969     s1 = s2 = 0;
   45970   }
   45971 
   45972   assert( nByte>=8 );
   45973   assert( (nByte&0x00000007)==0 );
   45974 
   45975   if( nativeCksum ){
   45976     do {
   45977       s1 += *aData++ + s2;
   45978       s2 += *aData++ + s1;
   45979     }while( aData<aEnd );
   45980   }else{
   45981     do {
   45982       s1 += BYTESWAP32(aData[0]) + s2;
   45983       s2 += BYTESWAP32(aData[1]) + s1;
   45984       aData += 2;
   45985     }while( aData<aEnd );
   45986   }
   45987 
   45988   aOut[0] = s1;
   45989   aOut[1] = s2;
   45990 }
   45991 
   45992 static void walShmBarrier(Wal *pWal){
   45993   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   45994     sqlite3OsShmBarrier(pWal->pDbFd);
   45995   }
   45996 }
   45997 
   45998 /*
   45999 ** Write the header information in pWal->hdr into the wal-index.
   46000 **
   46001 ** The checksum on pWal->hdr is updated before it is written.
   46002 */
   46003 static void walIndexWriteHdr(Wal *pWal){
   46004   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   46005   const int nCksum = offsetof(WalIndexHdr, aCksum);
   46006 
   46007   assert( pWal->writeLock );
   46008   pWal->hdr.isInit = 1;
   46009   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   46010   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   46011   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   46012   walShmBarrier(pWal);
   46013   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   46014 }
   46015 
   46016 /*
   46017 ** This function encodes a single frame header and writes it to a buffer
   46018 ** supplied by the caller. A frame-header is made up of a series of
   46019 ** 4-byte big-endian integers, as follows:
   46020 **
   46021 **     0: Page number.
   46022 **     4: For commit records, the size of the database image in pages
   46023 **        after the commit. For all other records, zero.
   46024 **     8: Salt-1 (copied from the wal-header)
   46025 **    12: Salt-2 (copied from the wal-header)
   46026 **    16: Checksum-1.
   46027 **    20: Checksum-2.
   46028 */
   46029 static void walEncodeFrame(
   46030   Wal *pWal,                      /* The write-ahead log */
   46031   u32 iPage,                      /* Database page number for frame */
   46032   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   46033   u8 *aData,                      /* Pointer to page data */
   46034   u8 *aFrame                      /* OUT: Write encoded frame here */
   46035 ){
   46036   int nativeCksum;                /* True for native byte-order checksums */
   46037   u32 *aCksum = pWal->hdr.aFrameCksum;
   46038   assert( WAL_FRAME_HDRSIZE==24 );
   46039   sqlite3Put4byte(&aFrame[0], iPage);
   46040   sqlite3Put4byte(&aFrame[4], nTruncate);
   46041   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   46042 
   46043   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   46044   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   46045   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   46046 
   46047   sqlite3Put4byte(&aFrame[16], aCksum[0]);
   46048   sqlite3Put4byte(&aFrame[20], aCksum[1]);
   46049 }
   46050 
   46051 /*
   46052 ** Check to see if the frame with header in aFrame[] and content
   46053 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   46054 ** *pnTruncate and return true.  Return if the frame is not valid.
   46055 */
   46056 static int walDecodeFrame(
   46057   Wal *pWal,                      /* The write-ahead log */
   46058   u32 *piPage,                    /* OUT: Database page number for frame */
   46059   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   46060   u8 *aData,                      /* Pointer to page data (for checksum) */
   46061   u8 *aFrame                      /* Frame data */
   46062 ){
   46063   int nativeCksum;                /* True for native byte-order checksums */
   46064   u32 *aCksum = pWal->hdr.aFrameCksum;
   46065   u32 pgno;                       /* Page number of the frame */
   46066   assert( WAL_FRAME_HDRSIZE==24 );
   46067 
   46068   /* A frame is only valid if the salt values in the frame-header
   46069   ** match the salt values in the wal-header.
   46070   */
   46071   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   46072     return 0;
   46073   }
   46074 
   46075   /* A frame is only valid if the page number is creater than zero.
   46076   */
   46077   pgno = sqlite3Get4byte(&aFrame[0]);
   46078   if( pgno==0 ){
   46079     return 0;
   46080   }
   46081 
   46082   /* A frame is only valid if a checksum of the WAL header,
   46083   ** all prior frams, the first 16 bytes of this frame-header,
   46084   ** and the frame-data matches the checksum in the last 8
   46085   ** bytes of this frame-header.
   46086   */
   46087   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   46088   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   46089   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   46090   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   46091    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   46092   ){
   46093     /* Checksum failed. */
   46094     return 0;
   46095   }
   46096 
   46097   /* If we reach this point, the frame is valid.  Return the page number
   46098   ** and the new database size.
   46099   */
   46100   *piPage = pgno;
   46101   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   46102   return 1;
   46103 }
   46104 
   46105 
   46106 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   46107 /*
   46108 ** Names of locks.  This routine is used to provide debugging output and is not
   46109 ** a part of an ordinary build.
   46110 */
   46111 static const char *walLockName(int lockIdx){
   46112   if( lockIdx==WAL_WRITE_LOCK ){
   46113     return "WRITE-LOCK";
   46114   }else if( lockIdx==WAL_CKPT_LOCK ){
   46115     return "CKPT-LOCK";
   46116   }else if( lockIdx==WAL_RECOVER_LOCK ){
   46117     return "RECOVER-LOCK";
   46118   }else{
   46119     static char zName[15];
   46120     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   46121                      lockIdx-WAL_READ_LOCK(0));
   46122     return zName;
   46123   }
   46124 }
   46125 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   46126 
   46127 
   46128 /*
   46129 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   46130 ** A lock cannot be moved directly between shared and exclusive - it must go
   46131 ** through the unlocked state first.
   46132 **
   46133 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   46134 */
   46135 static int walLockShared(Wal *pWal, int lockIdx){
   46136   int rc;
   46137   if( pWal->exclusiveMode ) return SQLITE_OK;
   46138   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   46139                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   46140   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   46141             walLockName(lockIdx), rc ? "failed" : "ok"));
   46142   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   46143   return rc;
   46144 }
   46145 static void walUnlockShared(Wal *pWal, int lockIdx){
   46146   if( pWal->exclusiveMode ) return;
   46147   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   46148                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   46149   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   46150 }
   46151 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   46152   int rc;
   46153   if( pWal->exclusiveMode ) return SQLITE_OK;
   46154   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   46155                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   46156   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   46157             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   46158   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   46159   return rc;
   46160 }
   46161 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   46162   if( pWal->exclusiveMode ) return;
   46163   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   46164                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   46165   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   46166              walLockName(lockIdx), n));
   46167 }
   46168 
   46169 /*
   46170 ** Compute a hash on a page number.  The resulting hash value must land
   46171 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   46172 ** the hash to the next value in the event of a collision.
   46173 */
   46174 static int walHash(u32 iPage){
   46175   assert( iPage>0 );
   46176   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   46177   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   46178 }
   46179 static int walNextHash(int iPriorHash){
   46180   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   46181 }
   46182 
   46183 /*
   46184 ** Return pointers to the hash table and page number array stored on
   46185 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   46186 ** numbered starting from 0.
   46187 **
   46188 ** Set output variable *paHash to point to the start of the hash table
   46189 ** in the wal-index file. Set *piZero to one less than the frame
   46190 ** number of the first frame indexed by this hash table. If a
   46191 ** slot in the hash table is set to N, it refers to frame number
   46192 ** (*piZero+N) in the log.
   46193 **
   46194 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   46195 ** first frame indexed by the hash table, frame (*piZero+1).
   46196 */
   46197 static int walHashGet(
   46198   Wal *pWal,                      /* WAL handle */
   46199   int iHash,                      /* Find the iHash'th table */
   46200   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   46201   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   46202   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   46203 ){
   46204   int rc;                         /* Return code */
   46205   volatile u32 *aPgno;
   46206 
   46207   rc = walIndexPage(pWal, iHash, &aPgno);
   46208   assert( rc==SQLITE_OK || iHash>0 );
   46209 
   46210   if( rc==SQLITE_OK ){
   46211     u32 iZero;
   46212     volatile ht_slot *aHash;
   46213 
   46214     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   46215     if( iHash==0 ){
   46216       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   46217       iZero = 0;
   46218     }else{
   46219       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   46220     }
   46221 
   46222     *paPgno = &aPgno[-1];
   46223     *paHash = aHash;
   46224     *piZero = iZero;
   46225   }
   46226   return rc;
   46227 }
   46228 
   46229 /*
   46230 ** Return the number of the wal-index page that contains the hash-table
   46231 ** and page-number array that contain entries corresponding to WAL frame
   46232 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   46233 ** are numbered starting from 0.
   46234 */
   46235 static int walFramePage(u32 iFrame){
   46236   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   46237   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   46238        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   46239        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   46240        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   46241        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   46242   );
   46243   return iHash;
   46244 }
   46245 
   46246 /*
   46247 ** Return the page number associated with frame iFrame in this WAL.
   46248 */
   46249 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   46250   int iHash = walFramePage(iFrame);
   46251   if( iHash==0 ){
   46252     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   46253   }
   46254   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   46255 }
   46256 
   46257 /*
   46258 ** Remove entries from the hash table that point to WAL slots greater
   46259 ** than pWal->hdr.mxFrame.
   46260 **
   46261 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   46262 ** to a rollback or savepoint.
   46263 **
   46264 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   46265 ** updated.  Any later hash tables will be automatically cleared when
   46266 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   46267 ** actually needed.
   46268 */
   46269 static void walCleanupHash(Wal *pWal){
   46270   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   46271   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   46272   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   46273   int iLimit = 0;                 /* Zero values greater than this */
   46274   int nByte;                      /* Number of bytes to zero in aPgno[] */
   46275   int i;                          /* Used to iterate through aHash[] */
   46276 
   46277   assert( pWal->writeLock );
   46278   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   46279   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   46280   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   46281 
   46282   if( pWal->hdr.mxFrame==0 ) return;
   46283 
   46284   /* Obtain pointers to the hash-table and page-number array containing
   46285   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   46286   ** that the page said hash-table and array reside on is already mapped.
   46287   */
   46288   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   46289   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   46290   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   46291 
   46292   /* Zero all hash-table entries that correspond to frame numbers greater
   46293   ** than pWal->hdr.mxFrame.
   46294   */
   46295   iLimit = pWal->hdr.mxFrame - iZero;
   46296   assert( iLimit>0 );
   46297   for(i=0; i<HASHTABLE_NSLOT; i++){
   46298     if( aHash[i]>iLimit ){
   46299       aHash[i] = 0;
   46300     }
   46301   }
   46302 
   46303   /* Zero the entries in the aPgno array that correspond to frames with
   46304   ** frame numbers greater than pWal->hdr.mxFrame.
   46305   */
   46306   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   46307   memset((void *)&aPgno[iLimit+1], 0, nByte);
   46308 
   46309 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   46310   /* Verify that the every entry in the mapping region is still reachable
   46311   ** via the hash table even after the cleanup.
   46312   */
   46313   if( iLimit ){
   46314     int i;           /* Loop counter */
   46315     int iKey;        /* Hash key */
   46316     for(i=1; i<=iLimit; i++){
   46317       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   46318         if( aHash[iKey]==i ) break;
   46319       }
   46320       assert( aHash[iKey]==i );
   46321     }
   46322   }
   46323 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   46324 }
   46325 
   46326 
   46327 /*
   46328 ** Set an entry in the wal-index that will map database page number
   46329 ** pPage into WAL frame iFrame.
   46330 */
   46331 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   46332   int rc;                         /* Return code */
   46333   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   46334   volatile u32 *aPgno = 0;        /* Page number array */
   46335   volatile ht_slot *aHash = 0;    /* Hash table */
   46336 
   46337   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   46338 
   46339   /* Assuming the wal-index file was successfully mapped, populate the
   46340   ** page number array and hash table entry.
   46341   */
   46342   if( rc==SQLITE_OK ){
   46343     int iKey;                     /* Hash table key */
   46344     int idx;                      /* Value to write to hash-table slot */
   46345     int nCollide;                 /* Number of hash collisions */
   46346 
   46347     idx = iFrame - iZero;
   46348     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   46349 
   46350     /* If this is the first entry to be added to this hash-table, zero the
   46351     ** entire hash table and aPgno[] array before proceding.
   46352     */
   46353     if( idx==1 ){
   46354       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   46355       memset((void*)&aPgno[1], 0, nByte);
   46356     }
   46357 
   46358     /* If the entry in aPgno[] is already set, then the previous writer
   46359     ** must have exited unexpectedly in the middle of a transaction (after
   46360     ** writing one or more dirty pages to the WAL to free up memory).
   46361     ** Remove the remnants of that writers uncommitted transaction from
   46362     ** the hash-table before writing any new entries.
   46363     */
   46364     if( aPgno[idx] ){
   46365       walCleanupHash(pWal);
   46366       assert( !aPgno[idx] );
   46367     }
   46368 
   46369     /* Write the aPgno[] array entry and the hash-table slot. */
   46370     nCollide = idx;
   46371     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   46372       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   46373     }
   46374     aPgno[idx] = iPage;
   46375     aHash[iKey] = (ht_slot)idx;
   46376 
   46377 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   46378     /* Verify that the number of entries in the hash table exactly equals
   46379     ** the number of entries in the mapping region.
   46380     */
   46381     {
   46382       int i;           /* Loop counter */
   46383       int nEntry = 0;  /* Number of entries in the hash table */
   46384       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   46385       assert( nEntry==idx );
   46386     }
   46387 
   46388     /* Verify that the every entry in the mapping region is reachable
   46389     ** via the hash table.  This turns out to be a really, really expensive
   46390     ** thing to check, so only do this occasionally - not on every
   46391     ** iteration.
   46392     */
   46393     if( (idx&0x3ff)==0 ){
   46394       int i;           /* Loop counter */
   46395       for(i=1; i<=idx; i++){
   46396         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   46397           if( aHash[iKey]==i ) break;
   46398         }
   46399         assert( aHash[iKey]==i );
   46400       }
   46401     }
   46402 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   46403   }
   46404 
   46405 
   46406   return rc;
   46407 }
   46408 
   46409 
   46410 /*
   46411 ** Recover the wal-index by reading the write-ahead log file.
   46412 **
   46413 ** This routine first tries to establish an exclusive lock on the
   46414 ** wal-index to prevent other threads/processes from doing anything
   46415 ** with the WAL or wal-index while recovery is running.  The
   46416 ** WAL_RECOVER_LOCK is also held so that other threads will know
   46417 ** that this thread is running recovery.  If unable to establish
   46418 ** the necessary locks, this routine returns SQLITE_BUSY.
   46419 */
   46420 static int walIndexRecover(Wal *pWal){
   46421   int rc;                         /* Return Code */
   46422   i64 nSize;                      /* Size of log file */
   46423   u32 aFrameCksum[2] = {0, 0};
   46424   int iLock;                      /* Lock offset to lock for checkpoint */
   46425   int nLock;                      /* Number of locks to hold */
   46426 
   46427   /* Obtain an exclusive lock on all byte in the locking range not already
   46428   ** locked by the caller. The caller is guaranteed to have locked the
   46429   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   46430   ** If successful, the same bytes that are locked here are unlocked before
   46431   ** this function returns.
   46432   */
   46433   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   46434   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   46435   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   46436   assert( pWal->writeLock );
   46437   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   46438   nLock = SQLITE_SHM_NLOCK - iLock;
   46439   rc = walLockExclusive(pWal, iLock, nLock);
   46440   if( rc ){
   46441     return rc;
   46442   }
   46443   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   46444 
   46445   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   46446 
   46447   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   46448   if( rc!=SQLITE_OK ){
   46449     goto recovery_error;
   46450   }
   46451 
   46452   if( nSize>WAL_HDRSIZE ){
   46453     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   46454     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   46455     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   46456     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   46457     int iFrame;                   /* Index of last frame read */
   46458     i64 iOffset;                  /* Next offset to read from log file */
   46459     int szPage;                   /* Page size according to the log */
   46460     u32 magic;                    /* Magic value read from WAL header */
   46461     u32 version;                  /* Magic value read from WAL header */
   46462     int isValid;                  /* True if this frame is valid */
   46463 
   46464     /* Read in the WAL header. */
   46465     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   46466     if( rc!=SQLITE_OK ){
   46467       goto recovery_error;
   46468     }
   46469 
   46470     /* If the database page size is not a power of two, or is greater than
   46471     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   46472     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   46473     ** WAL file.
   46474     */
   46475     magic = sqlite3Get4byte(&aBuf[0]);
   46476     szPage = sqlite3Get4byte(&aBuf[8]);
   46477     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   46478      || szPage&(szPage-1)
   46479      || szPage>SQLITE_MAX_PAGE_SIZE
   46480      || szPage<512
   46481     ){
   46482       goto finished;
   46483     }
   46484     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   46485     pWal->szPage = szPage;
   46486     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   46487     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   46488 
   46489     /* Verify that the WAL header checksum is correct */
   46490     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   46491         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   46492     );
   46493     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   46494      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   46495     ){
   46496       goto finished;
   46497     }
   46498 
   46499     /* Verify that the version number on the WAL format is one that
   46500     ** are able to understand */
   46501     version = sqlite3Get4byte(&aBuf[4]);
   46502     if( version!=WAL_MAX_VERSION ){
   46503       rc = SQLITE_CANTOPEN_BKPT;
   46504       goto finished;
   46505     }
   46506 
   46507     /* Malloc a buffer to read frames into. */
   46508     szFrame = szPage + WAL_FRAME_HDRSIZE;
   46509     aFrame = (u8 *)sqlite3_malloc(szFrame);
   46510     if( !aFrame ){
   46511       rc = SQLITE_NOMEM;
   46512       goto recovery_error;
   46513     }
   46514     aData = &aFrame[WAL_FRAME_HDRSIZE];
   46515 
   46516     /* Read all frames from the log file. */
   46517     iFrame = 0;
   46518     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   46519       u32 pgno;                   /* Database page number for frame */
   46520       u32 nTruncate;              /* dbsize field from frame header */
   46521 
   46522       /* Read and decode the next log frame. */
   46523       iFrame++;
   46524       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   46525       if( rc!=SQLITE_OK ) break;
   46526       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   46527       if( !isValid ) break;
   46528       rc = walIndexAppend(pWal, iFrame, pgno);
   46529       if( rc!=SQLITE_OK ) break;
   46530 
   46531       /* If nTruncate is non-zero, this is a commit record. */
   46532       if( nTruncate ){
   46533         pWal->hdr.mxFrame = iFrame;
   46534         pWal->hdr.nPage = nTruncate;
   46535         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   46536         testcase( szPage<=32768 );
   46537         testcase( szPage>=65536 );
   46538         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   46539         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   46540       }
   46541     }
   46542 
   46543     sqlite3_free(aFrame);
   46544   }
   46545 
   46546 finished:
   46547   if( rc==SQLITE_OK ){
   46548     volatile WalCkptInfo *pInfo;
   46549     int i;
   46550     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   46551     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   46552     walIndexWriteHdr(pWal);
   46553 
   46554     /* Reset the checkpoint-header. This is safe because this thread is
   46555     ** currently holding locks that exclude all other readers, writers and
   46556     ** checkpointers.
   46557     */
   46558     pInfo = walCkptInfo(pWal);
   46559     pInfo->nBackfill = 0;
   46560     pInfo->aReadMark[0] = 0;
   46561     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   46562 
   46563     /* If more than one frame was recovered from the log file, report an
   46564     ** event via sqlite3_log(). This is to help with identifying performance
   46565     ** problems caused by applications routinely shutting down without
   46566     ** checkpointing the log file.
   46567     */
   46568     if( pWal->hdr.nPage ){
   46569       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
   46570           pWal->hdr.nPage, pWal->zWalName
   46571       );
   46572     }
   46573   }
   46574 
   46575 recovery_error:
   46576   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   46577   walUnlockExclusive(pWal, iLock, nLock);
   46578   return rc;
   46579 }
   46580 
   46581 /*
   46582 ** Close an open wal-index.
   46583 */
   46584 static void walIndexClose(Wal *pWal, int isDelete){
   46585   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   46586     int i;
   46587     for(i=0; i<pWal->nWiData; i++){
   46588       sqlite3_free((void *)pWal->apWiData[i]);
   46589       pWal->apWiData[i] = 0;
   46590     }
   46591   }else{
   46592     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   46593   }
   46594 }
   46595 
   46596 /*
   46597 ** Open a connection to the WAL file zWalName. The database file must
   46598 ** already be opened on connection pDbFd. The buffer that zWalName points
   46599 ** to must remain valid for the lifetime of the returned Wal* handle.
   46600 **
   46601 ** A SHARED lock should be held on the database file when this function
   46602 ** is called. The purpose of this SHARED lock is to prevent any other
   46603 ** client from unlinking the WAL or wal-index file. If another process
   46604 ** were to do this just after this client opened one of these files, the
   46605 ** system would be badly broken.
   46606 **
   46607 ** If the log file is successfully opened, SQLITE_OK is returned and
   46608 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   46609 ** an SQLite error code is returned and *ppWal is left unmodified.
   46610 */
   46611 SQLITE_PRIVATE int sqlite3WalOpen(
   46612   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   46613   sqlite3_file *pDbFd,            /* The open database file */
   46614   const char *zWalName,           /* Name of the WAL file */
   46615   int bNoShm,                     /* True to run in heap-memory mode */
   46616   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
   46617   Wal **ppWal                     /* OUT: Allocated Wal handle */
   46618 ){
   46619   int rc;                         /* Return Code */
   46620   Wal *pRet;                      /* Object to allocate and return */
   46621   int flags;                      /* Flags passed to OsOpen() */
   46622 
   46623   assert( zWalName && zWalName[0] );
   46624   assert( pDbFd );
   46625 
   46626   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   46627   ** this source file.  Verify that the #defines of the locking byte offsets
   46628   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   46629   */
   46630 #ifdef WIN_SHM_BASE
   46631   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   46632 #endif
   46633 #ifdef UNIX_SHM_BASE
   46634   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   46635 #endif
   46636 
   46637 
   46638   /* Allocate an instance of struct Wal to return. */
   46639   *ppWal = 0;
   46640   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   46641   if( !pRet ){
   46642     return SQLITE_NOMEM;
   46643   }
   46644 
   46645   pRet->pVfs = pVfs;
   46646   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   46647   pRet->pDbFd = pDbFd;
   46648   pRet->readLock = -1;
   46649   pRet->mxWalSize = mxWalSize;
   46650   pRet->zWalName = zWalName;
   46651   pRet->syncHeader = 1;
   46652   pRet->padToSectorBoundary = 1;
   46653   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   46654 
   46655   /* Open file handle on the write-ahead log file. */
   46656   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   46657   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   46658   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   46659     pRet->readOnly = WAL_RDONLY;
   46660   }
   46661 
   46662   if( rc!=SQLITE_OK ){
   46663     walIndexClose(pRet, 0);
   46664     sqlite3OsClose(pRet->pWalFd);
   46665     sqlite3_free(pRet);
   46666   }else{
   46667     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
   46668     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
   46669     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
   46670       pRet->padToSectorBoundary = 0;
   46671     }
   46672     *ppWal = pRet;
   46673     WALTRACE(("WAL%d: opened\n", pRet));
   46674   }
   46675   return rc;
   46676 }
   46677 
   46678 /*
   46679 ** Change the size to which the WAL file is trucated on each reset.
   46680 */
   46681 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
   46682   if( pWal ) pWal->mxWalSize = iLimit;
   46683 }
   46684 
   46685 /*
   46686 ** Find the smallest page number out of all pages held in the WAL that
   46687 ** has not been returned by any prior invocation of this method on the
   46688 ** same WalIterator object.   Write into *piFrame the frame index where
   46689 ** that page was last written into the WAL.  Write into *piPage the page
   46690 ** number.
   46691 **
   46692 ** Return 0 on success.  If there are no pages in the WAL with a page
   46693 ** number larger than *piPage, then return 1.
   46694 */
   46695 static int walIteratorNext(
   46696   WalIterator *p,               /* Iterator */
   46697   u32 *piPage,                  /* OUT: The page number of the next page */
   46698   u32 *piFrame                  /* OUT: Wal frame index of next page */
   46699 ){
   46700   u32 iMin;                     /* Result pgno must be greater than iMin */
   46701   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   46702   int i;                        /* For looping through segments */
   46703 
   46704   iMin = p->iPrior;
   46705   assert( iMin<0xffffffff );
   46706   for(i=p->nSegment-1; i>=0; i--){
   46707     struct WalSegment *pSegment = &p->aSegment[i];
   46708     while( pSegment->iNext<pSegment->nEntry ){
   46709       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   46710       if( iPg>iMin ){
   46711         if( iPg<iRet ){
   46712           iRet = iPg;
   46713           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   46714         }
   46715         break;
   46716       }
   46717       pSegment->iNext++;
   46718     }
   46719   }
   46720 
   46721   *piPage = p->iPrior = iRet;
   46722   return (iRet==0xFFFFFFFF);
   46723 }
   46724 
   46725 /*
   46726 ** This function merges two sorted lists into a single sorted list.
   46727 **
   46728 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
   46729 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
   46730 ** is guaranteed for all J<K:
   46731 **
   46732 **        aContent[aLeft[J]] < aContent[aLeft[K]]
   46733 **        aContent[aRight[J]] < aContent[aRight[K]]
   46734 **
   46735 ** This routine overwrites aRight[] with a new (probably longer) sequence
   46736 ** of indices such that the aRight[] contains every index that appears in
   46737 ** either aLeft[] or the old aRight[] and such that the second condition
   46738 ** above is still met.
   46739 **
   46740 ** The aContent[aLeft[X]] values will be unique for all X.  And the
   46741 ** aContent[aRight[X]] values will be unique too.  But there might be
   46742 ** one or more combinations of X and Y such that
   46743 **
   46744 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
   46745 **
   46746 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
   46747 */
   46748 static void walMerge(
   46749   const u32 *aContent,            /* Pages in wal - keys for the sort */
   46750   ht_slot *aLeft,                 /* IN: Left hand input list */
   46751   int nLeft,                      /* IN: Elements in array *paLeft */
   46752   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   46753   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   46754   ht_slot *aTmp                   /* Temporary buffer */
   46755 ){
   46756   int iLeft = 0;                  /* Current index in aLeft */
   46757   int iRight = 0;                 /* Current index in aRight */
   46758   int iOut = 0;                   /* Current index in output buffer */
   46759   int nRight = *pnRight;
   46760   ht_slot *aRight = *paRight;
   46761 
   46762   assert( nLeft>0 && nRight>0 );
   46763   while( iRight<nRight || iLeft<nLeft ){
   46764     ht_slot logpage;
   46765     Pgno dbpage;
   46766 
   46767     if( (iLeft<nLeft)
   46768      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   46769     ){
   46770       logpage = aLeft[iLeft++];
   46771     }else{
   46772       logpage = aRight[iRight++];
   46773     }
   46774     dbpage = aContent[logpage];
   46775 
   46776     aTmp[iOut++] = logpage;
   46777     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   46778 
   46779     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   46780     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   46781   }
   46782 
   46783   *paRight = aLeft;
   46784   *pnRight = iOut;
   46785   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   46786 }
   46787 
   46788 /*
   46789 ** Sort the elements in list aList using aContent[] as the sort key.
   46790 ** Remove elements with duplicate keys, preferring to keep the
   46791 ** larger aList[] values.
   46792 **
   46793 ** The aList[] entries are indices into aContent[].  The values in
   46794 ** aList[] are to be sorted so that for all J<K:
   46795 **
   46796 **      aContent[aList[J]] < aContent[aList[K]]
   46797 **
   46798 ** For any X and Y such that
   46799 **
   46800 **      aContent[aList[X]] == aContent[aList[Y]]
   46801 **
   46802 ** Keep the larger of the two values aList[X] and aList[Y] and discard
   46803 ** the smaller.
   46804 */
   46805 static void walMergesort(
   46806   const u32 *aContent,            /* Pages in wal */
   46807   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   46808   ht_slot *aList,                 /* IN/OUT: List to sort */
   46809   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   46810 ){
   46811   struct Sublist {
   46812     int nList;                    /* Number of elements in aList */
   46813     ht_slot *aList;               /* Pointer to sub-list content */
   46814   };
   46815 
   46816   const int nList = *pnList;      /* Size of input list */
   46817   int nMerge = 0;                 /* Number of elements in list aMerge */
   46818   ht_slot *aMerge = 0;            /* List to be merged */
   46819   int iList;                      /* Index into input list */
   46820   int iSub = 0;                   /* Index into aSub array */
   46821   struct Sublist aSub[13];        /* Array of sub-lists */
   46822 
   46823   memset(aSub, 0, sizeof(aSub));
   46824   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   46825   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   46826 
   46827   for(iList=0; iList<nList; iList++){
   46828     nMerge = 1;
   46829     aMerge = &aList[iList];
   46830     for(iSub=0; iList & (1<<iSub); iSub++){
   46831       struct Sublist *p = &aSub[iSub];
   46832       assert( p->aList && p->nList<=(1<<iSub) );
   46833       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   46834       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   46835     }
   46836     aSub[iSub].aList = aMerge;
   46837     aSub[iSub].nList = nMerge;
   46838   }
   46839 
   46840   for(iSub++; iSub<ArraySize(aSub); iSub++){
   46841     if( nList & (1<<iSub) ){
   46842       struct Sublist *p = &aSub[iSub];
   46843       assert( p->nList<=(1<<iSub) );
   46844       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   46845       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   46846     }
   46847   }
   46848   assert( aMerge==aList );
   46849   *pnList = nMerge;
   46850 
   46851 #ifdef SQLITE_DEBUG
   46852   {
   46853     int i;
   46854     for(i=1; i<*pnList; i++){
   46855       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   46856     }
   46857   }
   46858 #endif
   46859 }
   46860 
   46861 /*
   46862 ** Free an iterator allocated by walIteratorInit().
   46863 */
   46864 static void walIteratorFree(WalIterator *p){
   46865   sqlite3ScratchFree(p);
   46866 }
   46867 
   46868 /*
   46869 ** Construct a WalInterator object that can be used to loop over all
   46870 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   46871 ** lock.
   46872 **
   46873 ** On success, make *pp point to the newly allocated WalInterator object
   46874 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   46875 ** returns an error, the value of *pp is undefined.
   46876 **
   46877 ** The calling routine should invoke walIteratorFree() to destroy the
   46878 ** WalIterator object when it has finished with it.
   46879 */
   46880 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   46881   WalIterator *p;                 /* Return value */
   46882   int nSegment;                   /* Number of segments to merge */
   46883   u32 iLast;                      /* Last frame in log */
   46884   int nByte;                      /* Number of bytes to allocate */
   46885   int i;                          /* Iterator variable */
   46886   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   46887   int rc = SQLITE_OK;             /* Return Code */
   46888 
   46889   /* This routine only runs while holding the checkpoint lock. And
   46890   ** it only runs if there is actually content in the log (mxFrame>0).
   46891   */
   46892   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   46893   iLast = pWal->hdr.mxFrame;
   46894 
   46895   /* Allocate space for the WalIterator object. */
   46896   nSegment = walFramePage(iLast) + 1;
   46897   nByte = sizeof(WalIterator)
   46898         + (nSegment-1)*sizeof(struct WalSegment)
   46899         + iLast*sizeof(ht_slot);
   46900   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
   46901   if( !p ){
   46902     return SQLITE_NOMEM;
   46903   }
   46904   memset(p, 0, nByte);
   46905   p->nSegment = nSegment;
   46906 
   46907   /* Allocate temporary space used by the merge-sort routine. This block
   46908   ** of memory will be freed before this function returns.
   46909   */
   46910   aTmp = (ht_slot *)sqlite3ScratchMalloc(
   46911       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   46912   );
   46913   if( !aTmp ){
   46914     rc = SQLITE_NOMEM;
   46915   }
   46916 
   46917   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   46918     volatile ht_slot *aHash;
   46919     u32 iZero;
   46920     volatile u32 *aPgno;
   46921 
   46922     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   46923     if( rc==SQLITE_OK ){
   46924       int j;                      /* Counter variable */
   46925       int nEntry;                 /* Number of entries in this segment */
   46926       ht_slot *aIndex;            /* Sorted index for this segment */
   46927 
   46928       aPgno++;
   46929       if( (i+1)==nSegment ){
   46930         nEntry = (int)(iLast - iZero);
   46931       }else{
   46932         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   46933       }
   46934       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   46935       iZero++;
   46936 
   46937       for(j=0; j<nEntry; j++){
   46938         aIndex[j] = (ht_slot)j;
   46939       }
   46940       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   46941       p->aSegment[i].iZero = iZero;
   46942       p->aSegment[i].nEntry = nEntry;
   46943       p->aSegment[i].aIndex = aIndex;
   46944       p->aSegment[i].aPgno = (u32 *)aPgno;
   46945     }
   46946   }
   46947   sqlite3ScratchFree(aTmp);
   46948 
   46949   if( rc!=SQLITE_OK ){
   46950     walIteratorFree(p);
   46951   }
   46952   *pp = p;
   46953   return rc;
   46954 }
   46955 
   46956 /*
   46957 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
   46958 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
   46959 ** busy-handler function. Invoke it and retry the lock until either the
   46960 ** lock is successfully obtained or the busy-handler returns 0.
   46961 */
   46962 static int walBusyLock(
   46963   Wal *pWal,                      /* WAL connection */
   46964   int (*xBusy)(void*),            /* Function to call when busy */
   46965   void *pBusyArg,                 /* Context argument for xBusyHandler */
   46966   int lockIdx,                    /* Offset of first byte to lock */
   46967   int n                           /* Number of bytes to lock */
   46968 ){
   46969   int rc;
   46970   do {
   46971     rc = walLockExclusive(pWal, lockIdx, n);
   46972   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
   46973   return rc;
   46974 }
   46975 
   46976 /*
   46977 ** The cache of the wal-index header must be valid to call this function.
   46978 ** Return the page-size in bytes used by the database.
   46979 */
   46980 static int walPagesize(Wal *pWal){
   46981   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   46982 }
   46983 
   46984 /*
   46985 ** Copy as much content as we can from the WAL back into the database file
   46986 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   46987 **
   46988 ** The amount of information copies from WAL to database might be limited
   46989 ** by active readers.  This routine will never overwrite a database page
   46990 ** that a concurrent reader might be using.
   46991 **
   46992 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   46993 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   46994 ** checkpoints are always run by a background thread or background
   46995 ** process, foreground threads will never block on a lengthy fsync call.
   46996 **
   46997 ** Fsync is called on the WAL before writing content out of the WAL and
   46998 ** into the database.  This ensures that if the new content is persistent
   46999 ** in the WAL and can be recovered following a power-loss or hard reset.
   47000 **
   47001 ** Fsync is also called on the database file if (and only if) the entire
   47002 ** WAL content is copied into the database file.  This second fsync makes
   47003 ** it safe to delete the WAL since the new content will persist in the
   47004 ** database file.
   47005 **
   47006 ** This routine uses and updates the nBackfill field of the wal-index header.
   47007 ** This is the only routine tha will increase the value of nBackfill.
   47008 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   47009 ** its value.)
   47010 **
   47011 ** The caller must be holding sufficient locks to ensure that no other
   47012 ** checkpoint is running (in any other thread or process) at the same
   47013 ** time.
   47014 */
   47015 static int walCheckpoint(
   47016   Wal *pWal,                      /* Wal connection */
   47017   int eMode,                      /* One of PASSIVE, FULL or RESTART */
   47018   int (*xBusyCall)(void*),        /* Function to call when busy */
   47019   void *pBusyArg,                 /* Context argument for xBusyHandler */
   47020   int sync_flags,                 /* Flags for OsSync() (or 0) */
   47021   u8 *zBuf                        /* Temporary buffer to use */
   47022 ){
   47023   int rc;                         /* Return code */
   47024   int szPage;                     /* Database page-size */
   47025   WalIterator *pIter = 0;         /* Wal iterator context */
   47026   u32 iDbpage = 0;                /* Next database page to write */
   47027   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   47028   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   47029   u32 mxPage;                     /* Max database page to write */
   47030   int i;                          /* Loop counter */
   47031   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   47032   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
   47033 
   47034   szPage = walPagesize(pWal);
   47035   testcase( szPage<=32768 );
   47036   testcase( szPage>=65536 );
   47037   pInfo = walCkptInfo(pWal);
   47038   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
   47039 
   47040   /* Allocate the iterator */
   47041   rc = walIteratorInit(pWal, &pIter);
   47042   if( rc!=SQLITE_OK ){
   47043     return rc;
   47044   }
   47045   assert( pIter );
   47046 
   47047   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
   47048 
   47049   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   47050   ** safe to write into the database.  Frames beyond mxSafeFrame might
   47051   ** overwrite database pages that are in use by active readers and thus
   47052   ** cannot be backfilled from the WAL.
   47053   */
   47054   mxSafeFrame = pWal->hdr.mxFrame;
   47055   mxPage = pWal->hdr.nPage;
   47056   for(i=1; i<WAL_NREADER; i++){
   47057     u32 y = pInfo->aReadMark[i];
   47058     if( mxSafeFrame>y ){
   47059       assert( y<=pWal->hdr.mxFrame );
   47060       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
   47061       if( rc==SQLITE_OK ){
   47062         pInfo->aReadMark[i] = READMARK_NOT_USED;
   47063         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47064       }else if( rc==SQLITE_BUSY ){
   47065         mxSafeFrame = y;
   47066         xBusy = 0;
   47067       }else{
   47068         goto walcheckpoint_out;
   47069       }
   47070     }
   47071   }
   47072 
   47073   if( pInfo->nBackfill<mxSafeFrame
   47074    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
   47075   ){
   47076     i64 nSize;                    /* Current size of database file */
   47077     u32 nBackfill = pInfo->nBackfill;
   47078 
   47079     /* Sync the WAL to disk */
   47080     if( sync_flags ){
   47081       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   47082     }
   47083 
   47084     /* If the database file may grow as a result of this checkpoint, hint
   47085     ** about the eventual size of the db file to the VFS layer.
   47086     */
   47087     if( rc==SQLITE_OK ){
   47088       i64 nReq = ((i64)mxPage * szPage);
   47089       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   47090       if( rc==SQLITE_OK && nSize<nReq ){
   47091         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   47092       }
   47093     }
   47094 
   47095     /* Iterate through the contents of the WAL, copying data to the db file. */
   47096     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   47097       i64 iOffset;
   47098       assert( walFramePgno(pWal, iFrame)==iDbpage );
   47099       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
   47100       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   47101       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   47102       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   47103       if( rc!=SQLITE_OK ) break;
   47104       iOffset = (iDbpage-1)*(i64)szPage;
   47105       testcase( IS_BIG_INT(iOffset) );
   47106       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   47107       if( rc!=SQLITE_OK ) break;
   47108     }
   47109 
   47110     /* If work was actually accomplished... */
   47111     if( rc==SQLITE_OK ){
   47112       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   47113         i64 szDb = pWal->hdr.nPage*(i64)szPage;
   47114         testcase( IS_BIG_INT(szDb) );
   47115         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   47116         if( rc==SQLITE_OK && sync_flags ){
   47117           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
   47118         }
   47119       }
   47120       if( rc==SQLITE_OK ){
   47121         pInfo->nBackfill = mxSafeFrame;
   47122       }
   47123     }
   47124 
   47125     /* Release the reader lock held while backfilling */
   47126     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   47127   }
   47128 
   47129   if( rc==SQLITE_BUSY ){
   47130     /* Reset the return code so as not to report a checkpoint failure
   47131     ** just because there are active readers.  */
   47132     rc = SQLITE_OK;
   47133   }
   47134 
   47135   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
   47136   ** file has been copied into the database file, then block until all
   47137   ** readers have finished using the wal file. This ensures that the next
   47138   ** process to write to the database restarts the wal file.
   47139   */
   47140   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   47141     assert( pWal->writeLock );
   47142     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   47143       rc = SQLITE_BUSY;
   47144     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
   47145       assert( mxSafeFrame==pWal->hdr.mxFrame );
   47146       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
   47147       if( rc==SQLITE_OK ){
   47148         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47149       }
   47150     }
   47151   }
   47152 
   47153  walcheckpoint_out:
   47154   walIteratorFree(pIter);
   47155   return rc;
   47156 }
   47157 
   47158 /*
   47159 ** If the WAL file is currently larger than nMax bytes in size, truncate
   47160 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
   47161 */
   47162 static void walLimitSize(Wal *pWal, i64 nMax){
   47163   i64 sz;
   47164   int rx;
   47165   sqlite3BeginBenignMalloc();
   47166   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
   47167   if( rx==SQLITE_OK && (sz > nMax ) ){
   47168     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
   47169   }
   47170   sqlite3EndBenignMalloc();
   47171   if( rx ){
   47172     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
   47173   }
   47174 }
   47175 
   47176 /*
   47177 ** Close a connection to a log file.
   47178 */
   47179 SQLITE_PRIVATE int sqlite3WalClose(
   47180   Wal *pWal,                      /* Wal to close */
   47181   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   47182   int nBuf,
   47183   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   47184 ){
   47185   int rc = SQLITE_OK;
   47186   if( pWal ){
   47187     int isDelete = 0;             /* True to unlink wal and wal-index files */
   47188 
   47189     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   47190     ** ordinary, rollback-mode locking methods, this guarantees that the
   47191     ** connection associated with this log file is the only connection to
   47192     ** the database. In this case checkpoint the database and unlink both
   47193     ** the wal and wal-index files.
   47194     **
   47195     ** The EXCLUSIVE lock is not released before returning.
   47196     */
   47197     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
   47198     if( rc==SQLITE_OK ){
   47199       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   47200         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   47201       }
   47202       rc = sqlite3WalCheckpoint(
   47203           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
   47204       );
   47205       if( rc==SQLITE_OK ){
   47206         int bPersist = -1;
   47207         sqlite3OsFileControlHint(
   47208             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
   47209         );
   47210         if( bPersist!=1 ){
   47211           /* Try to delete the WAL file if the checkpoint completed and
   47212           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
   47213           ** mode (!bPersist) */
   47214           isDelete = 1;
   47215         }else if( pWal->mxWalSize>=0 ){
   47216           /* Try to truncate the WAL file to zero bytes if the checkpoint
   47217           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
   47218           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
   47219           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
   47220           ** to zero bytes as truncating to the journal_size_limit might
   47221           ** leave a corrupt WAL file on disk. */
   47222           walLimitSize(pWal, 0);
   47223         }
   47224       }
   47225     }
   47226 
   47227     walIndexClose(pWal, isDelete);
   47228     sqlite3OsClose(pWal->pWalFd);
   47229     if( isDelete ){
   47230       sqlite3BeginBenignMalloc();
   47231       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   47232       sqlite3EndBenignMalloc();
   47233     }
   47234     WALTRACE(("WAL%p: closed\n", pWal));
   47235     sqlite3_free((void *)pWal->apWiData);
   47236     sqlite3_free(pWal);
   47237   }
   47238   return rc;
   47239 }
   47240 
   47241 /*
   47242 ** Try to read the wal-index header.  Return 0 on success and 1 if
   47243 ** there is a problem.
   47244 **
   47245 ** The wal-index is in shared memory.  Another thread or process might
   47246 ** be writing the header at the same time this procedure is trying to
   47247 ** read it, which might result in inconsistency.  A dirty read is detected
   47248 ** by verifying that both copies of the header are the same and also by
   47249 ** a checksum on the header.
   47250 **
   47251 ** If and only if the read is consistent and the header is different from
   47252 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   47253 ** and *pChanged is set to 1.
   47254 **
   47255 ** If the checksum cannot be verified return non-zero. If the header
   47256 ** is read successfully and the checksum verified, return zero.
   47257 */
   47258 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   47259   u32 aCksum[2];                  /* Checksum on the header content */
   47260   WalIndexHdr h1, h2;             /* Two copies of the header content */
   47261   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   47262 
   47263   /* The first page of the wal-index must be mapped at this point. */
   47264   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   47265 
   47266   /* Read the header. This might happen concurrently with a write to the
   47267   ** same area of shared memory on a different CPU in a SMP,
   47268   ** meaning it is possible that an inconsistent snapshot is read
   47269   ** from the file. If this happens, return non-zero.
   47270   **
   47271   ** There are two copies of the header at the beginning of the wal-index.
   47272   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   47273   ** Memory barriers are used to prevent the compiler or the hardware from
   47274   ** reordering the reads and writes.
   47275   */
   47276   aHdr = walIndexHdr(pWal);
   47277   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   47278   walShmBarrier(pWal);
   47279   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   47280 
   47281   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   47282     return 1;   /* Dirty read */
   47283   }
   47284   if( h1.isInit==0 ){
   47285     return 1;   /* Malformed header - probably all zeros */
   47286   }
   47287   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   47288   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   47289     return 1;   /* Checksum does not match */
   47290   }
   47291 
   47292   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   47293     *pChanged = 1;
   47294     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   47295     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   47296     testcase( pWal->szPage<=32768 );
   47297     testcase( pWal->szPage>=65536 );
   47298   }
   47299 
   47300   /* The header was successfully read. Return zero. */
   47301   return 0;
   47302 }
   47303 
   47304 /*
   47305 ** Read the wal-index header from the wal-index and into pWal->hdr.
   47306 ** If the wal-header appears to be corrupt, try to reconstruct the
   47307 ** wal-index from the WAL before returning.
   47308 **
   47309 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   47310 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
   47311 ** to 0.
   47312 **
   47313 ** If the wal-index header is successfully read, return SQLITE_OK.
   47314 ** Otherwise an SQLite error code.
   47315 */
   47316 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   47317   int rc;                         /* Return code */
   47318   int badHdr;                     /* True if a header read failed */
   47319   volatile u32 *page0;            /* Chunk of wal-index containing header */
   47320 
   47321   /* Ensure that page 0 of the wal-index (the page that contains the
   47322   ** wal-index header) is mapped. Return early if an error occurs here.
   47323   */
   47324   assert( pChanged );
   47325   rc = walIndexPage(pWal, 0, &page0);
   47326   if( rc!=SQLITE_OK ){
   47327     return rc;
   47328   };
   47329   assert( page0 || pWal->writeLock==0 );
   47330 
   47331   /* If the first page of the wal-index has been mapped, try to read the
   47332   ** wal-index header immediately, without holding any lock. This usually
   47333   ** works, but may fail if the wal-index header is corrupt or currently
   47334   ** being modified by another thread or process.
   47335   */
   47336   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   47337 
   47338   /* If the first attempt failed, it might have been due to a race
   47339   ** with a writer.  So get a WRITE lock and try again.
   47340   */
   47341   assert( badHdr==0 || pWal->writeLock==0 );
   47342   if( badHdr ){
   47343     if( pWal->readOnly & WAL_SHM_RDONLY ){
   47344       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
   47345         walUnlockShared(pWal, WAL_WRITE_LOCK);
   47346         rc = SQLITE_READONLY_RECOVERY;
   47347       }
   47348     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   47349       pWal->writeLock = 1;
   47350       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   47351         badHdr = walIndexTryHdr(pWal, pChanged);
   47352         if( badHdr ){
   47353           /* If the wal-index header is still malformed even while holding
   47354           ** a WRITE lock, it can only mean that the header is corrupted and
   47355           ** needs to be reconstructed.  So run recovery to do exactly that.
   47356           */
   47357           rc = walIndexRecover(pWal);
   47358           *pChanged = 1;
   47359         }
   47360       }
   47361       pWal->writeLock = 0;
   47362       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47363     }
   47364   }
   47365 
   47366   /* If the header is read successfully, check the version number to make
   47367   ** sure the wal-index was not constructed with some future format that
   47368   ** this version of SQLite cannot understand.
   47369   */
   47370   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   47371     rc = SQLITE_CANTOPEN_BKPT;
   47372   }
   47373 
   47374   return rc;
   47375 }
   47376 
   47377 /*
   47378 ** This is the value that walTryBeginRead returns when it needs to
   47379 ** be retried.
   47380 */
   47381 #define WAL_RETRY  (-1)
   47382 
   47383 /*
   47384 ** Attempt to start a read transaction.  This might fail due to a race or
   47385 ** other transient condition.  When that happens, it returns WAL_RETRY to
   47386 ** indicate to the caller that it is safe to retry immediately.
   47387 **
   47388 ** On success return SQLITE_OK.  On a permanent failure (such an
   47389 ** I/O error or an SQLITE_BUSY because another process is running
   47390 ** recovery) return a positive error code.
   47391 **
   47392 ** The useWal parameter is true to force the use of the WAL and disable
   47393 ** the case where the WAL is bypassed because it has been completely
   47394 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   47395 ** to make a copy of the wal-index header into pWal->hdr.  If the
   47396 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   47397 ** to the caller that the local paget cache is obsolete and needs to be
   47398 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   47399 ** be loaded and the pChanged parameter is unused.
   47400 **
   47401 ** The caller must set the cnt parameter to the number of prior calls to
   47402 ** this routine during the current read attempt that returned WAL_RETRY.
   47403 ** This routine will start taking more aggressive measures to clear the
   47404 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   47405 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   47406 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   47407 ** and is not honoring the locking protocol.  There is a vanishingly small
   47408 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   47409 ** bad luck when there is lots of contention for the wal-index, but that
   47410 ** possibility is so small that it can be safely neglected, we believe.
   47411 **
   47412 ** On success, this routine obtains a read lock on
   47413 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   47414 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   47415 ** that means the Wal does not hold any read lock.  The reader must not
   47416 ** access any database page that is modified by a WAL frame up to and
   47417 ** including frame number aReadMark[pWal->readLock].  The reader will
   47418 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   47419 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   47420 ** completely and get all content directly from the database file.
   47421 ** If the useWal parameter is 1 then the WAL will never be ignored and
   47422 ** this routine will always set pWal->readLock>0 on success.
   47423 ** When the read transaction is completed, the caller must release the
   47424 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   47425 **
   47426 ** This routine uses the nBackfill and aReadMark[] fields of the header
   47427 ** to select a particular WAL_READ_LOCK() that strives to let the
   47428 ** checkpoint process do as much work as possible.  This routine might
   47429 ** update values of the aReadMark[] array in the header, but if it does
   47430 ** so it takes care to hold an exclusive lock on the corresponding
   47431 ** WAL_READ_LOCK() while changing values.
   47432 */
   47433 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   47434   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   47435   u32 mxReadMark;                 /* Largest aReadMark[] value */
   47436   int mxI;                        /* Index of largest aReadMark[] value */
   47437   int i;                          /* Loop counter */
   47438   int rc = SQLITE_OK;             /* Return code  */
   47439 
   47440   assert( pWal->readLock<0 );     /* Not currently locked */
   47441 
   47442   /* Take steps to avoid spinning forever if there is a protocol error.
   47443   **
   47444   ** Circumstances that cause a RETRY should only last for the briefest
   47445   ** instances of time.  No I/O or other system calls are done while the
   47446   ** locks are held, so the locks should not be held for very long. But
   47447   ** if we are unlucky, another process that is holding a lock might get
   47448   ** paged out or take a page-fault that is time-consuming to resolve,
   47449   ** during the few nanoseconds that it is holding the lock.  In that case,
   47450   ** it might take longer than normal for the lock to free.
   47451   **
   47452   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   47453   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   47454   ** is more of a scheduler yield than an actual delay.  But on the 10th
   47455   ** an subsequent retries, the delays start becoming longer and longer,
   47456   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
   47457   ** The total delay time before giving up is less than 1 second.
   47458   */
   47459   if( cnt>5 ){
   47460     int nDelay = 1;                      /* Pause time in microseconds */
   47461     if( cnt>100 ){
   47462       VVA_ONLY( pWal->lockError = 1; )
   47463       return SQLITE_PROTOCOL;
   47464     }
   47465     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
   47466     sqlite3OsSleep(pWal->pVfs, nDelay);
   47467   }
   47468 
   47469   if( !useWal ){
   47470     rc = walIndexReadHdr(pWal, pChanged);
   47471     if( rc==SQLITE_BUSY ){
   47472       /* If there is not a recovery running in another thread or process
   47473       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   47474       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   47475       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   47476       ** would be technically correct.  But the race is benign since with
   47477       ** WAL_RETRY this routine will be called again and will probably be
   47478       ** right on the second iteration.
   47479       */
   47480       if( pWal->apWiData[0]==0 ){
   47481         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   47482         ** We assume this is a transient condition, so return WAL_RETRY. The
   47483         ** xShmMap() implementation used by the default unix and win32 VFS
   47484         ** modules may return SQLITE_BUSY due to a race condition in the
   47485         ** code that determines whether or not the shared-memory region
   47486         ** must be zeroed before the requested page is returned.
   47487         */
   47488         rc = WAL_RETRY;
   47489       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   47490         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   47491         rc = WAL_RETRY;
   47492       }else if( rc==SQLITE_BUSY ){
   47493         rc = SQLITE_BUSY_RECOVERY;
   47494       }
   47495     }
   47496     if( rc!=SQLITE_OK ){
   47497       return rc;
   47498     }
   47499   }
   47500 
   47501   pInfo = walCkptInfo(pWal);
   47502   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
   47503     /* The WAL has been completely backfilled (or it is empty).
   47504     ** and can be safely ignored.
   47505     */
   47506     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   47507     walShmBarrier(pWal);
   47508     if( rc==SQLITE_OK ){
   47509       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   47510         /* It is not safe to allow the reader to continue here if frames
   47511         ** may have been appended to the log before READ_LOCK(0) was obtained.
   47512         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   47513         ** which implies that the database file contains a trustworthy
   47514         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
   47515         ** happening, this is usually correct.
   47516         **
   47517         ** However, if frames have been appended to the log (or if the log
   47518         ** is wrapped and written for that matter) before the READ_LOCK(0)
   47519         ** is obtained, that is not necessarily true. A checkpointer may
   47520         ** have started to backfill the appended frames but crashed before
   47521         ** it finished. Leaving a corrupt image in the database file.
   47522         */
   47523         walUnlockShared(pWal, WAL_READ_LOCK(0));
   47524         return WAL_RETRY;
   47525       }
   47526       pWal->readLock = 0;
   47527       return SQLITE_OK;
   47528     }else if( rc!=SQLITE_BUSY ){
   47529       return rc;
   47530     }
   47531   }
   47532 
   47533   /* If we get this far, it means that the reader will want to use
   47534   ** the WAL to get at content from recent commits.  The job now is
   47535   ** to select one of the aReadMark[] entries that is closest to
   47536   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   47537   */
   47538   mxReadMark = 0;
   47539   mxI = 0;
   47540   for(i=1; i<WAL_NREADER; i++){
   47541     u32 thisMark = pInfo->aReadMark[i];
   47542     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
   47543       assert( thisMark!=READMARK_NOT_USED );
   47544       mxReadMark = thisMark;
   47545       mxI = i;
   47546     }
   47547   }
   47548   /* There was once an "if" here. The extra "{" is to preserve indentation. */
   47549   {
   47550     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   47551      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
   47552     ){
   47553       for(i=1; i<WAL_NREADER; i++){
   47554         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47555         if( rc==SQLITE_OK ){
   47556           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
   47557           mxI = i;
   47558           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47559           break;
   47560         }else if( rc!=SQLITE_BUSY ){
   47561           return rc;
   47562         }
   47563       }
   47564     }
   47565     if( mxI==0 ){
   47566       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
   47567       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
   47568     }
   47569 
   47570     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   47571     if( rc ){
   47572       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   47573     }
   47574     /* Now that the read-lock has been obtained, check that neither the
   47575     ** value in the aReadMark[] array or the contents of the wal-index
   47576     ** header have changed.
   47577     **
   47578     ** It is necessary to check that the wal-index header did not change
   47579     ** between the time it was read and when the shared-lock was obtained
   47580     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   47581     ** that the log file may have been wrapped by a writer, or that frames
   47582     ** that occur later in the log than pWal->hdr.mxFrame may have been
   47583     ** copied into the database by a checkpointer. If either of these things
   47584     ** happened, then reading the database with the current value of
   47585     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   47586     ** instead.
   47587     **
   47588     ** This does not guarantee that the copy of the wal-index header is up to
   47589     ** date before proceeding. That would not be possible without somehow
   47590     ** blocking writers. It only guarantees that a dangerous checkpoint or
   47591     ** log-wrap (either of which would require an exclusive lock on
   47592     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
   47593     */
   47594     walShmBarrier(pWal);
   47595     if( pInfo->aReadMark[mxI]!=mxReadMark
   47596      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   47597     ){
   47598       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   47599       return WAL_RETRY;
   47600     }else{
   47601       assert( mxReadMark<=pWal->hdr.mxFrame );
   47602       pWal->readLock = (i16)mxI;
   47603     }
   47604   }
   47605   return rc;
   47606 }
   47607 
   47608 /*
   47609 ** Begin a read transaction on the database.
   47610 **
   47611 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   47612 ** it takes a snapshot of the state of the WAL and wal-index for the current
   47613 ** instant in time.  The current thread will continue to use this snapshot.
   47614 ** Other threads might append new content to the WAL and wal-index but
   47615 ** that extra content is ignored by the current thread.
   47616 **
   47617 ** If the database contents have changes since the previous read
   47618 ** transaction, then *pChanged is set to 1 before returning.  The
   47619 ** Pager layer will use this to know that is cache is stale and
   47620 ** needs to be flushed.
   47621 */
   47622 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   47623   int rc;                         /* Return code */
   47624   int cnt = 0;                    /* Number of TryBeginRead attempts */
   47625 
   47626   do{
   47627     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   47628   }while( rc==WAL_RETRY );
   47629   testcase( (rc&0xff)==SQLITE_BUSY );
   47630   testcase( (rc&0xff)==SQLITE_IOERR );
   47631   testcase( rc==SQLITE_PROTOCOL );
   47632   testcase( rc==SQLITE_OK );
   47633   return rc;
   47634 }
   47635 
   47636 /*
   47637 ** Finish with a read transaction.  All this does is release the
   47638 ** read-lock.
   47639 */
   47640 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   47641   sqlite3WalEndWriteTransaction(pWal);
   47642   if( pWal->readLock>=0 ){
   47643     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   47644     pWal->readLock = -1;
   47645   }
   47646 }
   47647 
   47648 /*
   47649 ** Read a page from the WAL, if it is present in the WAL and if the
   47650 ** current read transaction is configured to use the WAL.
   47651 **
   47652 ** The *pInWal is set to 1 if the requested page is in the WAL and
   47653 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
   47654 ** the WAL and needs to be read out of the database.
   47655 */
   47656 SQLITE_PRIVATE int sqlite3WalRead(
   47657   Wal *pWal,                      /* WAL handle */
   47658   Pgno pgno,                      /* Database page number to read data for */
   47659   int *pInWal,                    /* OUT: True if data is read from WAL */
   47660   int nOut,                       /* Size of buffer pOut in bytes */
   47661   u8 *pOut                        /* Buffer to write page data to */
   47662 ){
   47663   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   47664   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   47665   int iHash;                      /* Used to loop through N hash tables */
   47666 
   47667   /* This routine is only be called from within a read transaction. */
   47668   assert( pWal->readLock>=0 || pWal->lockError );
   47669 
   47670   /* If the "last page" field of the wal-index header snapshot is 0, then
   47671   ** no data will be read from the wal under any circumstances. Return early
   47672   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   47673   ** then the WAL is ignored by the reader so return early, as if the
   47674   ** WAL were empty.
   47675   */
   47676   if( iLast==0 || pWal->readLock==0 ){
   47677     *pInWal = 0;
   47678     return SQLITE_OK;
   47679   }
   47680 
   47681   /* Search the hash table or tables for an entry matching page number
   47682   ** pgno. Each iteration of the following for() loop searches one
   47683   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   47684   **
   47685   ** This code might run concurrently to the code in walIndexAppend()
   47686   ** that adds entries to the wal-index (and possibly to this hash
   47687   ** table). This means the value just read from the hash
   47688   ** slot (aHash[iKey]) may have been added before or after the
   47689   ** current read transaction was opened. Values added after the
   47690   ** read transaction was opened may have been written incorrectly -
   47691   ** i.e. these slots may contain garbage data. However, we assume
   47692   ** that any slots written before the current read transaction was
   47693   ** opened remain unmodified.
   47694   **
   47695   ** For the reasons above, the if(...) condition featured in the inner
   47696   ** loop of the following block is more stringent that would be required
   47697   ** if we had exclusive access to the hash-table:
   47698   **
   47699   **   (aPgno[iFrame]==pgno):
   47700   **     This condition filters out normal hash-table collisions.
   47701   **
   47702   **   (iFrame<=iLast):
   47703   **     This condition filters out entries that were added to the hash
   47704   **     table after the current read-transaction had started.
   47705   */
   47706   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
   47707     volatile ht_slot *aHash;      /* Pointer to hash table */
   47708     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   47709     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   47710     int iKey;                     /* Hash slot index */
   47711     int nCollide;                 /* Number of hash collisions remaining */
   47712     int rc;                       /* Error code */
   47713 
   47714     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   47715     if( rc!=SQLITE_OK ){
   47716       return rc;
   47717     }
   47718     nCollide = HASHTABLE_NSLOT;
   47719     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   47720       u32 iFrame = aHash[iKey] + iZero;
   47721       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
   47722         /* assert( iFrame>iRead ); -- not true if there is corruption */
   47723         iRead = iFrame;
   47724       }
   47725       if( (nCollide--)==0 ){
   47726         return SQLITE_CORRUPT_BKPT;
   47727       }
   47728     }
   47729   }
   47730 
   47731 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   47732   /* If expensive assert() statements are available, do a linear search
   47733   ** of the wal-index file content. Make sure the results agree with the
   47734   ** result obtained using the hash indexes above.  */
   47735   {
   47736     u32 iRead2 = 0;
   47737     u32 iTest;
   47738     for(iTest=iLast; iTest>0; iTest--){
   47739       if( walFramePgno(pWal, iTest)==pgno ){
   47740         iRead2 = iTest;
   47741         break;
   47742       }
   47743     }
   47744     assert( iRead==iRead2 );
   47745   }
   47746 #endif
   47747 
   47748   /* If iRead is non-zero, then it is the log frame number that contains the
   47749   ** required page. Read and return data from the log file.
   47750   */
   47751   if( iRead ){
   47752     int sz;
   47753     i64 iOffset;
   47754     sz = pWal->hdr.szPage;
   47755     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
   47756     testcase( sz<=32768 );
   47757     testcase( sz>=65536 );
   47758     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   47759     *pInWal = 1;
   47760     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   47761     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
   47762   }
   47763 
   47764   *pInWal = 0;
   47765   return SQLITE_OK;
   47766 }
   47767 
   47768 
   47769 /*
   47770 ** Return the size of the database in pages (or zero, if unknown).
   47771 */
   47772 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   47773   if( pWal && ALWAYS(pWal->readLock>=0) ){
   47774     return pWal->hdr.nPage;
   47775   }
   47776   return 0;
   47777 }
   47778 
   47779 
   47780 /*
   47781 ** This function starts a write transaction on the WAL.
   47782 **
   47783 ** A read transaction must have already been started by a prior call
   47784 ** to sqlite3WalBeginReadTransaction().
   47785 **
   47786 ** If another thread or process has written into the database since
   47787 ** the read transaction was started, then it is not possible for this
   47788 ** thread to write as doing so would cause a fork.  So this routine
   47789 ** returns SQLITE_BUSY in that case and no write transaction is started.
   47790 **
   47791 ** There can only be a single writer active at a time.
   47792 */
   47793 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   47794   int rc;
   47795 
   47796   /* Cannot start a write transaction without first holding a read
   47797   ** transaction. */
   47798   assert( pWal->readLock>=0 );
   47799 
   47800   if( pWal->readOnly ){
   47801     return SQLITE_READONLY;
   47802   }
   47803 
   47804   /* Only one writer allowed at a time.  Get the write lock.  Return
   47805   ** SQLITE_BUSY if unable.
   47806   */
   47807   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47808   if( rc ){
   47809     return rc;
   47810   }
   47811   pWal->writeLock = 1;
   47812 
   47813   /* If another connection has written to the database file since the
   47814   ** time the read transaction on this connection was started, then
   47815   ** the write is disallowed.
   47816   */
   47817   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   47818     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47819     pWal->writeLock = 0;
   47820     rc = SQLITE_BUSY;
   47821   }
   47822 
   47823   return rc;
   47824 }
   47825 
   47826 /*
   47827 ** End a write transaction.  The commit has already been done.  This
   47828 ** routine merely releases the lock.
   47829 */
   47830 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   47831   if( pWal->writeLock ){
   47832     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47833     pWal->writeLock = 0;
   47834     pWal->truncateOnCommit = 0;
   47835   }
   47836   return SQLITE_OK;
   47837 }
   47838 
   47839 /*
   47840 ** If any data has been written (but not committed) to the log file, this
   47841 ** function moves the write-pointer back to the start of the transaction.
   47842 **
   47843 ** Additionally, the callback function is invoked for each frame written
   47844 ** to the WAL since the start of the transaction. If the callback returns
   47845 ** other than SQLITE_OK, it is not invoked again and the error code is
   47846 ** returned to the caller.
   47847 **
   47848 ** Otherwise, if the callback function does not return an error, this
   47849 ** function returns SQLITE_OK.
   47850 */
   47851 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   47852   int rc = SQLITE_OK;
   47853   if( ALWAYS(pWal->writeLock) ){
   47854     Pgno iMax = pWal->hdr.mxFrame;
   47855     Pgno iFrame;
   47856 
   47857     /* Restore the clients cache of the wal-index header to the state it
   47858     ** was in before the client began writing to the database.
   47859     */
   47860     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   47861 
   47862     for(iFrame=pWal->hdr.mxFrame+1;
   47863         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   47864         iFrame++
   47865     ){
   47866       /* This call cannot fail. Unless the page for which the page number
   47867       ** is passed as the second argument is (a) in the cache and
   47868       ** (b) has an outstanding reference, then xUndo is either a no-op
   47869       ** (if (a) is false) or simply expels the page from the cache (if (b)
   47870       ** is false).
   47871       **
   47872       ** If the upper layer is doing a rollback, it is guaranteed that there
   47873       ** are no outstanding references to any page other than page 1. And
   47874       ** page 1 is never written to the log until the transaction is
   47875       ** committed. As a result, the call to xUndo may not fail.
   47876       */
   47877       assert( walFramePgno(pWal, iFrame)!=1 );
   47878       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   47879     }
   47880     walCleanupHash(pWal);
   47881   }
   47882   assert( rc==SQLITE_OK );
   47883   return rc;
   47884 }
   47885 
   47886 /*
   47887 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   47888 ** values. This function populates the array with values required to
   47889 ** "rollback" the write position of the WAL handle back to the current
   47890 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   47891 */
   47892 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   47893   assert( pWal->writeLock );
   47894   aWalData[0] = pWal->hdr.mxFrame;
   47895   aWalData[1] = pWal->hdr.aFrameCksum[0];
   47896   aWalData[2] = pWal->hdr.aFrameCksum[1];
   47897   aWalData[3] = pWal->nCkpt;
   47898 }
   47899 
   47900 /*
   47901 ** Move the write position of the WAL back to the point identified by
   47902 ** the values in the aWalData[] array. aWalData must point to an array
   47903 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   47904 ** by a call to WalSavepoint().
   47905 */
   47906 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   47907   int rc = SQLITE_OK;
   47908 
   47909   assert( pWal->writeLock );
   47910   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   47911 
   47912   if( aWalData[3]!=pWal->nCkpt ){
   47913     /* This savepoint was opened immediately after the write-transaction
   47914     ** was started. Right after that, the writer decided to wrap around
   47915     ** to the start of the log. Update the savepoint values to match.
   47916     */
   47917     aWalData[0] = 0;
   47918     aWalData[3] = pWal->nCkpt;
   47919   }
   47920 
   47921   if( aWalData[0]<pWal->hdr.mxFrame ){
   47922     pWal->hdr.mxFrame = aWalData[0];
   47923     pWal->hdr.aFrameCksum[0] = aWalData[1];
   47924     pWal->hdr.aFrameCksum[1] = aWalData[2];
   47925     walCleanupHash(pWal);
   47926   }
   47927 
   47928   return rc;
   47929 }
   47930 
   47931 
   47932 /*
   47933 ** This function is called just before writing a set of frames to the log
   47934 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   47935 ** to the current log file, it is possible to overwrite the start of the
   47936 ** existing log file with the new frames (i.e. "reset" the log). If so,
   47937 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   47938 ** unchanged.
   47939 **
   47940 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   47941 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   47942 ** if an error occurs.
   47943 */
   47944 static int walRestartLog(Wal *pWal){
   47945   int rc = SQLITE_OK;
   47946   int cnt;
   47947 
   47948   if( pWal->readLock==0 ){
   47949     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   47950     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   47951     if( pInfo->nBackfill>0 ){
   47952       u32 salt1;
   47953       sqlite3_randomness(4, &salt1);
   47954       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47955       if( rc==SQLITE_OK ){
   47956         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   47957         ** readers are currently using the WAL), then the transactions
   47958         ** frames will overwrite the start of the existing log. Update the
   47959         ** wal-index header to reflect this.
   47960         **
   47961         ** In theory it would be Ok to update the cache of the header only
   47962         ** at this point. But updating the actual wal-index header is also
   47963         ** safe and means there is no special case for sqlite3WalUndo()
   47964         ** to handle if this transaction is rolled back.
   47965         */
   47966         int i;                    /* Loop counter */
   47967         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
   47968 
   47969         pWal->nCkpt++;
   47970         pWal->hdr.mxFrame = 0;
   47971         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   47972         aSalt[1] = salt1;
   47973         walIndexWriteHdr(pWal);
   47974         pInfo->nBackfill = 0;
   47975         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   47976         assert( pInfo->aReadMark[0]==0 );
   47977         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47978       }else if( rc!=SQLITE_BUSY ){
   47979         return rc;
   47980       }
   47981     }
   47982     walUnlockShared(pWal, WAL_READ_LOCK(0));
   47983     pWal->readLock = -1;
   47984     cnt = 0;
   47985     do{
   47986       int notUsed;
   47987       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   47988     }while( rc==WAL_RETRY );
   47989     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   47990     testcase( (rc&0xff)==SQLITE_IOERR );
   47991     testcase( rc==SQLITE_PROTOCOL );
   47992     testcase( rc==SQLITE_OK );
   47993   }
   47994   return rc;
   47995 }
   47996 
   47997 /*
   47998 ** Information about the current state of the WAL file and where
   47999 ** the next fsync should occur - passed from sqlite3WalFrames() into
   48000 ** walWriteToLog().
   48001 */
   48002 typedef struct WalWriter {
   48003   Wal *pWal;                   /* The complete WAL information */
   48004   sqlite3_file *pFd;           /* The WAL file to which we write */
   48005   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
   48006   int syncFlags;               /* Flags for the fsync */
   48007   int szPage;                  /* Size of one page */
   48008 } WalWriter;
   48009 
   48010 /*
   48011 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
   48012 ** Do a sync when crossing the p->iSyncPoint boundary.
   48013 **
   48014 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
   48015 ** first write the part before iSyncPoint, then sync, then write the
   48016 ** rest.
   48017 */
   48018 static int walWriteToLog(
   48019   WalWriter *p,              /* WAL to write to */
   48020   void *pContent,            /* Content to be written */
   48021   int iAmt,                  /* Number of bytes to write */
   48022   sqlite3_int64 iOffset      /* Start writing at this offset */
   48023 ){
   48024   int rc;
   48025   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
   48026     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
   48027     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
   48028     if( rc ) return rc;
   48029     iOffset += iFirstAmt;
   48030     iAmt -= iFirstAmt;
   48031     pContent = (void*)(iFirstAmt + (char*)pContent);
   48032     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
   48033     rc = sqlite3OsSync(p->pFd, p->syncFlags);
   48034     if( iAmt==0 || rc ) return rc;
   48035   }
   48036   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
   48037   return rc;
   48038 }
   48039 
   48040 /*
   48041 ** Write out a single frame of the WAL
   48042 */
   48043 static int walWriteOneFrame(
   48044   WalWriter *p,               /* Where to write the frame */
   48045   PgHdr *pPage,               /* The page of the frame to be written */
   48046   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
   48047   sqlite3_int64 iOffset       /* Byte offset at which to write */
   48048 ){
   48049   int rc;                         /* Result code from subfunctions */
   48050   void *pData;                    /* Data actually written */
   48051   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   48052 #if defined(SQLITE_HAS_CODEC)
   48053   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
   48054 #else
   48055   pData = pPage->pData;
   48056 #endif
   48057   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   48058   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   48059   if( rc ) return rc;
   48060   /* Write the page data */
   48061   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
   48062   return rc;
   48063 }
   48064 
   48065 /*
   48066 ** Write a set of frames to the log. The caller must hold the write-lock
   48067 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   48068 */
   48069 SQLITE_PRIVATE int sqlite3WalFrames(
   48070   Wal *pWal,                      /* Wal handle to write to */
   48071   int szPage,                     /* Database page-size in bytes */
   48072   PgHdr *pList,                   /* List of dirty pages to write */
   48073   Pgno nTruncate,                 /* Database size after this commit */
   48074   int isCommit,                   /* True if this is a commit */
   48075   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   48076 ){
   48077   int rc;                         /* Used to catch return codes */
   48078   u32 iFrame;                     /* Next frame address */
   48079   PgHdr *p;                       /* Iterator to run through pList with. */
   48080   PgHdr *pLast = 0;               /* Last frame in list */
   48081   int nExtra = 0;                 /* Number of extra copies of last page */
   48082   int szFrame;                    /* The size of a single frame */
   48083   i64 iOffset;                    /* Next byte to write in WAL file */
   48084   WalWriter w;                    /* The writer */
   48085 
   48086   assert( pList );
   48087   assert( pWal->writeLock );
   48088 
   48089   /* If this frame set completes a transaction, then nTruncate>0.  If
   48090   ** nTruncate==0 then this frame set does not complete the transaction. */
   48091   assert( (isCommit!=0)==(nTruncate!=0) );
   48092 
   48093 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   48094   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   48095     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   48096               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   48097   }
   48098 #endif
   48099 
   48100   /* See if it is possible to write these frames into the start of the
   48101   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   48102   */
   48103   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   48104     return rc;
   48105   }
   48106 
   48107   /* If this is the first frame written into the log, write the WAL
   48108   ** header to the start of the WAL file. See comments at the top of
   48109   ** this source file for a description of the WAL header format.
   48110   */
   48111   iFrame = pWal->hdr.mxFrame;
   48112   if( iFrame==0 ){
   48113     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   48114     u32 aCksum[2];                /* Checksum for wal-header */
   48115 
   48116     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   48117     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   48118     sqlite3Put4byte(&aWalHdr[8], szPage);
   48119     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   48120     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
   48121     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   48122     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   48123     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   48124     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   48125 
   48126     pWal->szPage = szPage;
   48127     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   48128     pWal->hdr.aFrameCksum[0] = aCksum[0];
   48129     pWal->hdr.aFrameCksum[1] = aCksum[1];
   48130     pWal->truncateOnCommit = 1;
   48131 
   48132     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   48133     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   48134     if( rc!=SQLITE_OK ){
   48135       return rc;
   48136     }
   48137 
   48138     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
   48139     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
   48140     ** an out-of-order write following a WAL restart could result in
   48141     ** database corruption.  See the ticket:
   48142     **
   48143     **     http://localhost:591/sqlite/info/ff5be73dee
   48144     */
   48145     if( pWal->syncHeader && sync_flags ){
   48146       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
   48147       if( rc ) return rc;
   48148     }
   48149   }
   48150   assert( (int)pWal->szPage==szPage );
   48151 
   48152   /* Setup information needed to write frames into the WAL */
   48153   w.pWal = pWal;
   48154   w.pFd = pWal->pWalFd;
   48155   w.iSyncPoint = 0;
   48156   w.syncFlags = sync_flags;
   48157   w.szPage = szPage;
   48158   iOffset = walFrameOffset(iFrame+1, szPage);
   48159   szFrame = szPage + WAL_FRAME_HDRSIZE;
   48160 
   48161   /* Write all frames into the log file exactly once */
   48162   for(p=pList; p; p=p->pDirty){
   48163     int nDbSize;   /* 0 normally.  Positive == commit flag */
   48164     iFrame++;
   48165     assert( iOffset==walFrameOffset(iFrame, szPage) );
   48166     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   48167     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
   48168     if( rc ) return rc;
   48169     pLast = p;
   48170     iOffset += szFrame;
   48171   }
   48172 
   48173   /* If this is the end of a transaction, then we might need to pad
   48174   ** the transaction and/or sync the WAL file.
   48175   **
   48176   ** Padding and syncing only occur if this set of frames complete a
   48177   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
   48178   ** or synchonous==OFF, then no padding or syncing are needed.
   48179   **
   48180   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
   48181   ** needed and only the sync is done.  If padding is needed, then the
   48182   ** final frame is repeated (with its commit mark) until the next sector
   48183   ** boundary is crossed.  Only the part of the WAL prior to the last
   48184   ** sector boundary is synced; the part of the last frame that extends
   48185   ** past the sector boundary is written after the sync.
   48186   */
   48187   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
   48188     if( pWal->padToSectorBoundary ){
   48189       int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
   48190       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
   48191       while( iOffset<w.iSyncPoint ){
   48192         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
   48193         if( rc ) return rc;
   48194         iOffset += szFrame;
   48195         nExtra++;
   48196       }
   48197     }else{
   48198       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
   48199     }
   48200   }
   48201 
   48202   /* If this frame set completes the first transaction in the WAL and
   48203   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
   48204   ** journal size limit, if possible.
   48205   */
   48206   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
   48207     i64 sz = pWal->mxWalSize;
   48208     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
   48209       sz = walFrameOffset(iFrame+nExtra+1, szPage);
   48210     }
   48211     walLimitSize(pWal, sz);
   48212     pWal->truncateOnCommit = 0;
   48213   }
   48214 
   48215   /* Append data to the wal-index. It is not necessary to lock the
   48216   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   48217   ** guarantees that there are no other writers, and no data that may
   48218   ** be in use by existing readers is being overwritten.
   48219   */
   48220   iFrame = pWal->hdr.mxFrame;
   48221   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   48222     iFrame++;
   48223     rc = walIndexAppend(pWal, iFrame, p->pgno);
   48224   }
   48225   while( rc==SQLITE_OK && nExtra>0 ){
   48226     iFrame++;
   48227     nExtra--;
   48228     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   48229   }
   48230 
   48231   if( rc==SQLITE_OK ){
   48232     /* Update the private copy of the header. */
   48233     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   48234     testcase( szPage<=32768 );
   48235     testcase( szPage>=65536 );
   48236     pWal->hdr.mxFrame = iFrame;
   48237     if( isCommit ){
   48238       pWal->hdr.iChange++;
   48239       pWal->hdr.nPage = nTruncate;
   48240     }
   48241     /* If this is a commit, update the wal-index header too. */
   48242     if( isCommit ){
   48243       walIndexWriteHdr(pWal);
   48244       pWal->iCallback = iFrame;
   48245     }
   48246   }
   48247 
   48248   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   48249   return rc;
   48250 }
   48251 
   48252 /*
   48253 ** This routine is called to implement sqlite3_wal_checkpoint() and
   48254 ** related interfaces.
   48255 **
   48256 ** Obtain a CHECKPOINT lock and then backfill as much information as
   48257 ** we can from WAL into the database.
   48258 **
   48259 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
   48260 ** callback. In this case this function runs a blocking checkpoint.
   48261 */
   48262 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   48263   Wal *pWal,                      /* Wal connection */
   48264   int eMode,                      /* PASSIVE, FULL or RESTART */
   48265   int (*xBusy)(void*),            /* Function to call when busy */
   48266   void *pBusyArg,                 /* Context argument for xBusyHandler */
   48267   int sync_flags,                 /* Flags to sync db file with (or 0) */
   48268   int nBuf,                       /* Size of temporary buffer */
   48269   u8 *zBuf,                       /* Temporary buffer to use */
   48270   int *pnLog,                     /* OUT: Number of frames in WAL */
   48271   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   48272 ){
   48273   int rc;                         /* Return code */
   48274   int isChanged = 0;              /* True if a new wal-index header is loaded */
   48275   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
   48276 
   48277   assert( pWal->ckptLock==0 );
   48278   assert( pWal->writeLock==0 );
   48279 
   48280   if( pWal->readOnly ) return SQLITE_READONLY;
   48281   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   48282   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   48283   if( rc ){
   48284     /* Usually this is SQLITE_BUSY meaning that another thread or process
   48285     ** is already running a checkpoint, or maybe a recovery.  But it might
   48286     ** also be SQLITE_IOERR. */
   48287     return rc;
   48288   }
   48289   pWal->ckptLock = 1;
   48290 
   48291   /* If this is a blocking-checkpoint, then obtain the write-lock as well
   48292   ** to prevent any writers from running while the checkpoint is underway.
   48293   ** This has to be done before the call to walIndexReadHdr() below.
   48294   **
   48295   ** If the writer lock cannot be obtained, then a passive checkpoint is
   48296   ** run instead. Since the checkpointer is not holding the writer lock,
   48297   ** there is no point in blocking waiting for any readers. Assuming no
   48298   ** other error occurs, this function will return SQLITE_BUSY to the caller.
   48299   */
   48300   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   48301     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
   48302     if( rc==SQLITE_OK ){
   48303       pWal->writeLock = 1;
   48304     }else if( rc==SQLITE_BUSY ){
   48305       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
   48306       rc = SQLITE_OK;
   48307     }
   48308   }
   48309 
   48310   /* Read the wal-index header. */
   48311   if( rc==SQLITE_OK ){
   48312     rc = walIndexReadHdr(pWal, &isChanged);
   48313   }
   48314 
   48315   /* Copy data from the log to the database file. */
   48316   if( rc==SQLITE_OK ){
   48317     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
   48318       rc = SQLITE_CORRUPT_BKPT;
   48319     }else{
   48320       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
   48321     }
   48322 
   48323     /* If no error occurred, set the output variables. */
   48324     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
   48325       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
   48326       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
   48327     }
   48328   }
   48329 
   48330   if( isChanged ){
   48331     /* If a new wal-index header was loaded before the checkpoint was
   48332     ** performed, then the pager-cache associated with pWal is now
   48333     ** out of date. So zero the cached wal-index header to ensure that
   48334     ** next time the pager opens a snapshot on this database it knows that
   48335     ** the cache needs to be reset.
   48336     */
   48337     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   48338   }
   48339 
   48340   /* Release the locks. */
   48341   sqlite3WalEndWriteTransaction(pWal);
   48342   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   48343   pWal->ckptLock = 0;
   48344   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   48345   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
   48346 }
   48347 
   48348 /* Return the value to pass to a sqlite3_wal_hook callback, the
   48349 ** number of frames in the WAL at the point of the last commit since
   48350 ** sqlite3WalCallback() was called.  If no commits have occurred since
   48351 ** the last call, then return 0.
   48352 */
   48353 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   48354   u32 ret = 0;
   48355   if( pWal ){
   48356     ret = pWal->iCallback;
   48357     pWal->iCallback = 0;
   48358   }
   48359   return (int)ret;
   48360 }
   48361 
   48362 /*
   48363 ** This function is called to change the WAL subsystem into or out
   48364 ** of locking_mode=EXCLUSIVE.
   48365 **
   48366 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   48367 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   48368 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   48369 ** or if the acquisition of the lock fails, then return 0.  If the
   48370 ** transition out of exclusive-mode is successful, return 1.  This
   48371 ** operation must occur while the pager is still holding the exclusive
   48372 ** lock on the main database file.
   48373 **
   48374 ** If op is one, then change from locking_mode=NORMAL into
   48375 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   48376 ** be released.  Return 1 if the transition is made and 0 if the
   48377 ** WAL is already in exclusive-locking mode - meaning that this
   48378 ** routine is a no-op.  The pager must already hold the exclusive lock
   48379 ** on the main database file before invoking this operation.
   48380 **
   48381 ** If op is negative, then do a dry-run of the op==1 case but do
   48382 ** not actually change anything. The pager uses this to see if it
   48383 ** should acquire the database exclusive lock prior to invoking
   48384 ** the op==1 case.
   48385 */
   48386 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   48387   int rc;
   48388   assert( pWal->writeLock==0 );
   48389   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   48390 
   48391   /* pWal->readLock is usually set, but might be -1 if there was a
   48392   ** prior error while attempting to acquire are read-lock. This cannot
   48393   ** happen if the connection is actually in exclusive mode (as no xShmLock
   48394   ** locks are taken in this case). Nor should the pager attempt to
   48395   ** upgrade to exclusive-mode following such an error.
   48396   */
   48397   assert( pWal->readLock>=0 || pWal->lockError );
   48398   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   48399 
   48400   if( op==0 ){
   48401     if( pWal->exclusiveMode ){
   48402       pWal->exclusiveMode = 0;
   48403       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   48404         pWal->exclusiveMode = 1;
   48405       }
   48406       rc = pWal->exclusiveMode==0;
   48407     }else{
   48408       /* Already in locking_mode=NORMAL */
   48409       rc = 0;
   48410     }
   48411   }else if( op>0 ){
   48412     assert( pWal->exclusiveMode==0 );
   48413     assert( pWal->readLock>=0 );
   48414     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   48415     pWal->exclusiveMode = 1;
   48416     rc = 1;
   48417   }else{
   48418     rc = pWal->exclusiveMode==0;
   48419   }
   48420   return rc;
   48421 }
   48422 
   48423 /*
   48424 ** Return true if the argument is non-NULL and the WAL module is using
   48425 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   48426 ** WAL module is using shared-memory, return false.
   48427 */
   48428 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   48429   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   48430 }
   48431 
   48432 #ifdef SQLITE_ENABLE_ZIPVFS
   48433 /*
   48434 ** If the argument is not NULL, it points to a Wal object that holds a
   48435 ** read-lock. This function returns the database page-size if it is known,
   48436 ** or zero if it is not (or if pWal is NULL).
   48437 */
   48438 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
   48439   assert( pWal==0 || pWal->readLock>=0 );
   48440   return (pWal ? pWal->szPage : 0);
   48441 }
   48442 #endif
   48443 
   48444 #endif /* #ifndef SQLITE_OMIT_WAL */
   48445 
   48446 /************** End of wal.c *************************************************/
   48447 /************** Begin file btmutex.c *****************************************/
   48448 /*
   48449 ** 2007 August 27
   48450 **
   48451 ** The author disclaims copyright to this source code.  In place of
   48452 ** a legal notice, here is a blessing:
   48453 **
   48454 **    May you do good and not evil.
   48455 **    May you find forgiveness for yourself and forgive others.
   48456 **    May you share freely, never taking more than you give.
   48457 **
   48458 *************************************************************************
   48459 **
   48460 ** This file contains code used to implement mutexes on Btree objects.
   48461 ** This code really belongs in btree.c.  But btree.c is getting too
   48462 ** big and we want to break it down some.  This packaged seemed like
   48463 ** a good breakout.
   48464 */
   48465 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   48466 /************** Begin file btreeInt.h ****************************************/
   48467 /*
   48468 ** 2004 April 6
   48469 **
   48470 ** The author disclaims copyright to this source code.  In place of
   48471 ** a legal notice, here is a blessing:
   48472 **
   48473 **    May you do good and not evil.
   48474 **    May you find forgiveness for yourself and forgive others.
   48475 **    May you share freely, never taking more than you give.
   48476 **
   48477 *************************************************************************
   48478 ** This file implements a external (disk-based) database using BTrees.
   48479 ** For a detailed discussion of BTrees, refer to
   48480 **
   48481 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   48482 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   48483 **     Publishing Company, Reading, Massachusetts.
   48484 **
   48485 ** The basic idea is that each page of the file contains N database
   48486 ** entries and N+1 pointers to subpages.
   48487 **
   48488 **   ----------------------------------------------------------------
   48489 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   48490 **   ----------------------------------------------------------------
   48491 **
   48492 ** All of the keys on the page that Ptr(0) points to have values less
   48493 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   48494 ** values greater than Key(0) and less than Key(1).  All of the keys
   48495 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   48496 ** so forth.
   48497 **
   48498 ** Finding a particular key requires reading O(log(M)) pages from the
   48499 ** disk where M is the number of entries in the tree.
   48500 **
   48501 ** In this implementation, a single file can hold one or more separate
   48502 ** BTrees.  Each BTree is identified by the index of its root page.  The
   48503 ** key and data for any entry are combined to form the "payload".  A
   48504 ** fixed amount of payload can be carried directly on the database
   48505 ** page.  If the payload is larger than the preset amount then surplus
   48506 ** bytes are stored on overflow pages.  The payload for an entry
   48507 ** and the preceding pointer are combined to form a "Cell".  Each
   48508 ** page has a small header which contains the Ptr(N) pointer and other
   48509 ** information such as the size of key and data.
   48510 **
   48511 ** FORMAT DETAILS
   48512 **
   48513 ** The file is divided into pages.  The first page is called page 1,
   48514 ** the second is page 2, and so forth.  A page number of zero indicates
   48515 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   48516 ** Each page can be either a btree page, a freelist page, an overflow
   48517 ** page, or a pointer-map page.
   48518 **
   48519 ** The first page is always a btree page.  The first 100 bytes of the first
   48520 ** page contain a special header (the "file header") that describes the file.
   48521 ** The format of the file header is as follows:
   48522 **
   48523 **   OFFSET   SIZE    DESCRIPTION
   48524 **      0      16     Header string: "SQLite format 3\000"
   48525 **     16       2     Page size in bytes.
   48526 **     18       1     File format write version
   48527 **     19       1     File format read version
   48528 **     20       1     Bytes of unused space at the end of each page
   48529 **     21       1     Max embedded payload fraction
   48530 **     22       1     Min embedded payload fraction
   48531 **     23       1     Min leaf payload fraction
   48532 **     24       4     File change counter
   48533 **     28       4     Reserved for future use
   48534 **     32       4     First freelist page
   48535 **     36       4     Number of freelist pages in the file
   48536 **     40      60     15 4-byte meta values passed to higher layers
   48537 **
   48538 **     40       4     Schema cookie
   48539 **     44       4     File format of schema layer
   48540 **     48       4     Size of page cache
   48541 **     52       4     Largest root-page (auto/incr_vacuum)
   48542 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   48543 **     60       4     User version
   48544 **     64       4     Incremental vacuum mode
   48545 **     68       4     unused
   48546 **     72       4     unused
   48547 **     76       4     unused
   48548 **
   48549 ** All of the integer values are big-endian (most significant byte first).
   48550 **
   48551 ** The file change counter is incremented when the database is changed
   48552 ** This counter allows other processes to know when the file has changed
   48553 ** and thus when they need to flush their cache.
   48554 **
   48555 ** The max embedded payload fraction is the amount of the total usable
   48556 ** space in a page that can be consumed by a single cell for standard
   48557 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   48558 ** is to limit the maximum cell size so that at least 4 cells will fit
   48559 ** on one page.  Thus the default max embedded payload fraction is 64.
   48560 **
   48561 ** If the payload for a cell is larger than the max payload, then extra
   48562 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   48563 ** as many bytes as possible are moved into the overflow pages without letting
   48564 ** the cell size drop below the min embedded payload fraction.
   48565 **
   48566 ** The min leaf payload fraction is like the min embedded payload fraction
   48567 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   48568 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   48569 ** not specified in the header.
   48570 **
   48571 ** Each btree pages is divided into three sections:  The header, the
   48572 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   48573 ** file header that occurs before the page header.
   48574 **
   48575 **      |----------------|
   48576 **      | file header    |   100 bytes.  Page 1 only.
   48577 **      |----------------|
   48578 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   48579 **      |----------------|
   48580 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   48581 **      | array          |   |  Grows downward
   48582 **      |                |   v
   48583 **      |----------------|
   48584 **      | unallocated    |
   48585 **      | space          |
   48586 **      |----------------|   ^  Grows upwards
   48587 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   48588 **      | area           |   |  and free space fragments.
   48589 **      |----------------|
   48590 **
   48591 ** The page headers looks like this:
   48592 **
   48593 **   OFFSET   SIZE     DESCRIPTION
   48594 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   48595 **      1       2      byte offset to the first freeblock
   48596 **      3       2      number of cells on this page
   48597 **      5       2      first byte of the cell content area
   48598 **      7       1      number of fragmented free bytes
   48599 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   48600 **
   48601 ** The flags define the format of this btree page.  The leaf flag means that
   48602 ** this page has no children.  The zerodata flag means that this page carries
   48603 ** only keys and no data.  The intkey flag means that the key is a integer
   48604 ** which is stored in the key size entry of the cell header rather than in
   48605 ** the payload area.
   48606 **
   48607 ** The cell pointer array begins on the first byte after the page header.
   48608 ** The cell pointer array contains zero or more 2-byte numbers which are
   48609 ** offsets from the beginning of the page to the cell content in the cell
   48610 ** content area.  The cell pointers occur in sorted order.  The system strives
   48611 ** to keep free space after the last cell pointer so that new cells can
   48612 ** be easily added without having to defragment the page.
   48613 **
   48614 ** Cell content is stored at the very end of the page and grows toward the
   48615 ** beginning of the page.
   48616 **
   48617 ** Unused space within the cell content area is collected into a linked list of
   48618 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   48619 ** to the first freeblock is given in the header.  Freeblocks occur in
   48620 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   48621 ** any group of 3 or fewer unused bytes in the cell content area cannot
   48622 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   48623 ** a fragment.  The total number of bytes in all fragments is recorded.
   48624 ** in the page header at offset 7.
   48625 **
   48626 **    SIZE    DESCRIPTION
   48627 **      2     Byte offset of the next freeblock
   48628 **      2     Bytes in this freeblock
   48629 **
   48630 ** Cells are of variable length.  Cells are stored in the cell content area at
   48631 ** the end of the page.  Pointers to the cells are in the cell pointer array
   48632 ** that immediately follows the page header.  Cells is not necessarily
   48633 ** contiguous or in order, but cell pointers are contiguous and in order.
   48634 **
   48635 ** Cell content makes use of variable length integers.  A variable
   48636 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   48637 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   48638 ** the first byte with bit 8 clear.  The most significant byte of the integer
   48639 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   48640 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   48641 ** allows a 64-bit integer to be encoded in 9 bytes.
   48642 **
   48643 **    0x00                      becomes  0x00000000
   48644 **    0x7f                      becomes  0x0000007f
   48645 **    0x81 0x00                 becomes  0x00000080
   48646 **    0x82 0x00                 becomes  0x00000100
   48647 **    0x80 0x7f                 becomes  0x0000007f
   48648 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   48649 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   48650 **
   48651 ** Variable length integers are used for rowids and to hold the number of
   48652 ** bytes of key and data in a btree cell.
   48653 **
   48654 ** The content of a cell looks like this:
   48655 **
   48656 **    SIZE    DESCRIPTION
   48657 **      4     Page number of the left child. Omitted if leaf flag is set.
   48658 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   48659 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   48660 **      *     Payload
   48661 **      4     First page of the overflow chain.  Omitted if no overflow
   48662 **
   48663 ** Overflow pages form a linked list.  Each page except the last is completely
   48664 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   48665 ** as 1 byte of data.
   48666 **
   48667 **    SIZE    DESCRIPTION
   48668 **      4     Page number of next overflow page
   48669 **      *     Data
   48670 **
   48671 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   48672 ** file header points to the first in a linked list of trunk page.  Each trunk
   48673 ** page points to multiple leaf pages.  The content of a leaf page is
   48674 ** unspecified.  A trunk page looks like this:
   48675 **
   48676 **    SIZE    DESCRIPTION
   48677 **      4     Page number of next trunk page
   48678 **      4     Number of leaf pointers on this page
   48679 **      *     zero or more pages numbers of leaves
   48680 */
   48681 
   48682 
   48683 /* The following value is the maximum cell size assuming a maximum page
   48684 ** size give above.
   48685 */
   48686 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
   48687 
   48688 /* The maximum number of cells on a single page of the database.  This
   48689 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   48690 ** plus 2 bytes for the index to the cell in the page header).  Such
   48691 ** small cells will be rare, but they are possible.
   48692 */
   48693 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   48694 
   48695 /* Forward declarations */
   48696 typedef struct MemPage MemPage;
   48697 typedef struct BtLock BtLock;
   48698 
   48699 /*
   48700 ** This is a magic string that appears at the beginning of every
   48701 ** SQLite database in order to identify the file as a real database.
   48702 **
   48703 ** You can change this value at compile-time by specifying a
   48704 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   48705 ** header must be exactly 16 bytes including the zero-terminator so
   48706 ** the string itself should be 15 characters long.  If you change
   48707 ** the header, then your custom library will not be able to read
   48708 ** databases generated by the standard tools and the standard tools
   48709 ** will not be able to read databases created by your custom library.
   48710 */
   48711 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   48712 #  define SQLITE_FILE_HEADER "SQLite format 3"
   48713 #endif
   48714 
   48715 /*
   48716 ** Page type flags.  An ORed combination of these flags appear as the
   48717 ** first byte of on-disk image of every BTree page.
   48718 */
   48719 #define PTF_INTKEY    0x01
   48720 #define PTF_ZERODATA  0x02
   48721 #define PTF_LEAFDATA  0x04
   48722 #define PTF_LEAF      0x08
   48723 
   48724 /*
   48725 ** As each page of the file is loaded into memory, an instance of the following
   48726 ** structure is appended and initialized to zero.  This structure stores
   48727 ** information about the page that is decoded from the raw file page.
   48728 **
   48729 ** The pParent field points back to the parent page.  This allows us to
   48730 ** walk up the BTree from any leaf to the root.  Care must be taken to
   48731 ** unref() the parent page pointer when this page is no longer referenced.
   48732 ** The pageDestructor() routine handles that chore.
   48733 **
   48734 ** Access to all fields of this structure is controlled by the mutex
   48735 ** stored in MemPage.pBt->mutex.
   48736 */
   48737 struct MemPage {
   48738   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   48739   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   48740   u8 intKey;           /* True if intkey flag is set */
   48741   u8 leaf;             /* True if leaf flag is set */
   48742   u8 hasData;          /* True if this page stores data */
   48743   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   48744   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   48745   u8 max1bytePayload;  /* min(maxLocal,127) */
   48746   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   48747   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   48748   u16 cellOffset;      /* Index in aData of first cell pointer */
   48749   u16 nFree;           /* Number of free bytes on the page */
   48750   u16 nCell;           /* Number of cells on this page, local and ovfl */
   48751   u16 maskPage;        /* Mask for page offset */
   48752   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
   48753                        ** non-overflow cell */
   48754   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
   48755   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   48756   u8 *aData;           /* Pointer to disk image of the page data */
   48757   u8 *aDataEnd;        /* One byte past the end of usable data */
   48758   u8 *aCellIdx;        /* The cell index area */
   48759   DbPage *pDbPage;     /* Pager page handle */
   48760   Pgno pgno;           /* Page number for this page */
   48761 };
   48762 
   48763 /*
   48764 ** The in-memory image of a disk page has the auxiliary information appended
   48765 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   48766 ** that extra information.
   48767 */
   48768 #define EXTRA_SIZE sizeof(MemPage)
   48769 
   48770 /*
   48771 ** A linked list of the following structures is stored at BtShared.pLock.
   48772 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   48773 ** is opened on the table with root page BtShared.iTable. Locks are removed
   48774 ** from this list when a transaction is committed or rolled back, or when
   48775 ** a btree handle is closed.
   48776 */
   48777 struct BtLock {
   48778   Btree *pBtree;        /* Btree handle holding this lock */
   48779   Pgno iTable;          /* Root page of table */
   48780   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   48781   BtLock *pNext;        /* Next in BtShared.pLock list */
   48782 };
   48783 
   48784 /* Candidate values for BtLock.eLock */
   48785 #define READ_LOCK     1
   48786 #define WRITE_LOCK    2
   48787 
   48788 /* A Btree handle
   48789 **
   48790 ** A database connection contains a pointer to an instance of
   48791 ** this object for every database file that it has open.  This structure
   48792 ** is opaque to the database connection.  The database connection cannot
   48793 ** see the internals of this structure and only deals with pointers to
   48794 ** this structure.
   48795 **
   48796 ** For some database files, the same underlying database cache might be
   48797 ** shared between multiple connections.  In that case, each connection
   48798 ** has it own instance of this object.  But each instance of this object
   48799 ** points to the same BtShared object.  The database cache and the
   48800 ** schema associated with the database file are all contained within
   48801 ** the BtShared object.
   48802 **
   48803 ** All fields in this structure are accessed under sqlite3.mutex.
   48804 ** The pBt pointer itself may not be changed while there exists cursors
   48805 ** in the referenced BtShared that point back to this Btree since those
   48806 ** cursors have to go through this Btree to find their BtShared and
   48807 ** they often do so without holding sqlite3.mutex.
   48808 */
   48809 struct Btree {
   48810   sqlite3 *db;       /* The database connection holding this btree */
   48811   BtShared *pBt;     /* Sharable content of this btree */
   48812   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   48813   u8 sharable;       /* True if we can share pBt with another db */
   48814   u8 locked;         /* True if db currently has pBt locked */
   48815   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   48816   int nBackup;       /* Number of backup operations reading this btree */
   48817   Btree *pNext;      /* List of other sharable Btrees from the same db */
   48818   Btree *pPrev;      /* Back pointer of the same list */
   48819 #ifndef SQLITE_OMIT_SHARED_CACHE
   48820   BtLock lock;       /* Object used to lock page 1 */
   48821 #endif
   48822 };
   48823 
   48824 /*
   48825 ** Btree.inTrans may take one of the following values.
   48826 **
   48827 ** If the shared-data extension is enabled, there may be multiple users
   48828 ** of the Btree structure. At most one of these may open a write transaction,
   48829 ** but any number may have active read transactions.
   48830 */
   48831 #define TRANS_NONE  0
   48832 #define TRANS_READ  1
   48833 #define TRANS_WRITE 2
   48834 
   48835 /*
   48836 ** An instance of this object represents a single database file.
   48837 **
   48838 ** A single database file can be in use at the same time by two
   48839 ** or more database connections.  When two or more connections are
   48840 ** sharing the same database file, each connection has it own
   48841 ** private Btree object for the file and each of those Btrees points
   48842 ** to this one BtShared object.  BtShared.nRef is the number of
   48843 ** connections currently sharing this database file.
   48844 **
   48845 ** Fields in this structure are accessed under the BtShared.mutex
   48846 ** mutex, except for nRef and pNext which are accessed under the
   48847 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   48848 ** may not be modified once it is initially set as long as nRef>0.
   48849 ** The pSchema field may be set once under BtShared.mutex and
   48850 ** thereafter is unchanged as long as nRef>0.
   48851 **
   48852 ** isPending:
   48853 **
   48854 **   If a BtShared client fails to obtain a write-lock on a database
   48855 **   table (because there exists one or more read-locks on the table),
   48856 **   the shared-cache enters 'pending-lock' state and isPending is
   48857 **   set to true.
   48858 **
   48859 **   The shared-cache leaves the 'pending lock' state when either of
   48860 **   the following occur:
   48861 **
   48862 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   48863 **     2) The number of locks held by other connections drops to zero.
   48864 **
   48865 **   while in the 'pending-lock' state, no connection may start a new
   48866 **   transaction.
   48867 **
   48868 **   This feature is included to help prevent writer-starvation.
   48869 */
   48870 struct BtShared {
   48871   Pager *pPager;        /* The page cache */
   48872   sqlite3 *db;          /* Database connection currently using this Btree */
   48873   BtCursor *pCursor;    /* A list of all open cursors */
   48874   MemPage *pPage1;      /* First page of the database */
   48875   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   48876 #ifndef SQLITE_OMIT_AUTOVACUUM
   48877   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   48878   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   48879 #endif
   48880   u8 inTransaction;     /* Transaction state */
   48881   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
   48882   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   48883   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   48884   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   48885   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   48886   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   48887   u32 pageSize;         /* Total number of bytes on a page */
   48888   u32 usableSize;       /* Number of usable bytes on each page */
   48889   int nTransaction;     /* Number of open transactions (read + write) */
   48890   u32 nPage;            /* Number of pages in the database */
   48891   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   48892   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   48893   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
   48894   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   48895 #ifndef SQLITE_OMIT_SHARED_CACHE
   48896   int nRef;             /* Number of references to this structure */
   48897   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   48898   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   48899   Btree *pWriter;       /* Btree with currently open write transaction */
   48900 #endif
   48901   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   48902 };
   48903 
   48904 /*
   48905 ** Allowed values for BtShared.btsFlags
   48906 */
   48907 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
   48908 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
   48909 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
   48910 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
   48911 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
   48912 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
   48913 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
   48914 
   48915 /*
   48916 ** An instance of the following structure is used to hold information
   48917 ** about a cell.  The parseCellPtr() function fills in this structure
   48918 ** based on information extract from the raw disk page.
   48919 */
   48920 typedef struct CellInfo CellInfo;
   48921 struct CellInfo {
   48922   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   48923   u8 *pCell;     /* Pointer to the start of cell content */
   48924   u32 nData;     /* Number of bytes of data */
   48925   u32 nPayload;  /* Total amount of payload */
   48926   u16 nHeader;   /* Size of the cell content header in bytes */
   48927   u16 nLocal;    /* Amount of payload held locally */
   48928   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   48929   u16 nSize;     /* Size of the cell content on the main b-tree page */
   48930 };
   48931 
   48932 /*
   48933 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   48934 ** this will be declared corrupt. This value is calculated based on a
   48935 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   48936 ** root-node and 3 for all other internal nodes.
   48937 **
   48938 ** If a tree that appears to be taller than this is encountered, it is
   48939 ** assumed that the database is corrupt.
   48940 */
   48941 #define BTCURSOR_MAX_DEPTH 20
   48942 
   48943 /*
   48944 ** A cursor is a pointer to a particular entry within a particular
   48945 ** b-tree within a database file.
   48946 **
   48947 ** The entry is identified by its MemPage and the index in
   48948 ** MemPage.aCell[] of the entry.
   48949 **
   48950 ** A single database file can be shared by two more database connections,
   48951 ** but cursors cannot be shared.  Each cursor is associated with a
   48952 ** particular database connection identified BtCursor.pBtree.db.
   48953 **
   48954 ** Fields in this structure are accessed under the BtShared.mutex
   48955 ** found at self->pBt->mutex.
   48956 */
   48957 struct BtCursor {
   48958   Btree *pBtree;            /* The Btree to which this cursor belongs */
   48959   BtShared *pBt;            /* The BtShared this cursor points to */
   48960   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   48961   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   48962 #ifndef SQLITE_OMIT_INCRBLOB
   48963   Pgno *aOverflow;          /* Cache of overflow page locations */
   48964 #endif
   48965   Pgno pgnoRoot;            /* The root page of this tree */
   48966   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
   48967   CellInfo info;            /* A parse of the cell we are pointing at */
   48968   i64 nKey;        /* Size of pKey, or last integer key */
   48969   void *pKey;      /* Saved key that was cursor's last known position */
   48970   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   48971   u8 wrFlag;                /* True if writable */
   48972   u8 atLast;                /* Cursor pointing to the last entry */
   48973   u8 validNKey;             /* True if info.nKey is valid */
   48974   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   48975 #ifndef SQLITE_OMIT_INCRBLOB
   48976   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
   48977 #endif
   48978   i16 iPage;                            /* Index of current page in apPage */
   48979   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   48980   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   48981 };
   48982 
   48983 /*
   48984 ** Potential values for BtCursor.eState.
   48985 **
   48986 ** CURSOR_VALID:
   48987 **   Cursor points to a valid entry. getPayload() etc. may be called.
   48988 **
   48989 ** CURSOR_INVALID:
   48990 **   Cursor does not point to a valid entry. This can happen (for example)
   48991 **   because the table is empty or because BtreeCursorFirst() has not been
   48992 **   called.
   48993 **
   48994 ** CURSOR_REQUIRESEEK:
   48995 **   The table that this cursor was opened on still exists, but has been
   48996 **   modified since the cursor was last used. The cursor position is saved
   48997 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   48998 **   this state, restoreCursorPosition() can be called to attempt to
   48999 **   seek the cursor to the saved position.
   49000 **
   49001 ** CURSOR_FAULT:
   49002 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   49003 **   on a different connection that shares the BtShared cache with this
   49004 **   cursor.  The error has left the cache in an inconsistent state.
   49005 **   Do nothing else with this cursor.  Any attempt to use the cursor
   49006 **   should return the error code stored in BtCursor.skip
   49007 */
   49008 #define CURSOR_INVALID           0
   49009 #define CURSOR_VALID             1
   49010 #define CURSOR_REQUIRESEEK       2
   49011 #define CURSOR_FAULT             3
   49012 
   49013 /*
   49014 ** The database page the PENDING_BYTE occupies. This page is never used.
   49015 */
   49016 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   49017 
   49018 /*
   49019 ** These macros define the location of the pointer-map entry for a
   49020 ** database page. The first argument to each is the number of usable
   49021 ** bytes on each page of the database (often 1024). The second is the
   49022 ** page number to look up in the pointer map.
   49023 **
   49024 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   49025 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   49026 ** the offset of the requested map entry.
   49027 **
   49028 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   49029 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   49030 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   49031 ** this test.
   49032 */
   49033 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   49034 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   49035 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   49036 
   49037 /*
   49038 ** The pointer map is a lookup table that identifies the parent page for
   49039 ** each child page in the database file.  The parent page is the page that
   49040 ** contains a pointer to the child.  Every page in the database contains
   49041 ** 0 or 1 parent pages.  (In this context 'database page' refers
   49042 ** to any page that is not part of the pointer map itself.)  Each pointer map
   49043 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   49044 ** The PTRMAP_XXX identifiers below are the valid types.
   49045 **
   49046 ** The purpose of the pointer map is to facility moving pages from one
   49047 ** position in the file to another as part of autovacuum.  When a page
   49048 ** is moved, the pointer in its parent must be updated to point to the
   49049 ** new location.  The pointer map is used to locate the parent page quickly.
   49050 **
   49051 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   49052 **                  used in this case.
   49053 **
   49054 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   49055 **                  is not used in this case.
   49056 **
   49057 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   49058 **                   overflow pages. The page number identifies the page that
   49059 **                   contains the cell with a pointer to this overflow page.
   49060 **
   49061 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   49062 **                   overflow pages. The page-number identifies the previous
   49063 **                   page in the overflow page list.
   49064 **
   49065 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   49066 **               identifies the parent page in the btree.
   49067 */
   49068 #define PTRMAP_ROOTPAGE 1
   49069 #define PTRMAP_FREEPAGE 2
   49070 #define PTRMAP_OVERFLOW1 3
   49071 #define PTRMAP_OVERFLOW2 4
   49072 #define PTRMAP_BTREE 5
   49073 
   49074 /* A bunch of assert() statements to check the transaction state variables
   49075 ** of handle p (type Btree*) are internally consistent.
   49076 */
   49077 #define btreeIntegrity(p) \
   49078   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   49079   assert( p->pBt->inTransaction>=p->inTrans );
   49080 
   49081 
   49082 /*
   49083 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   49084 ** if the database supports auto-vacuum or not. Because it is used
   49085 ** within an expression that is an argument to another macro
   49086 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   49087 ** So, this macro is defined instead.
   49088 */
   49089 #ifndef SQLITE_OMIT_AUTOVACUUM
   49090 #define ISAUTOVACUUM (pBt->autoVacuum)
   49091 #else
   49092 #define ISAUTOVACUUM 0
   49093 #endif
   49094 
   49095 
   49096 /*
   49097 ** This structure is passed around through all the sanity checking routines
   49098 ** in order to keep track of some global state information.
   49099 */
   49100 typedef struct IntegrityCk IntegrityCk;
   49101 struct IntegrityCk {
   49102   BtShared *pBt;    /* The tree being checked out */
   49103   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   49104   int *anRef;       /* Number of times each page is referenced */
   49105   Pgno nPage;       /* Number of pages in the database */
   49106   int mxErr;        /* Stop accumulating errors when this reaches zero */
   49107   int nErr;         /* Number of messages written to zErrMsg so far */
   49108   int mallocFailed; /* A memory allocation error has occurred */
   49109   StrAccum errMsg;  /* Accumulate the error message text here */
   49110 };
   49111 
   49112 /*
   49113 ** Routines to read or write a two- and four-byte big-endian integer values.
   49114 */
   49115 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   49116 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   49117 #define get4byte sqlite3Get4byte
   49118 #define put4byte sqlite3Put4byte
   49119 
   49120 /************** End of btreeInt.h ********************************************/
   49121 /************** Continuing where we left off in btmutex.c ********************/
   49122 #ifndef SQLITE_OMIT_SHARED_CACHE
   49123 #if SQLITE_THREADSAFE
   49124 
   49125 /*
   49126 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   49127 ** set BtShared.db to the database handle associated with p and the
   49128 ** p->locked boolean to true.
   49129 */
   49130 static void lockBtreeMutex(Btree *p){
   49131   assert( p->locked==0 );
   49132   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   49133   assert( sqlite3_mutex_held(p->db->mutex) );
   49134 
   49135   sqlite3_mutex_enter(p->pBt->mutex);
   49136   p->pBt->db = p->db;
   49137   p->locked = 1;
   49138 }
   49139 
   49140 /*
   49141 ** Release the BtShared mutex associated with B-Tree handle p and
   49142 ** clear the p->locked boolean.
   49143 */
   49144 static void unlockBtreeMutex(Btree *p){
   49145   BtShared *pBt = p->pBt;
   49146   assert( p->locked==1 );
   49147   assert( sqlite3_mutex_held(pBt->mutex) );
   49148   assert( sqlite3_mutex_held(p->db->mutex) );
   49149   assert( p->db==pBt->db );
   49150 
   49151   sqlite3_mutex_leave(pBt->mutex);
   49152   p->locked = 0;
   49153 }
   49154 
   49155 /*
   49156 ** Enter a mutex on the given BTree object.
   49157 **
   49158 ** If the object is not sharable, then no mutex is ever required
   49159 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   49160 ** But we keep a reference count in Btree.wantToLock so the behavior
   49161 ** of this interface is recursive.
   49162 **
   49163 ** To avoid deadlocks, multiple Btrees are locked in the same order
   49164 ** by all database connections.  The p->pNext is a list of other
   49165 ** Btrees belonging to the same database connection as the p Btree
   49166 ** which need to be locked after p.  If we cannot get a lock on
   49167 ** p, then first unlock all of the others on p->pNext, then wait
   49168 ** for the lock to become available on p, then relock all of the
   49169 ** subsequent Btrees that desire a lock.
   49170 */
   49171 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   49172   Btree *pLater;
   49173 
   49174   /* Some basic sanity checking on the Btree.  The list of Btrees
   49175   ** connected by pNext and pPrev should be in sorted order by
   49176   ** Btree.pBt value. All elements of the list should belong to
   49177   ** the same connection. Only shared Btrees are on the list. */
   49178   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   49179   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   49180   assert( p->pNext==0 || p->pNext->db==p->db );
   49181   assert( p->pPrev==0 || p->pPrev->db==p->db );
   49182   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   49183 
   49184   /* Check for locking consistency */
   49185   assert( !p->locked || p->wantToLock>0 );
   49186   assert( p->sharable || p->wantToLock==0 );
   49187 
   49188   /* We should already hold a lock on the database connection */
   49189   assert( sqlite3_mutex_held(p->db->mutex) );
   49190 
   49191   /* Unless the database is sharable and unlocked, then BtShared.db
   49192   ** should already be set correctly. */
   49193   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   49194 
   49195   if( !p->sharable ) return;
   49196   p->wantToLock++;
   49197   if( p->locked ) return;
   49198 
   49199   /* In most cases, we should be able to acquire the lock we
   49200   ** want without having to go throught the ascending lock
   49201   ** procedure that follows.  Just be sure not to block.
   49202   */
   49203   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   49204     p->pBt->db = p->db;
   49205     p->locked = 1;
   49206     return;
   49207   }
   49208 
   49209   /* To avoid deadlock, first release all locks with a larger
   49210   ** BtShared address.  Then acquire our lock.  Then reacquire
   49211   ** the other BtShared locks that we used to hold in ascending
   49212   ** order.
   49213   */
   49214   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   49215     assert( pLater->sharable );
   49216     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   49217     assert( !pLater->locked || pLater->wantToLock>0 );
   49218     if( pLater->locked ){
   49219       unlockBtreeMutex(pLater);
   49220     }
   49221   }
   49222   lockBtreeMutex(p);
   49223   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   49224     if( pLater->wantToLock ){
   49225       lockBtreeMutex(pLater);
   49226     }
   49227   }
   49228 }
   49229 
   49230 /*
   49231 ** Exit the recursive mutex on a Btree.
   49232 */
   49233 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   49234   if( p->sharable ){
   49235     assert( p->wantToLock>0 );
   49236     p->wantToLock--;
   49237     if( p->wantToLock==0 ){
   49238       unlockBtreeMutex(p);
   49239     }
   49240   }
   49241 }
   49242 
   49243 #ifndef NDEBUG
   49244 /*
   49245 ** Return true if the BtShared mutex is held on the btree, or if the
   49246 ** B-Tree is not marked as sharable.
   49247 **
   49248 ** This routine is used only from within assert() statements.
   49249 */
   49250 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   49251   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   49252   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   49253   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   49254   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   49255 
   49256   return (p->sharable==0 || p->locked);
   49257 }
   49258 #endif
   49259 
   49260 
   49261 #ifndef SQLITE_OMIT_INCRBLOB
   49262 /*
   49263 ** Enter and leave a mutex on a Btree given a cursor owned by that
   49264 ** Btree.  These entry points are used by incremental I/O and can be
   49265 ** omitted if that module is not used.
   49266 */
   49267 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   49268   sqlite3BtreeEnter(pCur->pBtree);
   49269 }
   49270 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   49271   sqlite3BtreeLeave(pCur->pBtree);
   49272 }
   49273 #endif /* SQLITE_OMIT_INCRBLOB */
   49274 
   49275 
   49276 /*
   49277 ** Enter the mutex on every Btree associated with a database
   49278 ** connection.  This is needed (for example) prior to parsing
   49279 ** a statement since we will be comparing table and column names
   49280 ** against all schemas and we do not want those schemas being
   49281 ** reset out from under us.
   49282 **
   49283 ** There is a corresponding leave-all procedures.
   49284 **
   49285 ** Enter the mutexes in accending order by BtShared pointer address
   49286 ** to avoid the possibility of deadlock when two threads with
   49287 ** two or more btrees in common both try to lock all their btrees
   49288 ** at the same instant.
   49289 */
   49290 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   49291   int i;
   49292   Btree *p;
   49293   assert( sqlite3_mutex_held(db->mutex) );
   49294   for(i=0; i<db->nDb; i++){
   49295     p = db->aDb[i].pBt;
   49296     if( p ) sqlite3BtreeEnter(p);
   49297   }
   49298 }
   49299 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   49300   int i;
   49301   Btree *p;
   49302   assert( sqlite3_mutex_held(db->mutex) );
   49303   for(i=0; i<db->nDb; i++){
   49304     p = db->aDb[i].pBt;
   49305     if( p ) sqlite3BtreeLeave(p);
   49306   }
   49307 }
   49308 
   49309 /*
   49310 ** Return true if a particular Btree requires a lock.  Return FALSE if
   49311 ** no lock is ever required since it is not sharable.
   49312 */
   49313 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
   49314   return p->sharable;
   49315 }
   49316 
   49317 #ifndef NDEBUG
   49318 /*
   49319 ** Return true if the current thread holds the database connection
   49320 ** mutex and all required BtShared mutexes.
   49321 **
   49322 ** This routine is used inside assert() statements only.
   49323 */
   49324 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   49325   int i;
   49326   if( !sqlite3_mutex_held(db->mutex) ){
   49327     return 0;
   49328   }
   49329   for(i=0; i<db->nDb; i++){
   49330     Btree *p;
   49331     p = db->aDb[i].pBt;
   49332     if( p && p->sharable &&
   49333          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   49334       return 0;
   49335     }
   49336   }
   49337   return 1;
   49338 }
   49339 #endif /* NDEBUG */
   49340 
   49341 #ifndef NDEBUG
   49342 /*
   49343 ** Return true if the correct mutexes are held for accessing the
   49344 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
   49345 ** access are:
   49346 **
   49347 **   (1) The mutex on db
   49348 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
   49349 **
   49350 ** If pSchema is not NULL, then iDb is computed from pSchema and
   49351 ** db using sqlite3SchemaToIndex().
   49352 */
   49353 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
   49354   Btree *p;
   49355   assert( db!=0 );
   49356   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
   49357   assert( iDb>=0 && iDb<db->nDb );
   49358   if( !sqlite3_mutex_held(db->mutex) ) return 0;
   49359   if( iDb==1 ) return 1;
   49360   p = db->aDb[iDb].pBt;
   49361   assert( p!=0 );
   49362   return p->sharable==0 || p->locked==1;
   49363 }
   49364 #endif /* NDEBUG */
   49365 
   49366 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
   49367 /*
   49368 ** The following are special cases for mutex enter routines for use
   49369 ** in single threaded applications that use shared cache.  Except for
   49370 ** these two routines, all mutex operations are no-ops in that case and
   49371 ** are null #defines in btree.h.
   49372 **
   49373 ** If shared cache is disabled, then all btree mutex routines, including
   49374 ** the ones below, are no-ops and are null #defines in btree.h.
   49375 */
   49376 
   49377 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   49378   p->pBt->db = p->db;
   49379 }
   49380 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   49381   int i;
   49382   for(i=0; i<db->nDb; i++){
   49383     Btree *p = db->aDb[i].pBt;
   49384     if( p ){
   49385       p->pBt->db = p->db;
   49386     }
   49387   }
   49388 }
   49389 #endif /* if SQLITE_THREADSAFE */
   49390 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   49391 
   49392 /************** End of btmutex.c *********************************************/
   49393 /************** Begin file btree.c *******************************************/
   49394 /*
   49395 ** 2004 April 6
   49396 **
   49397 ** The author disclaims copyright to this source code.  In place of
   49398 ** a legal notice, here is a blessing:
   49399 **
   49400 **    May you do good and not evil.
   49401 **    May you find forgiveness for yourself and forgive others.
   49402 **    May you share freely, never taking more than you give.
   49403 **
   49404 *************************************************************************
   49405 ** This file implements a external (disk-based) database using BTrees.
   49406 ** See the header comment on "btreeInt.h" for additional information.
   49407 ** Including a description of file format and an overview of operation.
   49408 */
   49409 
   49410 /*
   49411 ** The header string that appears at the beginning of every
   49412 ** SQLite database.
   49413 */
   49414 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   49415 
   49416 /*
   49417 ** Set this global variable to 1 to enable tracing using the TRACE
   49418 ** macro.
   49419 */
   49420 #if 0
   49421 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   49422 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   49423 #else
   49424 # define TRACE(X)
   49425 #endif
   49426 
   49427 /*
   49428 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   49429 ** But if the value is zero, make it 65536.
   49430 **
   49431 ** This routine is used to extract the "offset to cell content area" value
   49432 ** from the header of a btree page.  If the page size is 65536 and the page
   49433 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   49434 ** This routine makes the necessary adjustment to 65536.
   49435 */
   49436 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   49437 
   49438 #ifndef SQLITE_OMIT_SHARED_CACHE
   49439 /*
   49440 ** A list of BtShared objects that are eligible for participation
   49441 ** in shared cache.  This variable has file scope during normal builds,
   49442 ** but the test harness needs to access it so we make it global for
   49443 ** test builds.
   49444 **
   49445 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   49446 */
   49447 #ifdef SQLITE_TEST
   49448 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   49449 #else
   49450 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   49451 #endif
   49452 #endif /* SQLITE_OMIT_SHARED_CACHE */
   49453 
   49454 #ifndef SQLITE_OMIT_SHARED_CACHE
   49455 /*
   49456 ** Enable or disable the shared pager and schema features.
   49457 **
   49458 ** This routine has no effect on existing database connections.
   49459 ** The shared cache setting effects only future calls to
   49460 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   49461 */
   49462 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   49463   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   49464   return SQLITE_OK;
   49465 }
   49466 #endif
   49467 
   49468 
   49469 
   49470 #ifdef SQLITE_OMIT_SHARED_CACHE
   49471   /*
   49472   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   49473   ** and clearAllSharedCacheTableLocks()
   49474   ** manipulate entries in the BtShared.pLock linked list used to store
   49475   ** shared-cache table level locks. If the library is compiled with the
   49476   ** shared-cache feature disabled, then there is only ever one user
   49477   ** of each BtShared structure and so this locking is not necessary.
   49478   ** So define the lock related functions as no-ops.
   49479   */
   49480   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   49481   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   49482   #define clearAllSharedCacheTableLocks(a)
   49483   #define downgradeAllSharedCacheTableLocks(a)
   49484   #define hasSharedCacheTableLock(a,b,c,d) 1
   49485   #define hasReadConflicts(a, b) 0
   49486 #endif
   49487 
   49488 #ifndef SQLITE_OMIT_SHARED_CACHE
   49489 
   49490 #ifdef SQLITE_DEBUG
   49491 /*
   49492 **** This function is only used as part of an assert() statement. ***
   49493 **
   49494 ** Check to see if pBtree holds the required locks to read or write to the
   49495 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   49496 **
   49497 ** For example, when writing to a table with root-page iRoot via
   49498 ** Btree connection pBtree:
   49499 **
   49500 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   49501 **
   49502 ** When writing to an index that resides in a sharable database, the
   49503 ** caller should have first obtained a lock specifying the root page of
   49504 ** the corresponding table. This makes things a bit more complicated,
   49505 ** as this module treats each table as a separate structure. To determine
   49506 ** the table corresponding to the index being written, this
   49507 ** function has to search through the database schema.
   49508 **
   49509 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   49510 ** hold a write-lock on the schema table (root page 1). This is also
   49511 ** acceptable.
   49512 */
   49513 static int hasSharedCacheTableLock(
   49514   Btree *pBtree,         /* Handle that must hold lock */
   49515   Pgno iRoot,            /* Root page of b-tree */
   49516   int isIndex,           /* True if iRoot is the root of an index b-tree */
   49517   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   49518 ){
   49519   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   49520   Pgno iTab = 0;
   49521   BtLock *pLock;
   49522 
   49523   /* If this database is not shareable, or if the client is reading
   49524   ** and has the read-uncommitted flag set, then no lock is required.
   49525   ** Return true immediately.
   49526   */
   49527   if( (pBtree->sharable==0)
   49528    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   49529   ){
   49530     return 1;
   49531   }
   49532 
   49533   /* If the client is reading  or writing an index and the schema is
   49534   ** not loaded, then it is too difficult to actually check to see if
   49535   ** the correct locks are held.  So do not bother - just return true.
   49536   ** This case does not come up very often anyhow.
   49537   */
   49538   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
   49539     return 1;
   49540   }
   49541 
   49542   /* Figure out the root-page that the lock should be held on. For table
   49543   ** b-trees, this is just the root page of the b-tree being read or
   49544   ** written. For index b-trees, it is the root page of the associated
   49545   ** table.  */
   49546   if( isIndex ){
   49547     HashElem *p;
   49548     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   49549       Index *pIdx = (Index *)sqliteHashData(p);
   49550       if( pIdx->tnum==(int)iRoot ){
   49551         iTab = pIdx->pTable->tnum;
   49552       }
   49553     }
   49554   }else{
   49555     iTab = iRoot;
   49556   }
   49557 
   49558   /* Search for the required lock. Either a write-lock on root-page iTab, a
   49559   ** write-lock on the schema table, or (if the client is reading) a
   49560   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   49561   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   49562     if( pLock->pBtree==pBtree
   49563      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   49564      && pLock->eLock>=eLockType
   49565     ){
   49566       return 1;
   49567     }
   49568   }
   49569 
   49570   /* Failed to find the required lock. */
   49571   return 0;
   49572 }
   49573 #endif /* SQLITE_DEBUG */
   49574 
   49575 #ifdef SQLITE_DEBUG
   49576 /*
   49577 **** This function may be used as part of assert() statements only. ****
   49578 **
   49579 ** Return true if it would be illegal for pBtree to write into the
   49580 ** table or index rooted at iRoot because other shared connections are
   49581 ** simultaneously reading that same table or index.
   49582 **
   49583 ** It is illegal for pBtree to write if some other Btree object that
   49584 ** shares the same BtShared object is currently reading or writing
   49585 ** the iRoot table.  Except, if the other Btree object has the
   49586 ** read-uncommitted flag set, then it is OK for the other object to
   49587 ** have a read cursor.
   49588 **
   49589 ** For example, before writing to any part of the table or index
   49590 ** rooted at page iRoot, one should call:
   49591 **
   49592 **    assert( !hasReadConflicts(pBtree, iRoot) );
   49593 */
   49594 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   49595   BtCursor *p;
   49596   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   49597     if( p->pgnoRoot==iRoot
   49598      && p->pBtree!=pBtree
   49599      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   49600     ){
   49601       return 1;
   49602     }
   49603   }
   49604   return 0;
   49605 }
   49606 #endif    /* #ifdef SQLITE_DEBUG */
   49607 
   49608 /*
   49609 ** Query to see if Btree handle p may obtain a lock of type eLock
   49610 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   49611 ** SQLITE_OK if the lock may be obtained (by calling
   49612 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   49613 */
   49614 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   49615   BtShared *pBt = p->pBt;
   49616   BtLock *pIter;
   49617 
   49618   assert( sqlite3BtreeHoldsMutex(p) );
   49619   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   49620   assert( p->db!=0 );
   49621   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   49622 
   49623   /* If requesting a write-lock, then the Btree must have an open write
   49624   ** transaction on this file. And, obviously, for this to be so there
   49625   ** must be an open write transaction on the file itself.
   49626   */
   49627   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   49628   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   49629 
   49630   /* This routine is a no-op if the shared-cache is not enabled */
   49631   if( !p->sharable ){
   49632     return SQLITE_OK;
   49633   }
   49634 
   49635   /* If some other connection is holding an exclusive lock, the
   49636   ** requested lock may not be obtained.
   49637   */
   49638   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
   49639     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   49640     return SQLITE_LOCKED_SHAREDCACHE;
   49641   }
   49642 
   49643   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   49644     /* The condition (pIter->eLock!=eLock) in the following if(...)
   49645     ** statement is a simplification of:
   49646     **
   49647     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   49648     **
   49649     ** since we know that if eLock==WRITE_LOCK, then no other connection
   49650     ** may hold a WRITE_LOCK on any table in this file (since there can
   49651     ** only be a single writer).
   49652     */
   49653     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   49654     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   49655     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   49656       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   49657       if( eLock==WRITE_LOCK ){
   49658         assert( p==pBt->pWriter );
   49659         pBt->btsFlags |= BTS_PENDING;
   49660       }
   49661       return SQLITE_LOCKED_SHAREDCACHE;
   49662     }
   49663   }
   49664   return SQLITE_OK;
   49665 }
   49666 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   49667 
   49668 #ifndef SQLITE_OMIT_SHARED_CACHE
   49669 /*
   49670 ** Add a lock on the table with root-page iTable to the shared-btree used
   49671 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   49672 ** WRITE_LOCK.
   49673 **
   49674 ** This function assumes the following:
   49675 **
   49676 **   (a) The specified Btree object p is connected to a sharable
   49677 **       database (one with the BtShared.sharable flag set), and
   49678 **
   49679 **   (b) No other Btree objects hold a lock that conflicts
   49680 **       with the requested lock (i.e. querySharedCacheTableLock() has
   49681 **       already been called and returned SQLITE_OK).
   49682 **
   49683 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   49684 ** is returned if a malloc attempt fails.
   49685 */
   49686 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   49687   BtShared *pBt = p->pBt;
   49688   BtLock *pLock = 0;
   49689   BtLock *pIter;
   49690 
   49691   assert( sqlite3BtreeHoldsMutex(p) );
   49692   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   49693   assert( p->db!=0 );
   49694 
   49695   /* A connection with the read-uncommitted flag set will never try to
   49696   ** obtain a read-lock using this function. The only read-lock obtained
   49697   ** by a connection in read-uncommitted mode is on the sqlite_master
   49698   ** table, and that lock is obtained in BtreeBeginTrans().  */
   49699   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   49700 
   49701   /* This function should only be called on a sharable b-tree after it
   49702   ** has been determined that no other b-tree holds a conflicting lock.  */
   49703   assert( p->sharable );
   49704   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   49705 
   49706   /* First search the list for an existing lock on this table. */
   49707   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   49708     if( pIter->iTable==iTable && pIter->pBtree==p ){
   49709       pLock = pIter;
   49710       break;
   49711     }
   49712   }
   49713 
   49714   /* If the above search did not find a BtLock struct associating Btree p
   49715   ** with table iTable, allocate one and link it into the list.
   49716   */
   49717   if( !pLock ){
   49718     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   49719     if( !pLock ){
   49720       return SQLITE_NOMEM;
   49721     }
   49722     pLock->iTable = iTable;
   49723     pLock->pBtree = p;
   49724     pLock->pNext = pBt->pLock;
   49725     pBt->pLock = pLock;
   49726   }
   49727 
   49728   /* Set the BtLock.eLock variable to the maximum of the current lock
   49729   ** and the requested lock. This means if a write-lock was already held
   49730   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   49731   */
   49732   assert( WRITE_LOCK>READ_LOCK );
   49733   if( eLock>pLock->eLock ){
   49734     pLock->eLock = eLock;
   49735   }
   49736 
   49737   return SQLITE_OK;
   49738 }
   49739 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   49740 
   49741 #ifndef SQLITE_OMIT_SHARED_CACHE
   49742 /*
   49743 ** Release all the table locks (locks obtained via calls to
   49744 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   49745 **
   49746 ** This function assumes that Btree p has an open read or write
   49747 ** transaction. If it does not, then the BTS_PENDING flag
   49748 ** may be incorrectly cleared.
   49749 */
   49750 static void clearAllSharedCacheTableLocks(Btree *p){
   49751   BtShared *pBt = p->pBt;
   49752   BtLock **ppIter = &pBt->pLock;
   49753 
   49754   assert( sqlite3BtreeHoldsMutex(p) );
   49755   assert( p->sharable || 0==*ppIter );
   49756   assert( p->inTrans>0 );
   49757 
   49758   while( *ppIter ){
   49759     BtLock *pLock = *ppIter;
   49760     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
   49761     assert( pLock->pBtree->inTrans>=pLock->eLock );
   49762     if( pLock->pBtree==p ){
   49763       *ppIter = pLock->pNext;
   49764       assert( pLock->iTable!=1 || pLock==&p->lock );
   49765       if( pLock->iTable!=1 ){
   49766         sqlite3_free(pLock);
   49767       }
   49768     }else{
   49769       ppIter = &pLock->pNext;
   49770     }
   49771   }
   49772 
   49773   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
   49774   if( pBt->pWriter==p ){
   49775     pBt->pWriter = 0;
   49776     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   49777   }else if( pBt->nTransaction==2 ){
   49778     /* This function is called when Btree p is concluding its
   49779     ** transaction. If there currently exists a writer, and p is not
   49780     ** that writer, then the number of locks held by connections other
   49781     ** than the writer must be about to drop to zero. In this case
   49782     ** set the BTS_PENDING flag to 0.
   49783     **
   49784     ** If there is not currently a writer, then BTS_PENDING must
   49785     ** be zero already. So this next line is harmless in that case.
   49786     */
   49787     pBt->btsFlags &= ~BTS_PENDING;
   49788   }
   49789 }
   49790 
   49791 /*
   49792 ** This function changes all write-locks held by Btree p into read-locks.
   49793 */
   49794 static void downgradeAllSharedCacheTableLocks(Btree *p){
   49795   BtShared *pBt = p->pBt;
   49796   if( pBt->pWriter==p ){
   49797     BtLock *pLock;
   49798     pBt->pWriter = 0;
   49799     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   49800     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   49801       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   49802       pLock->eLock = READ_LOCK;
   49803     }
   49804   }
   49805 }
   49806 
   49807 #endif /* SQLITE_OMIT_SHARED_CACHE */
   49808 
   49809 static void releasePage(MemPage *pPage);  /* Forward reference */
   49810 
   49811 /*
   49812 ***** This routine is used inside of assert() only ****
   49813 **
   49814 ** Verify that the cursor holds the mutex on its BtShared
   49815 */
   49816 #ifdef SQLITE_DEBUG
   49817 static int cursorHoldsMutex(BtCursor *p){
   49818   return sqlite3_mutex_held(p->pBt->mutex);
   49819 }
   49820 #endif
   49821 
   49822 
   49823 #ifndef SQLITE_OMIT_INCRBLOB
   49824 /*
   49825 ** Invalidate the overflow page-list cache for cursor pCur, if any.
   49826 */
   49827 static void invalidateOverflowCache(BtCursor *pCur){
   49828   assert( cursorHoldsMutex(pCur) );
   49829   sqlite3_free(pCur->aOverflow);
   49830   pCur->aOverflow = 0;
   49831 }
   49832 
   49833 /*
   49834 ** Invalidate the overflow page-list cache for all cursors opened
   49835 ** on the shared btree structure pBt.
   49836 */
   49837 static void invalidateAllOverflowCache(BtShared *pBt){
   49838   BtCursor *p;
   49839   assert( sqlite3_mutex_held(pBt->mutex) );
   49840   for(p=pBt->pCursor; p; p=p->pNext){
   49841     invalidateOverflowCache(p);
   49842   }
   49843 }
   49844 
   49845 /*
   49846 ** This function is called before modifying the contents of a table
   49847 ** to invalidate any incrblob cursors that are open on the
   49848 ** row or one of the rows being modified.
   49849 **
   49850 ** If argument isClearTable is true, then the entire contents of the
   49851 ** table is about to be deleted. In this case invalidate all incrblob
   49852 ** cursors open on any row within the table with root-page pgnoRoot.
   49853 **
   49854 ** Otherwise, if argument isClearTable is false, then the row with
   49855 ** rowid iRow is being replaced or deleted. In this case invalidate
   49856 ** only those incrblob cursors open on that specific row.
   49857 */
   49858 static void invalidateIncrblobCursors(
   49859   Btree *pBtree,          /* The database file to check */
   49860   i64 iRow,               /* The rowid that might be changing */
   49861   int isClearTable        /* True if all rows are being deleted */
   49862 ){
   49863   BtCursor *p;
   49864   BtShared *pBt = pBtree->pBt;
   49865   assert( sqlite3BtreeHoldsMutex(pBtree) );
   49866   for(p=pBt->pCursor; p; p=p->pNext){
   49867     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
   49868       p->eState = CURSOR_INVALID;
   49869     }
   49870   }
   49871 }
   49872 
   49873 #else
   49874   /* Stub functions when INCRBLOB is omitted */
   49875   #define invalidateOverflowCache(x)
   49876   #define invalidateAllOverflowCache(x)
   49877   #define invalidateIncrblobCursors(x,y,z)
   49878 #endif /* SQLITE_OMIT_INCRBLOB */
   49879 
   49880 /*
   49881 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   49882 ** when a page that previously contained data becomes a free-list leaf
   49883 ** page.
   49884 **
   49885 ** The BtShared.pHasContent bitvec exists to work around an obscure
   49886 ** bug caused by the interaction of two useful IO optimizations surrounding
   49887 ** free-list leaf pages:
   49888 **
   49889 **   1) When all data is deleted from a page and the page becomes
   49890 **      a free-list leaf page, the page is not written to the database
   49891 **      (as free-list leaf pages contain no meaningful data). Sometimes
   49892 **      such a page is not even journalled (as it will not be modified,
   49893 **      why bother journalling it?).
   49894 **
   49895 **   2) When a free-list leaf page is reused, its content is not read
   49896 **      from the database or written to the journal file (why should it
   49897 **      be, if it is not at all meaningful?).
   49898 **
   49899 ** By themselves, these optimizations work fine and provide a handy
   49900 ** performance boost to bulk delete or insert operations. However, if
   49901 ** a page is moved to the free-list and then reused within the same
   49902 ** transaction, a problem comes up. If the page is not journalled when
   49903 ** it is moved to the free-list and it is also not journalled when it
   49904 ** is extracted from the free-list and reused, then the original data
   49905 ** may be lost. In the event of a rollback, it may not be possible
   49906 ** to restore the database to its original configuration.
   49907 **
   49908 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   49909 ** moved to become a free-list leaf page, the corresponding bit is
   49910 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   49911 ** optimization 2 above is omitted if the corresponding bit is already
   49912 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   49913 ** at the end of every transaction.
   49914 */
   49915 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   49916   int rc = SQLITE_OK;
   49917   if( !pBt->pHasContent ){
   49918     assert( pgno<=pBt->nPage );
   49919     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   49920     if( !pBt->pHasContent ){
   49921       rc = SQLITE_NOMEM;
   49922     }
   49923   }
   49924   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   49925     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   49926   }
   49927   return rc;
   49928 }
   49929 
   49930 /*
   49931 ** Query the BtShared.pHasContent vector.
   49932 **
   49933 ** This function is called when a free-list leaf page is removed from the
   49934 ** free-list for reuse. It returns false if it is safe to retrieve the
   49935 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   49936 */
   49937 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   49938   Bitvec *p = pBt->pHasContent;
   49939   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   49940 }
   49941 
   49942 /*
   49943 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   49944 ** invoked at the conclusion of each write-transaction.
   49945 */
   49946 static void btreeClearHasContent(BtShared *pBt){
   49947   sqlite3BitvecDestroy(pBt->pHasContent);
   49948   pBt->pHasContent = 0;
   49949 }
   49950 
   49951 /*
   49952 ** Save the current cursor position in the variables BtCursor.nKey
   49953 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   49954 **
   49955 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   49956 ** prior to calling this routine.
   49957 */
   49958 static int saveCursorPosition(BtCursor *pCur){
   49959   int rc;
   49960 
   49961   assert( CURSOR_VALID==pCur->eState );
   49962   assert( 0==pCur->pKey );
   49963   assert( cursorHoldsMutex(pCur) );
   49964 
   49965   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   49966   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   49967 
   49968   /* If this is an intKey table, then the above call to BtreeKeySize()
   49969   ** stores the integer key in pCur->nKey. In this case this value is
   49970   ** all that is required. Otherwise, if pCur is not open on an intKey
   49971   ** table, then malloc space for and store the pCur->nKey bytes of key
   49972   ** data.
   49973   */
   49974   if( 0==pCur->apPage[0]->intKey ){
   49975     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   49976     if( pKey ){
   49977       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   49978       if( rc==SQLITE_OK ){
   49979         pCur->pKey = pKey;
   49980       }else{
   49981         sqlite3_free(pKey);
   49982       }
   49983     }else{
   49984       rc = SQLITE_NOMEM;
   49985     }
   49986   }
   49987   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   49988 
   49989   if( rc==SQLITE_OK ){
   49990     int i;
   49991     for(i=0; i<=pCur->iPage; i++){
   49992       releasePage(pCur->apPage[i]);
   49993       pCur->apPage[i] = 0;
   49994     }
   49995     pCur->iPage = -1;
   49996     pCur->eState = CURSOR_REQUIRESEEK;
   49997   }
   49998 
   49999   invalidateOverflowCache(pCur);
   50000   return rc;
   50001 }
   50002 
   50003 /*
   50004 ** Save the positions of all cursors (except pExcept) that are open on
   50005 ** the table  with root-page iRoot. Usually, this is called just before cursor
   50006 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   50007 */
   50008 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   50009   BtCursor *p;
   50010   assert( sqlite3_mutex_held(pBt->mutex) );
   50011   assert( pExcept==0 || pExcept->pBt==pBt );
   50012   for(p=pBt->pCursor; p; p=p->pNext){
   50013     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
   50014         p->eState==CURSOR_VALID ){
   50015       int rc = saveCursorPosition(p);
   50016       if( SQLITE_OK!=rc ){
   50017         return rc;
   50018       }
   50019     }
   50020   }
   50021   return SQLITE_OK;
   50022 }
   50023 
   50024 /*
   50025 ** Clear the current cursor position.
   50026 */
   50027 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   50028   assert( cursorHoldsMutex(pCur) );
   50029   sqlite3_free(pCur->pKey);
   50030   pCur->pKey = 0;
   50031   pCur->eState = CURSOR_INVALID;
   50032 }
   50033 
   50034 /*
   50035 ** In this version of BtreeMoveto, pKey is a packed index record
   50036 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   50037 ** record and then call BtreeMovetoUnpacked() to do the work.
   50038 */
   50039 static int btreeMoveto(
   50040   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   50041   const void *pKey,   /* Packed key if the btree is an index */
   50042   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   50043   int bias,           /* Bias search to the high end */
   50044   int *pRes           /* Write search results here */
   50045 ){
   50046   int rc;                    /* Status code */
   50047   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   50048   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
   50049   char *pFree = 0;
   50050 
   50051   if( pKey ){
   50052     assert( nKey==(i64)(int)nKey );
   50053     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   50054         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
   50055     );
   50056     if( pIdxKey==0 ) return SQLITE_NOMEM;
   50057     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
   50058   }else{
   50059     pIdxKey = 0;
   50060   }
   50061   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   50062   if( pFree ){
   50063     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   50064   }
   50065   return rc;
   50066 }
   50067 
   50068 /*
   50069 ** Restore the cursor to the position it was in (or as close to as possible)
   50070 ** when saveCursorPosition() was called. Note that this call deletes the
   50071 ** saved position info stored by saveCursorPosition(), so there can be
   50072 ** at most one effective restoreCursorPosition() call after each
   50073 ** saveCursorPosition().
   50074 */
   50075 static int btreeRestoreCursorPosition(BtCursor *pCur){
   50076   int rc;
   50077   assert( cursorHoldsMutex(pCur) );
   50078   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   50079   if( pCur->eState==CURSOR_FAULT ){
   50080     return pCur->skipNext;
   50081   }
   50082   pCur->eState = CURSOR_INVALID;
   50083   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   50084   if( rc==SQLITE_OK ){
   50085     sqlite3_free(pCur->pKey);
   50086     pCur->pKey = 0;
   50087     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   50088   }
   50089   return rc;
   50090 }
   50091 
   50092 #define restoreCursorPosition(p) \
   50093   (p->eState>=CURSOR_REQUIRESEEK ? \
   50094          btreeRestoreCursorPosition(p) : \
   50095          SQLITE_OK)
   50096 
   50097 /*
   50098 ** Determine whether or not a cursor has moved from the position it
   50099 ** was last placed at.  Cursors can move when the row they are pointing
   50100 ** at is deleted out from under them.
   50101 **
   50102 ** This routine returns an error code if something goes wrong.  The
   50103 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
   50104 */
   50105 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   50106   int rc;
   50107 
   50108   rc = restoreCursorPosition(pCur);
   50109   if( rc ){
   50110     *pHasMoved = 1;
   50111     return rc;
   50112   }
   50113   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
   50114     *pHasMoved = 1;
   50115   }else{
   50116     *pHasMoved = 0;
   50117   }
   50118   return SQLITE_OK;
   50119 }
   50120 
   50121 #ifndef SQLITE_OMIT_AUTOVACUUM
   50122 /*
   50123 ** Given a page number of a regular database page, return the page
   50124 ** number for the pointer-map page that contains the entry for the
   50125 ** input page number.
   50126 **
   50127 ** Return 0 (not a valid page) for pgno==1 since there is
   50128 ** no pointer map associated with page 1.  The integrity_check logic
   50129 ** requires that ptrmapPageno(*,1)!=1.
   50130 */
   50131 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   50132   int nPagesPerMapPage;
   50133   Pgno iPtrMap, ret;
   50134   assert( sqlite3_mutex_held(pBt->mutex) );
   50135   if( pgno<2 ) return 0;
   50136   nPagesPerMapPage = (pBt->usableSize/5)+1;
   50137   iPtrMap = (pgno-2)/nPagesPerMapPage;
   50138   ret = (iPtrMap*nPagesPerMapPage) + 2;
   50139   if( ret==PENDING_BYTE_PAGE(pBt) ){
   50140     ret++;
   50141   }
   50142   return ret;
   50143 }
   50144 
   50145 /*
   50146 ** Write an entry into the pointer map.
   50147 **
   50148 ** This routine updates the pointer map entry for page number 'key'
   50149 ** so that it maps to type 'eType' and parent page number 'pgno'.
   50150 **
   50151 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   50152 ** a no-op.  If an error occurs, the appropriate error code is written
   50153 ** into *pRC.
   50154 */
   50155 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   50156   DbPage *pDbPage;  /* The pointer map page */
   50157   u8 *pPtrmap;      /* The pointer map data */
   50158   Pgno iPtrmap;     /* The pointer map page number */
   50159   int offset;       /* Offset in pointer map page */
   50160   int rc;           /* Return code from subfunctions */
   50161 
   50162   if( *pRC ) return;
   50163 
   50164   assert( sqlite3_mutex_held(pBt->mutex) );
   50165   /* The master-journal page number must never be used as a pointer map page */
   50166   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   50167 
   50168   assert( pBt->autoVacuum );
   50169   if( key==0 ){
   50170     *pRC = SQLITE_CORRUPT_BKPT;
   50171     return;
   50172   }
   50173   iPtrmap = PTRMAP_PAGENO(pBt, key);
   50174   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   50175   if( rc!=SQLITE_OK ){
   50176     *pRC = rc;
   50177     return;
   50178   }
   50179   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   50180   if( offset<0 ){
   50181     *pRC = SQLITE_CORRUPT_BKPT;
   50182     goto ptrmap_exit;
   50183   }
   50184   assert( offset <= (int)pBt->usableSize-5 );
   50185   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   50186 
   50187   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   50188     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   50189     *pRC= rc = sqlite3PagerWrite(pDbPage);
   50190     if( rc==SQLITE_OK ){
   50191       pPtrmap[offset] = eType;
   50192       put4byte(&pPtrmap[offset+1], parent);
   50193     }
   50194   }
   50195 
   50196 ptrmap_exit:
   50197   sqlite3PagerUnref(pDbPage);
   50198 }
   50199 
   50200 /*
   50201 ** Read an entry from the pointer map.
   50202 **
   50203 ** This routine retrieves the pointer map entry for page 'key', writing
   50204 ** the type and parent page number to *pEType and *pPgno respectively.
   50205 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   50206 */
   50207 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   50208   DbPage *pDbPage;   /* The pointer map page */
   50209   int iPtrmap;       /* Pointer map page index */
   50210   u8 *pPtrmap;       /* Pointer map page data */
   50211   int offset;        /* Offset of entry in pointer map */
   50212   int rc;
   50213 
   50214   assert( sqlite3_mutex_held(pBt->mutex) );
   50215 
   50216   iPtrmap = PTRMAP_PAGENO(pBt, key);
   50217   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   50218   if( rc!=0 ){
   50219     return rc;
   50220   }
   50221   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   50222 
   50223   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   50224   if( offset<0 ){
   50225     sqlite3PagerUnref(pDbPage);
   50226     return SQLITE_CORRUPT_BKPT;
   50227   }
   50228   assert( offset <= (int)pBt->usableSize-5 );
   50229   assert( pEType!=0 );
   50230   *pEType = pPtrmap[offset];
   50231   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   50232 
   50233   sqlite3PagerUnref(pDbPage);
   50234   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   50235   return SQLITE_OK;
   50236 }
   50237 
   50238 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   50239   #define ptrmapPut(w,x,y,z,rc)
   50240   #define ptrmapGet(w,x,y,z) SQLITE_OK
   50241   #define ptrmapPutOvflPtr(x, y, rc)
   50242 #endif
   50243 
   50244 /*
   50245 ** Given a btree page and a cell index (0 means the first cell on
   50246 ** the page, 1 means the second cell, and so forth) return a pointer
   50247 ** to the cell content.
   50248 **
   50249 ** This routine works only for pages that do not contain overflow cells.
   50250 */
   50251 #define findCell(P,I) \
   50252   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
   50253 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
   50254 
   50255 
   50256 /*
   50257 ** This a more complex version of findCell() that works for
   50258 ** pages that do contain overflow cells.
   50259 */
   50260 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   50261   int i;
   50262   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50263   for(i=pPage->nOverflow-1; i>=0; i--){
   50264     int k;
   50265     k = pPage->aiOvfl[i];
   50266     if( k<=iCell ){
   50267       if( k==iCell ){
   50268         return pPage->apOvfl[i];
   50269       }
   50270       iCell--;
   50271     }
   50272   }
   50273   return findCell(pPage, iCell);
   50274 }
   50275 
   50276 /*
   50277 ** Parse a cell content block and fill in the CellInfo structure.  There
   50278 ** are two versions of this function.  btreeParseCell() takes a
   50279 ** cell index as the second argument and btreeParseCellPtr()
   50280 ** takes a pointer to the body of the cell as its second argument.
   50281 **
   50282 ** Within this file, the parseCell() macro can be called instead of
   50283 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   50284 */
   50285 static void btreeParseCellPtr(
   50286   MemPage *pPage,         /* Page containing the cell */
   50287   u8 *pCell,              /* Pointer to the cell text. */
   50288   CellInfo *pInfo         /* Fill in this structure */
   50289 ){
   50290   u16 n;                  /* Number bytes in cell content header */
   50291   u32 nPayload;           /* Number of bytes of cell payload */
   50292 
   50293   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50294 
   50295   pInfo->pCell = pCell;
   50296   assert( pPage->leaf==0 || pPage->leaf==1 );
   50297   n = pPage->childPtrSize;
   50298   assert( n==4-4*pPage->leaf );
   50299   if( pPage->intKey ){
   50300     if( pPage->hasData ){
   50301       n += getVarint32(&pCell[n], nPayload);
   50302     }else{
   50303       nPayload = 0;
   50304     }
   50305     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   50306     pInfo->nData = nPayload;
   50307   }else{
   50308     pInfo->nData = 0;
   50309     n += getVarint32(&pCell[n], nPayload);
   50310     pInfo->nKey = nPayload;
   50311   }
   50312   pInfo->nPayload = nPayload;
   50313   pInfo->nHeader = n;
   50314   testcase( nPayload==pPage->maxLocal );
   50315   testcase( nPayload==pPage->maxLocal+1 );
   50316   if( likely(nPayload<=pPage->maxLocal) ){
   50317     /* This is the (easy) common case where the entire payload fits
   50318     ** on the local page.  No overflow is required.
   50319     */
   50320     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
   50321     pInfo->nLocal = (u16)nPayload;
   50322     pInfo->iOverflow = 0;
   50323   }else{
   50324     /* If the payload will not fit completely on the local page, we have
   50325     ** to decide how much to store locally and how much to spill onto
   50326     ** overflow pages.  The strategy is to minimize the amount of unused
   50327     ** space on overflow pages while keeping the amount of local storage
   50328     ** in between minLocal and maxLocal.
   50329     **
   50330     ** Warning:  changing the way overflow payload is distributed in any
   50331     ** way will result in an incompatible file format.
   50332     */
   50333     int minLocal;  /* Minimum amount of payload held locally */
   50334     int maxLocal;  /* Maximum amount of payload held locally */
   50335     int surplus;   /* Overflow payload available for local storage */
   50336 
   50337     minLocal = pPage->minLocal;
   50338     maxLocal = pPage->maxLocal;
   50339     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   50340     testcase( surplus==maxLocal );
   50341     testcase( surplus==maxLocal+1 );
   50342     if( surplus <= maxLocal ){
   50343       pInfo->nLocal = (u16)surplus;
   50344     }else{
   50345       pInfo->nLocal = (u16)minLocal;
   50346     }
   50347     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   50348     pInfo->nSize = pInfo->iOverflow + 4;
   50349   }
   50350 }
   50351 #define parseCell(pPage, iCell, pInfo) \
   50352   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   50353 static void btreeParseCell(
   50354   MemPage *pPage,         /* Page containing the cell */
   50355   int iCell,              /* The cell index.  First cell is 0 */
   50356   CellInfo *pInfo         /* Fill in this structure */
   50357 ){
   50358   parseCell(pPage, iCell, pInfo);
   50359 }
   50360 
   50361 /*
   50362 ** Compute the total number of bytes that a Cell needs in the cell
   50363 ** data area of the btree-page.  The return number includes the cell
   50364 ** data header and the local payload, but not any overflow page or
   50365 ** the space used by the cell pointer.
   50366 */
   50367 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   50368   u8 *pIter = &pCell[pPage->childPtrSize];
   50369   u32 nSize;
   50370 
   50371 #ifdef SQLITE_DEBUG
   50372   /* The value returned by this function should always be the same as
   50373   ** the (CellInfo.nSize) value found by doing a full parse of the
   50374   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   50375   ** this function verifies that this invariant is not violated. */
   50376   CellInfo debuginfo;
   50377   btreeParseCellPtr(pPage, pCell, &debuginfo);
   50378 #endif
   50379 
   50380   if( pPage->intKey ){
   50381     u8 *pEnd;
   50382     if( pPage->hasData ){
   50383       pIter += getVarint32(pIter, nSize);
   50384     }else{
   50385       nSize = 0;
   50386     }
   50387 
   50388     /* pIter now points at the 64-bit integer key value, a variable length
   50389     ** integer. The following block moves pIter to point at the first byte
   50390     ** past the end of the key value. */
   50391     pEnd = &pIter[9];
   50392     while( (*pIter++)&0x80 && pIter<pEnd );
   50393   }else{
   50394     pIter += getVarint32(pIter, nSize);
   50395   }
   50396 
   50397   testcase( nSize==pPage->maxLocal );
   50398   testcase( nSize==pPage->maxLocal+1 );
   50399   if( nSize>pPage->maxLocal ){
   50400     int minLocal = pPage->minLocal;
   50401     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   50402     testcase( nSize==pPage->maxLocal );
   50403     testcase( nSize==pPage->maxLocal+1 );
   50404     if( nSize>pPage->maxLocal ){
   50405       nSize = minLocal;
   50406     }
   50407     nSize += 4;
   50408   }
   50409   nSize += (u32)(pIter - pCell);
   50410 
   50411   /* The minimum size of any cell is 4 bytes. */
   50412   if( nSize<4 ){
   50413     nSize = 4;
   50414   }
   50415 
   50416   assert( nSize==debuginfo.nSize );
   50417   return (u16)nSize;
   50418 }
   50419 
   50420 #ifdef SQLITE_DEBUG
   50421 /* This variation on cellSizePtr() is used inside of assert() statements
   50422 ** only. */
   50423 static u16 cellSize(MemPage *pPage, int iCell){
   50424   return cellSizePtr(pPage, findCell(pPage, iCell));
   50425 }
   50426 #endif
   50427 
   50428 #ifndef SQLITE_OMIT_AUTOVACUUM
   50429 /*
   50430 ** If the cell pCell, part of page pPage contains a pointer
   50431 ** to an overflow page, insert an entry into the pointer-map
   50432 ** for the overflow page.
   50433 */
   50434 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   50435   CellInfo info;
   50436   if( *pRC ) return;
   50437   assert( pCell!=0 );
   50438   btreeParseCellPtr(pPage, pCell, &info);
   50439   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   50440   if( info.iOverflow ){
   50441     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   50442     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   50443   }
   50444 }
   50445 #endif
   50446 
   50447 
   50448 /*
   50449 ** Defragment the page given.  All Cells are moved to the
   50450 ** end of the page and all free space is collected into one
   50451 ** big FreeBlk that occurs in between the header and cell
   50452 ** pointer array and the cell content area.
   50453 */
   50454 static int defragmentPage(MemPage *pPage){
   50455   int i;                     /* Loop counter */
   50456   int pc;                    /* Address of a i-th cell */
   50457   int hdr;                   /* Offset to the page header */
   50458   int size;                  /* Size of a cell */
   50459   int usableSize;            /* Number of usable bytes on a page */
   50460   int cellOffset;            /* Offset to the cell pointer array */
   50461   int cbrk;                  /* Offset to the cell content area */
   50462   int nCell;                 /* Number of cells on the page */
   50463   unsigned char *data;       /* The page data */
   50464   unsigned char *temp;       /* Temp area for cell content */
   50465   int iCellFirst;            /* First allowable cell index */
   50466   int iCellLast;             /* Last possible cell index */
   50467 
   50468 
   50469   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50470   assert( pPage->pBt!=0 );
   50471   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   50472   assert( pPage->nOverflow==0 );
   50473   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50474   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   50475   data = pPage->aData;
   50476   hdr = pPage->hdrOffset;
   50477   cellOffset = pPage->cellOffset;
   50478   nCell = pPage->nCell;
   50479   assert( nCell==get2byte(&data[hdr+3]) );
   50480   usableSize = pPage->pBt->usableSize;
   50481   cbrk = get2byte(&data[hdr+5]);
   50482   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   50483   cbrk = usableSize;
   50484   iCellFirst = cellOffset + 2*nCell;
   50485   iCellLast = usableSize - 4;
   50486   for(i=0; i<nCell; i++){
   50487     u8 *pAddr;     /* The i-th cell pointer */
   50488     pAddr = &data[cellOffset + i*2];
   50489     pc = get2byte(pAddr);
   50490     testcase( pc==iCellFirst );
   50491     testcase( pc==iCellLast );
   50492 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50493     /* These conditions have already been verified in btreeInitPage()
   50494     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   50495     */
   50496     if( pc<iCellFirst || pc>iCellLast ){
   50497       return SQLITE_CORRUPT_BKPT;
   50498     }
   50499 #endif
   50500     assert( pc>=iCellFirst && pc<=iCellLast );
   50501     size = cellSizePtr(pPage, &temp[pc]);
   50502     cbrk -= size;
   50503 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50504     if( cbrk<iCellFirst ){
   50505       return SQLITE_CORRUPT_BKPT;
   50506     }
   50507 #else
   50508     if( cbrk<iCellFirst || pc+size>usableSize ){
   50509       return SQLITE_CORRUPT_BKPT;
   50510     }
   50511 #endif
   50512     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   50513     testcase( cbrk+size==usableSize );
   50514     testcase( pc+size==usableSize );
   50515     memcpy(&data[cbrk], &temp[pc], size);
   50516     put2byte(pAddr, cbrk);
   50517   }
   50518   assert( cbrk>=iCellFirst );
   50519   put2byte(&data[hdr+5], cbrk);
   50520   data[hdr+1] = 0;
   50521   data[hdr+2] = 0;
   50522   data[hdr+7] = 0;
   50523   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   50524   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50525   if( cbrk-iCellFirst!=pPage->nFree ){
   50526     return SQLITE_CORRUPT_BKPT;
   50527   }
   50528   return SQLITE_OK;
   50529 }
   50530 
   50531 /*
   50532 ** Allocate nByte bytes of space from within the B-Tree page passed
   50533 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   50534 ** of the first byte of allocated space. Return either SQLITE_OK or
   50535 ** an error code (usually SQLITE_CORRUPT).
   50536 **
   50537 ** The caller guarantees that there is sufficient space to make the
   50538 ** allocation.  This routine might need to defragment in order to bring
   50539 ** all the space together, however.  This routine will avoid using
   50540 ** the first two bytes past the cell pointer area since presumably this
   50541 ** allocation is being made in order to insert a new cell, so we will
   50542 ** also end up needing a new cell pointer.
   50543 */
   50544 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   50545   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   50546   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   50547   int nFrag;                           /* Number of fragmented bytes on pPage */
   50548   int top;                             /* First byte of cell content area */
   50549   int gap;        /* First byte of gap between cell pointers and cell content */
   50550   int rc;         /* Integer return code */
   50551   int usableSize; /* Usable size of the page */
   50552 
   50553   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50554   assert( pPage->pBt );
   50555   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50556   assert( nByte>=0 );  /* Minimum cell size is 4 */
   50557   assert( pPage->nFree>=nByte );
   50558   assert( pPage->nOverflow==0 );
   50559   usableSize = pPage->pBt->usableSize;
   50560   assert( nByte < usableSize-8 );
   50561 
   50562   nFrag = data[hdr+7];
   50563   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   50564   gap = pPage->cellOffset + 2*pPage->nCell;
   50565   top = get2byteNotZero(&data[hdr+5]);
   50566   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   50567   testcase( gap+2==top );
   50568   testcase( gap+1==top );
   50569   testcase( gap==top );
   50570 
   50571   if( nFrag>=60 ){
   50572     /* Always defragment highly fragmented pages */
   50573     rc = defragmentPage(pPage);
   50574     if( rc ) return rc;
   50575     top = get2byteNotZero(&data[hdr+5]);
   50576   }else if( gap+2<=top ){
   50577     /* Search the freelist looking for a free slot big enough to satisfy
   50578     ** the request. The allocation is made from the first free slot in
   50579     ** the list that is large enough to accomadate it.
   50580     */
   50581     int pc, addr;
   50582     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   50583       int size;            /* Size of the free slot */
   50584       if( pc>usableSize-4 || pc<addr+4 ){
   50585         return SQLITE_CORRUPT_BKPT;
   50586       }
   50587       size = get2byte(&data[pc+2]);
   50588       if( size>=nByte ){
   50589         int x = size - nByte;
   50590         testcase( x==4 );
   50591         testcase( x==3 );
   50592         if( x<4 ){
   50593           /* Remove the slot from the free-list. Update the number of
   50594           ** fragmented bytes within the page. */
   50595           memcpy(&data[addr], &data[pc], 2);
   50596           data[hdr+7] = (u8)(nFrag + x);
   50597         }else if( size+pc > usableSize ){
   50598           return SQLITE_CORRUPT_BKPT;
   50599         }else{
   50600           /* The slot remains on the free-list. Reduce its size to account
   50601           ** for the portion used by the new allocation. */
   50602           put2byte(&data[pc+2], x);
   50603         }
   50604         *pIdx = pc + x;
   50605         return SQLITE_OK;
   50606       }
   50607     }
   50608   }
   50609 
   50610   /* Check to make sure there is enough space in the gap to satisfy
   50611   ** the allocation.  If not, defragment.
   50612   */
   50613   testcase( gap+2+nByte==top );
   50614   if( gap+2+nByte>top ){
   50615     rc = defragmentPage(pPage);
   50616     if( rc ) return rc;
   50617     top = get2byteNotZero(&data[hdr+5]);
   50618     assert( gap+nByte<=top );
   50619   }
   50620 
   50621 
   50622   /* Allocate memory from the gap in between the cell pointer array
   50623   ** and the cell content area.  The btreeInitPage() call has already
   50624   ** validated the freelist.  Given that the freelist is valid, there
   50625   ** is no way that the allocation can extend off the end of the page.
   50626   ** The assert() below verifies the previous sentence.
   50627   */
   50628   top -= nByte;
   50629   put2byte(&data[hdr+5], top);
   50630   assert( top+nByte <= (int)pPage->pBt->usableSize );
   50631   *pIdx = top;
   50632   return SQLITE_OK;
   50633 }
   50634 
   50635 /*
   50636 ** Return a section of the pPage->aData to the freelist.
   50637 ** The first byte of the new free block is pPage->aDisk[start]
   50638 ** and the size of the block is "size" bytes.
   50639 **
   50640 ** Most of the effort here is involved in coalesing adjacent
   50641 ** free blocks into a single big free block.
   50642 */
   50643 static int freeSpace(MemPage *pPage, int start, int size){
   50644   int addr, pbegin, hdr;
   50645   int iLast;                        /* Largest possible freeblock offset */
   50646   unsigned char *data = pPage->aData;
   50647 
   50648   assert( pPage->pBt!=0 );
   50649   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50650   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   50651   assert( (start + size) <= (int)pPage->pBt->usableSize );
   50652   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50653   assert( size>=0 );   /* Minimum cell size is 4 */
   50654 
   50655   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
   50656     /* Overwrite deleted information with zeros when the secure_delete
   50657     ** option is enabled */
   50658     memset(&data[start], 0, size);
   50659   }
   50660 
   50661   /* Add the space back into the linked list of freeblocks.  Note that
   50662   ** even though the freeblock list was checked by btreeInitPage(),
   50663   ** btreeInitPage() did not detect overlapping cells or
   50664   ** freeblocks that overlapped cells.   Nor does it detect when the
   50665   ** cell content area exceeds the value in the page header.  If these
   50666   ** situations arise, then subsequent insert operations might corrupt
   50667   ** the freelist.  So we do need to check for corruption while scanning
   50668   ** the freelist.
   50669   */
   50670   hdr = pPage->hdrOffset;
   50671   addr = hdr + 1;
   50672   iLast = pPage->pBt->usableSize - 4;
   50673   assert( start<=iLast );
   50674   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   50675     if( pbegin<addr+4 ){
   50676       return SQLITE_CORRUPT_BKPT;
   50677     }
   50678     addr = pbegin;
   50679   }
   50680   if( pbegin>iLast ){
   50681     return SQLITE_CORRUPT_BKPT;
   50682   }
   50683   assert( pbegin>addr || pbegin==0 );
   50684   put2byte(&data[addr], start);
   50685   put2byte(&data[start], pbegin);
   50686   put2byte(&data[start+2], size);
   50687   pPage->nFree = pPage->nFree + (u16)size;
   50688 
   50689   /* Coalesce adjacent free blocks */
   50690   addr = hdr + 1;
   50691   while( (pbegin = get2byte(&data[addr]))>0 ){
   50692     int pnext, psize, x;
   50693     assert( pbegin>addr );
   50694     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
   50695     pnext = get2byte(&data[pbegin]);
   50696     psize = get2byte(&data[pbegin+2]);
   50697     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   50698       int frag = pnext - (pbegin+psize);
   50699       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   50700         return SQLITE_CORRUPT_BKPT;
   50701       }
   50702       data[hdr+7] -= (u8)frag;
   50703       x = get2byte(&data[pnext]);
   50704       put2byte(&data[pbegin], x);
   50705       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   50706       put2byte(&data[pbegin+2], x);
   50707     }else{
   50708       addr = pbegin;
   50709     }
   50710   }
   50711 
   50712   /* If the cell content area begins with a freeblock, remove it. */
   50713   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   50714     int top;
   50715     pbegin = get2byte(&data[hdr+1]);
   50716     memcpy(&data[hdr+1], &data[pbegin], 2);
   50717     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   50718     put2byte(&data[hdr+5], top);
   50719   }
   50720   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50721   return SQLITE_OK;
   50722 }
   50723 
   50724 /*
   50725 ** Decode the flags byte (the first byte of the header) for a page
   50726 ** and initialize fields of the MemPage structure accordingly.
   50727 **
   50728 ** Only the following combinations are supported.  Anything different
   50729 ** indicates a corrupt database files:
   50730 **
   50731 **         PTF_ZERODATA
   50732 **         PTF_ZERODATA | PTF_LEAF
   50733 **         PTF_LEAFDATA | PTF_INTKEY
   50734 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   50735 */
   50736 static int decodeFlags(MemPage *pPage, int flagByte){
   50737   BtShared *pBt;     /* A copy of pPage->pBt */
   50738 
   50739   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   50740   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50741   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   50742   flagByte &= ~PTF_LEAF;
   50743   pPage->childPtrSize = 4-4*pPage->leaf;
   50744   pBt = pPage->pBt;
   50745   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   50746     pPage->intKey = 1;
   50747     pPage->hasData = pPage->leaf;
   50748     pPage->maxLocal = pBt->maxLeaf;
   50749     pPage->minLocal = pBt->minLeaf;
   50750   }else if( flagByte==PTF_ZERODATA ){
   50751     pPage->intKey = 0;
   50752     pPage->hasData = 0;
   50753     pPage->maxLocal = pBt->maxLocal;
   50754     pPage->minLocal = pBt->minLocal;
   50755   }else{
   50756     return SQLITE_CORRUPT_BKPT;
   50757   }
   50758   pPage->max1bytePayload = pBt->max1bytePayload;
   50759   return SQLITE_OK;
   50760 }
   50761 
   50762 /*
   50763 ** Initialize the auxiliary information for a disk block.
   50764 **
   50765 ** Return SQLITE_OK on success.  If we see that the page does
   50766 ** not contain a well-formed database page, then return
   50767 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   50768 ** guarantee that the page is well-formed.  It only shows that
   50769 ** we failed to detect any corruption.
   50770 */
   50771 static int btreeInitPage(MemPage *pPage){
   50772 
   50773   assert( pPage->pBt!=0 );
   50774   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50775   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   50776   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   50777   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   50778 
   50779   if( !pPage->isInit ){
   50780     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   50781     u8 hdr;            /* Offset to beginning of page header */
   50782     u8 *data;          /* Equal to pPage->aData */
   50783     BtShared *pBt;        /* The main btree structure */
   50784     int usableSize;    /* Amount of usable space on each page */
   50785     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   50786     int nFree;         /* Number of unused bytes on the page */
   50787     int top;           /* First byte of the cell content area */
   50788     int iCellFirst;    /* First allowable cell or freeblock offset */
   50789     int iCellLast;     /* Last possible cell or freeblock offset */
   50790 
   50791     pBt = pPage->pBt;
   50792 
   50793     hdr = pPage->hdrOffset;
   50794     data = pPage->aData;
   50795     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   50796     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   50797     pPage->maskPage = (u16)(pBt->pageSize - 1);
   50798     pPage->nOverflow = 0;
   50799     usableSize = pBt->usableSize;
   50800     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   50801     pPage->aDataEnd = &data[usableSize];
   50802     pPage->aCellIdx = &data[cellOffset];
   50803     top = get2byteNotZero(&data[hdr+5]);
   50804     pPage->nCell = get2byte(&data[hdr+3]);
   50805     if( pPage->nCell>MX_CELL(pBt) ){
   50806       /* To many cells for a single page.  The page must be corrupt */
   50807       return SQLITE_CORRUPT_BKPT;
   50808     }
   50809     testcase( pPage->nCell==MX_CELL(pBt) );
   50810 
   50811     /* A malformed database page might cause us to read past the end
   50812     ** of page when parsing a cell.
   50813     **
   50814     ** The following block of code checks early to see if a cell extends
   50815     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   50816     ** returned if it does.
   50817     */
   50818     iCellFirst = cellOffset + 2*pPage->nCell;
   50819     iCellLast = usableSize - 4;
   50820 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50821     {
   50822       int i;            /* Index into the cell pointer array */
   50823       int sz;           /* Size of a cell */
   50824 
   50825       if( !pPage->leaf ) iCellLast--;
   50826       for(i=0; i<pPage->nCell; i++){
   50827         pc = get2byte(&data[cellOffset+i*2]);
   50828         testcase( pc==iCellFirst );
   50829         testcase( pc==iCellLast );
   50830         if( pc<iCellFirst || pc>iCellLast ){
   50831           return SQLITE_CORRUPT_BKPT;
   50832         }
   50833         sz = cellSizePtr(pPage, &data[pc]);
   50834         testcase( pc+sz==usableSize );
   50835         if( pc+sz>usableSize ){
   50836           return SQLITE_CORRUPT_BKPT;
   50837         }
   50838       }
   50839       if( !pPage->leaf ) iCellLast++;
   50840     }
   50841 #endif
   50842 
   50843     /* Compute the total free space on the page */
   50844     pc = get2byte(&data[hdr+1]);
   50845     nFree = data[hdr+7] + top;
   50846     while( pc>0 ){
   50847       u16 next, size;
   50848       if( pc<iCellFirst || pc>iCellLast ){
   50849         /* Start of free block is off the page */
   50850         return SQLITE_CORRUPT_BKPT;
   50851       }
   50852       next = get2byte(&data[pc]);
   50853       size = get2byte(&data[pc+2]);
   50854       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   50855         /* Free blocks must be in ascending order. And the last byte of
   50856 	** the free-block must lie on the database page.  */
   50857         return SQLITE_CORRUPT_BKPT;
   50858       }
   50859       nFree = nFree + size;
   50860       pc = next;
   50861     }
   50862 
   50863     /* At this point, nFree contains the sum of the offset to the start
   50864     ** of the cell-content area plus the number of free bytes within
   50865     ** the cell-content area. If this is greater than the usable-size
   50866     ** of the page, then the page must be corrupted. This check also
   50867     ** serves to verify that the offset to the start of the cell-content
   50868     ** area, according to the page header, lies within the page.
   50869     */
   50870     if( nFree>usableSize ){
   50871       return SQLITE_CORRUPT_BKPT;
   50872     }
   50873     pPage->nFree = (u16)(nFree - iCellFirst);
   50874     pPage->isInit = 1;
   50875   }
   50876   return SQLITE_OK;
   50877 }
   50878 
   50879 /*
   50880 ** Set up a raw page so that it looks like a database page holding
   50881 ** no entries.
   50882 */
   50883 static void zeroPage(MemPage *pPage, int flags){
   50884   unsigned char *data = pPage->aData;
   50885   BtShared *pBt = pPage->pBt;
   50886   u8 hdr = pPage->hdrOffset;
   50887   u16 first;
   50888 
   50889   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   50890   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   50891   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   50892   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50893   assert( sqlite3_mutex_held(pBt->mutex) );
   50894   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   50895     memset(&data[hdr], 0, pBt->usableSize - hdr);
   50896   }
   50897   data[hdr] = (char)flags;
   50898   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
   50899   memset(&data[hdr+1], 0, 4);
   50900   data[hdr+7] = 0;
   50901   put2byte(&data[hdr+5], pBt->usableSize);
   50902   pPage->nFree = (u16)(pBt->usableSize - first);
   50903   decodeFlags(pPage, flags);
   50904   pPage->hdrOffset = hdr;
   50905   pPage->cellOffset = first;
   50906   pPage->aDataEnd = &data[pBt->usableSize];
   50907   pPage->aCellIdx = &data[first];
   50908   pPage->nOverflow = 0;
   50909   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   50910   pPage->maskPage = (u16)(pBt->pageSize - 1);
   50911   pPage->nCell = 0;
   50912   pPage->isInit = 1;
   50913 }
   50914 
   50915 
   50916 /*
   50917 ** Convert a DbPage obtained from the pager into a MemPage used by
   50918 ** the btree layer.
   50919 */
   50920 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   50921   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   50922   pPage->aData = sqlite3PagerGetData(pDbPage);
   50923   pPage->pDbPage = pDbPage;
   50924   pPage->pBt = pBt;
   50925   pPage->pgno = pgno;
   50926   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   50927   return pPage;
   50928 }
   50929 
   50930 /*
   50931 ** Get a page from the pager.  Initialize the MemPage.pBt and
   50932 ** MemPage.aData elements if needed.
   50933 **
   50934 ** If the noContent flag is set, it means that we do not care about
   50935 ** the content of the page at this time.  So do not go to the disk
   50936 ** to fetch the content.  Just fill in the content with zeros for now.
   50937 ** If in the future we call sqlite3PagerWrite() on this page, that
   50938 ** means we have started to be concerned about content and the disk
   50939 ** read should occur at that point.
   50940 */
   50941 static int btreeGetPage(
   50942   BtShared *pBt,       /* The btree */
   50943   Pgno pgno,           /* Number of the page to fetch */
   50944   MemPage **ppPage,    /* Return the page in this parameter */
   50945   int noContent        /* Do not load page content if true */
   50946 ){
   50947   int rc;
   50948   DbPage *pDbPage;
   50949 
   50950   assert( sqlite3_mutex_held(pBt->mutex) );
   50951   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
   50952   if( rc ) return rc;
   50953   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   50954   return SQLITE_OK;
   50955 }
   50956 
   50957 /*
   50958 ** Retrieve a page from the pager cache. If the requested page is not
   50959 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   50960 ** MemPage.aData elements if needed.
   50961 */
   50962 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   50963   DbPage *pDbPage;
   50964   assert( sqlite3_mutex_held(pBt->mutex) );
   50965   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   50966   if( pDbPage ){
   50967     return btreePageFromDbPage(pDbPage, pgno, pBt);
   50968   }
   50969   return 0;
   50970 }
   50971 
   50972 /*
   50973 ** Return the size of the database file in pages. If there is any kind of
   50974 ** error, return ((unsigned int)-1).
   50975 */
   50976 static Pgno btreePagecount(BtShared *pBt){
   50977   return pBt->nPage;
   50978 }
   50979 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   50980   assert( sqlite3BtreeHoldsMutex(p) );
   50981   assert( ((p->pBt->nPage)&0x8000000)==0 );
   50982   return (int)btreePagecount(p->pBt);
   50983 }
   50984 
   50985 /*
   50986 ** Get a page from the pager and initialize it.  This routine is just a
   50987 ** convenience wrapper around separate calls to btreeGetPage() and
   50988 ** btreeInitPage().
   50989 **
   50990 ** If an error occurs, then the value *ppPage is set to is undefined. It
   50991 ** may remain unchanged, or it may be set to an invalid value.
   50992 */
   50993 static int getAndInitPage(
   50994   BtShared *pBt,          /* The database file */
   50995   Pgno pgno,           /* Number of the page to get */
   50996   MemPage **ppPage     /* Write the page pointer here */
   50997 ){
   50998   int rc;
   50999   assert( sqlite3_mutex_held(pBt->mutex) );
   51000 
   51001   if( pgno>btreePagecount(pBt) ){
   51002     rc = SQLITE_CORRUPT_BKPT;
   51003   }else{
   51004     rc = btreeGetPage(pBt, pgno, ppPage, 0);
   51005     if( rc==SQLITE_OK ){
   51006       rc = btreeInitPage(*ppPage);
   51007       if( rc!=SQLITE_OK ){
   51008         releasePage(*ppPage);
   51009       }
   51010     }
   51011   }
   51012 
   51013   testcase( pgno==0 );
   51014   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   51015   return rc;
   51016 }
   51017 
   51018 /*
   51019 ** Release a MemPage.  This should be called once for each prior
   51020 ** call to btreeGetPage.
   51021 */
   51022 static void releasePage(MemPage *pPage){
   51023   if( pPage ){
   51024     assert( pPage->aData );
   51025     assert( pPage->pBt );
   51026     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   51027     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   51028     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   51029     sqlite3PagerUnref(pPage->pDbPage);
   51030   }
   51031 }
   51032 
   51033 /*
   51034 ** During a rollback, when the pager reloads information into the cache
   51035 ** so that the cache is restored to its original state at the start of
   51036 ** the transaction, for each page restored this routine is called.
   51037 **
   51038 ** This routine needs to reset the extra data section at the end of the
   51039 ** page to agree with the restored data.
   51040 */
   51041 static void pageReinit(DbPage *pData){
   51042   MemPage *pPage;
   51043   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   51044   assert( sqlite3PagerPageRefcount(pData)>0 );
   51045   if( pPage->isInit ){
   51046     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   51047     pPage->isInit = 0;
   51048     if( sqlite3PagerPageRefcount(pData)>1 ){
   51049       /* pPage might not be a btree page;  it might be an overflow page
   51050       ** or ptrmap page or a free page.  In those cases, the following
   51051       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   51052       ** But no harm is done by this.  And it is very important that
   51053       ** btreeInitPage() be called on every btree page so we make
   51054       ** the call for every page that comes in for re-initing. */
   51055       btreeInitPage(pPage);
   51056     }
   51057   }
   51058 }
   51059 
   51060 /*
   51061 ** Invoke the busy handler for a btree.
   51062 */
   51063 static int btreeInvokeBusyHandler(void *pArg){
   51064   BtShared *pBt = (BtShared*)pArg;
   51065   assert( pBt->db );
   51066   assert( sqlite3_mutex_held(pBt->db->mutex) );
   51067   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   51068 }
   51069 
   51070 /*
   51071 ** Open a database file.
   51072 **
   51073 ** zFilename is the name of the database file.  If zFilename is NULL
   51074 ** then an ephemeral database is created.  The ephemeral database might
   51075 ** be exclusively in memory, or it might use a disk-based memory cache.
   51076 ** Either way, the ephemeral database will be automatically deleted
   51077 ** when sqlite3BtreeClose() is called.
   51078 **
   51079 ** If zFilename is ":memory:" then an in-memory database is created
   51080 ** that is automatically destroyed when it is closed.
   51081 **
   51082 ** The "flags" parameter is a bitmask that might contain bits like
   51083 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
   51084 **
   51085 ** If the database is already opened in the same database connection
   51086 ** and we are in shared cache mode, then the open will fail with an
   51087 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   51088 ** objects in the same database connection since doing so will lead
   51089 ** to problems with locking.
   51090 */
   51091 SQLITE_PRIVATE int sqlite3BtreeOpen(
   51092   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
   51093   const char *zFilename,  /* Name of the file containing the BTree database */
   51094   sqlite3 *db,            /* Associated database handle */
   51095   Btree **ppBtree,        /* Pointer to new Btree object written here */
   51096   int flags,              /* Options */
   51097   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   51098 ){
   51099   BtShared *pBt = 0;             /* Shared part of btree structure */
   51100   Btree *p;                      /* Handle to return */
   51101   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   51102   int rc = SQLITE_OK;            /* Result code from this function */
   51103   u8 nReserve;                   /* Byte of unused space on each page */
   51104   unsigned char zDbHeader[100];  /* Database header content */
   51105 
   51106   /* True if opening an ephemeral, temporary database */
   51107   const int isTempDb = zFilename==0 || zFilename[0]==0;
   51108 
   51109   /* Set the variable isMemdb to true for an in-memory database, or
   51110   ** false for a file-based database.
   51111   */
   51112 #ifdef SQLITE_OMIT_MEMORYDB
   51113   const int isMemdb = 0;
   51114 #else
   51115   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   51116                        || (isTempDb && sqlite3TempInMemory(db));
   51117 #endif
   51118 
   51119   assert( db!=0 );
   51120   assert( pVfs!=0 );
   51121   assert( sqlite3_mutex_held(db->mutex) );
   51122   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   51123 
   51124   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   51125   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   51126 
   51127   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   51128   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   51129 
   51130   if( isMemdb ){
   51131     flags |= BTREE_MEMORY;
   51132   }
   51133   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   51134     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   51135   }
   51136   p = sqlite3MallocZero(sizeof(Btree));
   51137   if( !p ){
   51138     return SQLITE_NOMEM;
   51139   }
   51140   p->inTrans = TRANS_NONE;
   51141   p->db = db;
   51142 #ifndef SQLITE_OMIT_SHARED_CACHE
   51143   p->lock.pBtree = p;
   51144   p->lock.iTable = 1;
   51145 #endif
   51146 
   51147 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51148   /*
   51149   ** If this Btree is a candidate for shared cache, try to find an
   51150   ** existing BtShared object that we can share with
   51151   */
   51152   if( isMemdb==0 && isTempDb==0 ){
   51153     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   51154       int nFullPathname = pVfs->mxPathname+1;
   51155       char *zFullPathname = sqlite3Malloc(nFullPathname);
   51156       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   51157       p->sharable = 1;
   51158       if( !zFullPathname ){
   51159         sqlite3_free(p);
   51160         return SQLITE_NOMEM;
   51161       }
   51162       rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
   51163       if( rc ){
   51164         sqlite3_free(zFullPathname);
   51165         sqlite3_free(p);
   51166         return rc;
   51167       }
   51168 #if SQLITE_THREADSAFE
   51169       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   51170       sqlite3_mutex_enter(mutexOpen);
   51171       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   51172       sqlite3_mutex_enter(mutexShared);
   51173 #endif
   51174       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   51175         assert( pBt->nRef>0 );
   51176         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
   51177                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   51178           int iDb;
   51179           for(iDb=db->nDb-1; iDb>=0; iDb--){
   51180             Btree *pExisting = db->aDb[iDb].pBt;
   51181             if( pExisting && pExisting->pBt==pBt ){
   51182               sqlite3_mutex_leave(mutexShared);
   51183               sqlite3_mutex_leave(mutexOpen);
   51184               sqlite3_free(zFullPathname);
   51185               sqlite3_free(p);
   51186               return SQLITE_CONSTRAINT;
   51187             }
   51188           }
   51189           p->pBt = pBt;
   51190           pBt->nRef++;
   51191           break;
   51192         }
   51193       }
   51194       sqlite3_mutex_leave(mutexShared);
   51195       sqlite3_free(zFullPathname);
   51196     }
   51197 #ifdef SQLITE_DEBUG
   51198     else{
   51199       /* In debug mode, we mark all persistent databases as sharable
   51200       ** even when they are not.  This exercises the locking code and
   51201       ** gives more opportunity for asserts(sqlite3_mutex_held())
   51202       ** statements to find locking problems.
   51203       */
   51204       p->sharable = 1;
   51205     }
   51206 #endif
   51207   }
   51208 #endif
   51209   if( pBt==0 ){
   51210     /*
   51211     ** The following asserts make sure that structures used by the btree are
   51212     ** the right size.  This is to guard against size changes that result
   51213     ** when compiling on a different architecture.
   51214     */
   51215     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   51216     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   51217     assert( sizeof(u32)==4 );
   51218     assert( sizeof(u16)==2 );
   51219     assert( sizeof(Pgno)==4 );
   51220 
   51221     pBt = sqlite3MallocZero( sizeof(*pBt) );
   51222     if( pBt==0 ){
   51223       rc = SQLITE_NOMEM;
   51224       goto btree_open_out;
   51225     }
   51226     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   51227                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   51228     if( rc==SQLITE_OK ){
   51229       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   51230     }
   51231     if( rc!=SQLITE_OK ){
   51232       goto btree_open_out;
   51233     }
   51234     pBt->openFlags = (u8)flags;
   51235     pBt->db = db;
   51236     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   51237     p->pBt = pBt;
   51238 
   51239     pBt->pCursor = 0;
   51240     pBt->pPage1 = 0;
   51241     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
   51242 #ifdef SQLITE_SECURE_DELETE
   51243     pBt->btsFlags |= BTS_SECURE_DELETE;
   51244 #endif
   51245     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   51246     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   51247          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   51248       pBt->pageSize = 0;
   51249 #ifndef SQLITE_OMIT_AUTOVACUUM
   51250       /* If the magic name ":memory:" will create an in-memory database, then
   51251       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   51252       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   51253       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   51254       ** regular file-name. In this case the auto-vacuum applies as per normal.
   51255       */
   51256       if( zFilename && !isMemdb ){
   51257         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   51258         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   51259       }
   51260 #endif
   51261       nReserve = 0;
   51262     }else{
   51263       nReserve = zDbHeader[20];
   51264       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51265 #ifndef SQLITE_OMIT_AUTOVACUUM
   51266       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   51267       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   51268 #endif
   51269     }
   51270     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   51271     if( rc ) goto btree_open_out;
   51272     pBt->usableSize = pBt->pageSize - nReserve;
   51273     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   51274 
   51275 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51276     /* Add the new BtShared object to the linked list sharable BtShareds.
   51277     */
   51278     if( p->sharable ){
   51279       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   51280       pBt->nRef = 1;
   51281       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
   51282       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   51283         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   51284         if( pBt->mutex==0 ){
   51285           rc = SQLITE_NOMEM;
   51286           db->mallocFailed = 0;
   51287           goto btree_open_out;
   51288         }
   51289       }
   51290       sqlite3_mutex_enter(mutexShared);
   51291       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   51292       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   51293       sqlite3_mutex_leave(mutexShared);
   51294     }
   51295 #endif
   51296   }
   51297 
   51298 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51299   /* If the new Btree uses a sharable pBtShared, then link the new
   51300   ** Btree into the list of all sharable Btrees for the same connection.
   51301   ** The list is kept in ascending order by pBt address.
   51302   */
   51303   if( p->sharable ){
   51304     int i;
   51305     Btree *pSib;
   51306     for(i=0; i<db->nDb; i++){
   51307       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   51308         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   51309         if( p->pBt<pSib->pBt ){
   51310           p->pNext = pSib;
   51311           p->pPrev = 0;
   51312           pSib->pPrev = p;
   51313         }else{
   51314           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   51315             pSib = pSib->pNext;
   51316           }
   51317           p->pNext = pSib->pNext;
   51318           p->pPrev = pSib;
   51319           if( p->pNext ){
   51320             p->pNext->pPrev = p;
   51321           }
   51322           pSib->pNext = p;
   51323         }
   51324         break;
   51325       }
   51326     }
   51327   }
   51328 #endif
   51329   *ppBtree = p;
   51330 
   51331 btree_open_out:
   51332   if( rc!=SQLITE_OK ){
   51333     if( pBt && pBt->pPager ){
   51334       sqlite3PagerClose(pBt->pPager);
   51335     }
   51336     sqlite3_free(pBt);
   51337     sqlite3_free(p);
   51338     *ppBtree = 0;
   51339   }else{
   51340     /* If the B-Tree was successfully opened, set the pager-cache size to the
   51341     ** default value. Except, when opening on an existing shared pager-cache,
   51342     ** do not change the pager-cache size.
   51343     */
   51344     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   51345       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   51346     }
   51347   }
   51348   if( mutexOpen ){
   51349     assert( sqlite3_mutex_held(mutexOpen) );
   51350     sqlite3_mutex_leave(mutexOpen);
   51351   }
   51352   return rc;
   51353 }
   51354 
   51355 /*
   51356 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   51357 ** remove the BtShared structure from the sharing list.  Return
   51358 ** true if the BtShared.nRef counter reaches zero and return
   51359 ** false if it is still positive.
   51360 */
   51361 static int removeFromSharingList(BtShared *pBt){
   51362 #ifndef SQLITE_OMIT_SHARED_CACHE
   51363   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
   51364   BtShared *pList;
   51365   int removed = 0;
   51366 
   51367   assert( sqlite3_mutex_notheld(pBt->mutex) );
   51368   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   51369   sqlite3_mutex_enter(pMaster);
   51370   pBt->nRef--;
   51371   if( pBt->nRef<=0 ){
   51372     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   51373       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   51374     }else{
   51375       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   51376       while( ALWAYS(pList) && pList->pNext!=pBt ){
   51377         pList=pList->pNext;
   51378       }
   51379       if( ALWAYS(pList) ){
   51380         pList->pNext = pBt->pNext;
   51381       }
   51382     }
   51383     if( SQLITE_THREADSAFE ){
   51384       sqlite3_mutex_free(pBt->mutex);
   51385     }
   51386     removed = 1;
   51387   }
   51388   sqlite3_mutex_leave(pMaster);
   51389   return removed;
   51390 #else
   51391   return 1;
   51392 #endif
   51393 }
   51394 
   51395 /*
   51396 ** Make sure pBt->pTmpSpace points to an allocation of
   51397 ** MX_CELL_SIZE(pBt) bytes.
   51398 */
   51399 static void allocateTempSpace(BtShared *pBt){
   51400   if( !pBt->pTmpSpace ){
   51401     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   51402   }
   51403 }
   51404 
   51405 /*
   51406 ** Free the pBt->pTmpSpace allocation
   51407 */
   51408 static void freeTempSpace(BtShared *pBt){
   51409   sqlite3PageFree( pBt->pTmpSpace);
   51410   pBt->pTmpSpace = 0;
   51411 }
   51412 
   51413 /*
   51414 ** Close an open database and invalidate all cursors.
   51415 */
   51416 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   51417   BtShared *pBt = p->pBt;
   51418   BtCursor *pCur;
   51419 
   51420   /* Close all cursors opened via this handle.  */
   51421   assert( sqlite3_mutex_held(p->db->mutex) );
   51422   sqlite3BtreeEnter(p);
   51423   pCur = pBt->pCursor;
   51424   while( pCur ){
   51425     BtCursor *pTmp = pCur;
   51426     pCur = pCur->pNext;
   51427     if( pTmp->pBtree==p ){
   51428       sqlite3BtreeCloseCursor(pTmp);
   51429     }
   51430   }
   51431 
   51432   /* Rollback any active transaction and free the handle structure.
   51433   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   51434   ** this handle.
   51435   */
   51436   sqlite3BtreeRollback(p, SQLITE_OK);
   51437   sqlite3BtreeLeave(p);
   51438 
   51439   /* If there are still other outstanding references to the shared-btree
   51440   ** structure, return now. The remainder of this procedure cleans
   51441   ** up the shared-btree.
   51442   */
   51443   assert( p->wantToLock==0 && p->locked==0 );
   51444   if( !p->sharable || removeFromSharingList(pBt) ){
   51445     /* The pBt is no longer on the sharing list, so we can access
   51446     ** it without having to hold the mutex.
   51447     **
   51448     ** Clean out and delete the BtShared object.
   51449     */
   51450     assert( !pBt->pCursor );
   51451     sqlite3PagerClose(pBt->pPager);
   51452     if( pBt->xFreeSchema && pBt->pSchema ){
   51453       pBt->xFreeSchema(pBt->pSchema);
   51454     }
   51455     sqlite3DbFree(0, pBt->pSchema);
   51456     freeTempSpace(pBt);
   51457     sqlite3_free(pBt);
   51458   }
   51459 
   51460 #ifndef SQLITE_OMIT_SHARED_CACHE
   51461   assert( p->wantToLock==0 );
   51462   assert( p->locked==0 );
   51463   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   51464   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   51465 #endif
   51466 
   51467   sqlite3_free(p);
   51468   return SQLITE_OK;
   51469 }
   51470 
   51471 /*
   51472 ** Change the limit on the number of pages allowed in the cache.
   51473 **
   51474 ** The maximum number of cache pages is set to the absolute
   51475 ** value of mxPage.  If mxPage is negative, the pager will
   51476 ** operate asynchronously - it will not stop to do fsync()s
   51477 ** to insure data is written to the disk surface before
   51478 ** continuing.  Transactions still work if synchronous is off,
   51479 ** and the database cannot be corrupted if this program
   51480 ** crashes.  But if the operating system crashes or there is
   51481 ** an abrupt power failure when synchronous is off, the database
   51482 ** could be left in an inconsistent and unrecoverable state.
   51483 ** Synchronous is on by default so database corruption is not
   51484 ** normally a worry.
   51485 */
   51486 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   51487   BtShared *pBt = p->pBt;
   51488   assert( sqlite3_mutex_held(p->db->mutex) );
   51489   sqlite3BtreeEnter(p);
   51490   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   51491   sqlite3BtreeLeave(p);
   51492   return SQLITE_OK;
   51493 }
   51494 
   51495 /*
   51496 ** Change the way data is synced to disk in order to increase or decrease
   51497 ** how well the database resists damage due to OS crashes and power
   51498 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   51499 ** there is a high probability of damage)  Level 2 is the default.  There
   51500 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   51501 ** probability of damage to near zero but with a write performance reduction.
   51502 */
   51503 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   51504 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
   51505   Btree *p,              /* The btree to set the safety level on */
   51506   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   51507   int fullSync,          /* PRAGMA fullfsync. */
   51508   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
   51509 ){
   51510   BtShared *pBt = p->pBt;
   51511   assert( sqlite3_mutex_held(p->db->mutex) );
   51512   assert( level>=1 && level<=3 );
   51513   sqlite3BtreeEnter(p);
   51514   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
   51515   sqlite3BtreeLeave(p);
   51516   return SQLITE_OK;
   51517 }
   51518 #endif
   51519 
   51520 /*
   51521 ** Return TRUE if the given btree is set to safety level 1.  In other
   51522 ** words, return TRUE if no sync() occurs on the disk files.
   51523 */
   51524 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   51525   BtShared *pBt = p->pBt;
   51526   int rc;
   51527   assert( sqlite3_mutex_held(p->db->mutex) );
   51528   sqlite3BtreeEnter(p);
   51529   assert( pBt && pBt->pPager );
   51530   rc = sqlite3PagerNosync(pBt->pPager);
   51531   sqlite3BtreeLeave(p);
   51532   return rc;
   51533 }
   51534 
   51535 /*
   51536 ** Change the default pages size and the number of reserved bytes per page.
   51537 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   51538 ** without changing anything.
   51539 **
   51540 ** The page size must be a power of 2 between 512 and 65536.  If the page
   51541 ** size supplied does not meet this constraint then the page size is not
   51542 ** changed.
   51543 **
   51544 ** Page sizes are constrained to be a power of two so that the region
   51545 ** of the database file used for locking (beginning at PENDING_BYTE,
   51546 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   51547 ** at the beginning of a page.
   51548 **
   51549 ** If parameter nReserve is less than zero, then the number of reserved
   51550 ** bytes per page is left unchanged.
   51551 **
   51552 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
   51553 ** and autovacuum mode can no longer be changed.
   51554 */
   51555 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   51556   int rc = SQLITE_OK;
   51557   BtShared *pBt = p->pBt;
   51558   assert( nReserve>=-1 && nReserve<=255 );
   51559   sqlite3BtreeEnter(p);
   51560   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
   51561     sqlite3BtreeLeave(p);
   51562     return SQLITE_READONLY;
   51563   }
   51564   if( nReserve<0 ){
   51565     nReserve = pBt->pageSize - pBt->usableSize;
   51566   }
   51567   assert( nReserve>=0 && nReserve<=255 );
   51568   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   51569         ((pageSize-1)&pageSize)==0 ){
   51570     assert( (pageSize & 7)==0 );
   51571     assert( !pBt->pPage1 && !pBt->pCursor );
   51572     pBt->pageSize = (u32)pageSize;
   51573     freeTempSpace(pBt);
   51574   }
   51575   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   51576   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   51577   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51578   sqlite3BtreeLeave(p);
   51579   return rc;
   51580 }
   51581 
   51582 /*
   51583 ** Return the currently defined page size
   51584 */
   51585 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   51586   return p->pBt->pageSize;
   51587 }
   51588 
   51589 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   51590 /*
   51591 ** Return the number of bytes of space at the end of every page that
   51592 ** are intentually left unused.  This is the "reserved" space that is
   51593 ** sometimes used by extensions.
   51594 */
   51595 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   51596   int n;
   51597   sqlite3BtreeEnter(p);
   51598   n = p->pBt->pageSize - p->pBt->usableSize;
   51599   sqlite3BtreeLeave(p);
   51600   return n;
   51601 }
   51602 
   51603 /*
   51604 ** Set the maximum page count for a database if mxPage is positive.
   51605 ** No changes are made if mxPage is 0 or negative.
   51606 ** Regardless of the value of mxPage, return the maximum page count.
   51607 */
   51608 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   51609   int n;
   51610   sqlite3BtreeEnter(p);
   51611   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   51612   sqlite3BtreeLeave(p);
   51613   return n;
   51614 }
   51615 
   51616 /*
   51617 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
   51618 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
   51619 ** setting after the change.
   51620 */
   51621 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   51622   int b;
   51623   if( p==0 ) return 0;
   51624   sqlite3BtreeEnter(p);
   51625   if( newFlag>=0 ){
   51626     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
   51627     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
   51628   }
   51629   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
   51630   sqlite3BtreeLeave(p);
   51631   return b;
   51632 }
   51633 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   51634 
   51635 /*
   51636 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   51637 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   51638 ** is disabled. The default value for the auto-vacuum property is
   51639 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   51640 */
   51641 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   51642 #ifdef SQLITE_OMIT_AUTOVACUUM
   51643   return SQLITE_READONLY;
   51644 #else
   51645   BtShared *pBt = p->pBt;
   51646   int rc = SQLITE_OK;
   51647   u8 av = (u8)autoVacuum;
   51648 
   51649   sqlite3BtreeEnter(p);
   51650   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
   51651     rc = SQLITE_READONLY;
   51652   }else{
   51653     pBt->autoVacuum = av ?1:0;
   51654     pBt->incrVacuum = av==2 ?1:0;
   51655   }
   51656   sqlite3BtreeLeave(p);
   51657   return rc;
   51658 #endif
   51659 }
   51660 
   51661 /*
   51662 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   51663 ** enabled 1 is returned. Otherwise 0.
   51664 */
   51665 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   51666 #ifdef SQLITE_OMIT_AUTOVACUUM
   51667   return BTREE_AUTOVACUUM_NONE;
   51668 #else
   51669   int rc;
   51670   sqlite3BtreeEnter(p);
   51671   rc = (
   51672     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   51673     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   51674     BTREE_AUTOVACUUM_INCR
   51675   );
   51676   sqlite3BtreeLeave(p);
   51677   return rc;
   51678 #endif
   51679 }
   51680 
   51681 
   51682 /*
   51683 ** Get a reference to pPage1 of the database file.  This will
   51684 ** also acquire a readlock on that file.
   51685 **
   51686 ** SQLITE_OK is returned on success.  If the file is not a
   51687 ** well-formed database file, then SQLITE_CORRUPT is returned.
   51688 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   51689 ** is returned if we run out of memory.
   51690 */
   51691 static int lockBtree(BtShared *pBt){
   51692   int rc;              /* Result code from subfunctions */
   51693   MemPage *pPage1;     /* Page 1 of the database file */
   51694   int nPage;           /* Number of pages in the database */
   51695   int nPageFile = 0;   /* Number of pages in the database file */
   51696   int nPageHeader;     /* Number of pages in the database according to hdr */
   51697 
   51698   assert( sqlite3_mutex_held(pBt->mutex) );
   51699   assert( pBt->pPage1==0 );
   51700   rc = sqlite3PagerSharedLock(pBt->pPager);
   51701   if( rc!=SQLITE_OK ) return rc;
   51702   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   51703   if( rc!=SQLITE_OK ) return rc;
   51704 
   51705   /* Do some checking to help insure the file we opened really is
   51706   ** a valid database file.
   51707   */
   51708   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   51709   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   51710   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   51711     nPage = nPageFile;
   51712   }
   51713   if( nPage>0 ){
   51714     u32 pageSize;
   51715     u32 usableSize;
   51716     u8 *page1 = pPage1->aData;
   51717     rc = SQLITE_NOTADB;
   51718     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   51719       goto page1_init_failed;
   51720     }
   51721 
   51722 #ifdef SQLITE_OMIT_WAL
   51723     if( page1[18]>1 ){
   51724       pBt->btsFlags |= BTS_READ_ONLY;
   51725     }
   51726     if( page1[19]>1 ){
   51727       goto page1_init_failed;
   51728     }
   51729 #else
   51730     if( page1[18]>2 ){
   51731       pBt->btsFlags |= BTS_READ_ONLY;
   51732     }
   51733     if( page1[19]>2 ){
   51734       goto page1_init_failed;
   51735     }
   51736 
   51737     /* If the write version is set to 2, this database should be accessed
   51738     ** in WAL mode. If the log is not already open, open it now. Then
   51739     ** return SQLITE_OK and return without populating BtShared.pPage1.
   51740     ** The caller detects this and calls this function again. This is
   51741     ** required as the version of page 1 currently in the page1 buffer
   51742     ** may not be the latest version - there may be a newer one in the log
   51743     ** file.
   51744     */
   51745     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
   51746       int isOpen = 0;
   51747       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   51748       if( rc!=SQLITE_OK ){
   51749         goto page1_init_failed;
   51750       }else if( isOpen==0 ){
   51751         releasePage(pPage1);
   51752         return SQLITE_OK;
   51753       }
   51754       rc = SQLITE_NOTADB;
   51755     }
   51756 #endif
   51757 
   51758     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   51759     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   51760     ** The original design allowed these amounts to vary, but as of
   51761     ** version 3.6.0, we require them to be fixed.
   51762     */
   51763     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   51764       goto page1_init_failed;
   51765     }
   51766     pageSize = (page1[16]<<8) | (page1[17]<<16);
   51767     if( ((pageSize-1)&pageSize)!=0
   51768      || pageSize>SQLITE_MAX_PAGE_SIZE
   51769      || pageSize<=256
   51770     ){
   51771       goto page1_init_failed;
   51772     }
   51773     assert( (pageSize & 7)==0 );
   51774     usableSize = pageSize - page1[20];
   51775     if( (u32)pageSize!=pBt->pageSize ){
   51776       /* After reading the first page of the database assuming a page size
   51777       ** of BtShared.pageSize, we have discovered that the page-size is
   51778       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   51779       ** zero and return SQLITE_OK. The caller will call this function
   51780       ** again with the correct page-size.
   51781       */
   51782       releasePage(pPage1);
   51783       pBt->usableSize = usableSize;
   51784       pBt->pageSize = pageSize;
   51785       freeTempSpace(pBt);
   51786       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   51787                                    pageSize-usableSize);
   51788       return rc;
   51789     }
   51790     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
   51791       rc = SQLITE_CORRUPT_BKPT;
   51792       goto page1_init_failed;
   51793     }
   51794     if( usableSize<480 ){
   51795       goto page1_init_failed;
   51796     }
   51797     pBt->pageSize = pageSize;
   51798     pBt->usableSize = usableSize;
   51799 #ifndef SQLITE_OMIT_AUTOVACUUM
   51800     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   51801     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   51802 #endif
   51803   }
   51804 
   51805   /* maxLocal is the maximum amount of payload to store locally for
   51806   ** a cell.  Make sure it is small enough so that at least minFanout
   51807   ** cells can will fit on one page.  We assume a 10-byte page header.
   51808   ** Besides the payload, the cell must store:
   51809   **     2-byte pointer to the cell
   51810   **     4-byte child pointer
   51811   **     9-byte nKey value
   51812   **     4-byte nData value
   51813   **     4-byte overflow page pointer
   51814   ** So a cell consists of a 2-byte pointer, a header which is as much as
   51815   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   51816   ** page pointer.
   51817   */
   51818   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   51819   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   51820   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   51821   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   51822   if( pBt->maxLocal>127 ){
   51823     pBt->max1bytePayload = 127;
   51824   }else{
   51825     pBt->max1bytePayload = (u8)pBt->maxLocal;
   51826   }
   51827   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   51828   pBt->pPage1 = pPage1;
   51829   pBt->nPage = nPage;
   51830   return SQLITE_OK;
   51831 
   51832 page1_init_failed:
   51833   releasePage(pPage1);
   51834   pBt->pPage1 = 0;
   51835   return rc;
   51836 }
   51837 
   51838 /*
   51839 ** If there are no outstanding cursors and we are not in the middle
   51840 ** of a transaction but there is a read lock on the database, then
   51841 ** this routine unrefs the first page of the database file which
   51842 ** has the effect of releasing the read lock.
   51843 **
   51844 ** If there is a transaction in progress, this routine is a no-op.
   51845 */
   51846 static void unlockBtreeIfUnused(BtShared *pBt){
   51847   assert( sqlite3_mutex_held(pBt->mutex) );
   51848   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
   51849   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   51850     assert( pBt->pPage1->aData );
   51851     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   51852     assert( pBt->pPage1->aData );
   51853     releasePage(pBt->pPage1);
   51854     pBt->pPage1 = 0;
   51855   }
   51856 }
   51857 
   51858 /*
   51859 ** If pBt points to an empty file then convert that empty file
   51860 ** into a new empty database by initializing the first page of
   51861 ** the database.
   51862 */
   51863 static int newDatabase(BtShared *pBt){
   51864   MemPage *pP1;
   51865   unsigned char *data;
   51866   int rc;
   51867 
   51868   assert( sqlite3_mutex_held(pBt->mutex) );
   51869   if( pBt->nPage>0 ){
   51870     return SQLITE_OK;
   51871   }
   51872   pP1 = pBt->pPage1;
   51873   assert( pP1!=0 );
   51874   data = pP1->aData;
   51875   rc = sqlite3PagerWrite(pP1->pDbPage);
   51876   if( rc ) return rc;
   51877   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   51878   assert( sizeof(zMagicHeader)==16 );
   51879   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   51880   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   51881   data[18] = 1;
   51882   data[19] = 1;
   51883   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   51884   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   51885   data[21] = 64;
   51886   data[22] = 32;
   51887   data[23] = 32;
   51888   memset(&data[24], 0, 100-24);
   51889   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   51890   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51891 #ifndef SQLITE_OMIT_AUTOVACUUM
   51892   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   51893   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   51894   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   51895   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   51896 #endif
   51897   pBt->nPage = 1;
   51898   data[31] = 1;
   51899   return SQLITE_OK;
   51900 }
   51901 
   51902 /*
   51903 ** Attempt to start a new transaction. A write-transaction
   51904 ** is started if the second argument is nonzero, otherwise a read-
   51905 ** transaction.  If the second argument is 2 or more and exclusive
   51906 ** transaction is started, meaning that no other process is allowed
   51907 ** to access the database.  A preexisting transaction may not be
   51908 ** upgraded to exclusive by calling this routine a second time - the
   51909 ** exclusivity flag only works for a new transaction.
   51910 **
   51911 ** A write-transaction must be started before attempting any
   51912 ** changes to the database.  None of the following routines
   51913 ** will work unless a transaction is started first:
   51914 **
   51915 **      sqlite3BtreeCreateTable()
   51916 **      sqlite3BtreeCreateIndex()
   51917 **      sqlite3BtreeClearTable()
   51918 **      sqlite3BtreeDropTable()
   51919 **      sqlite3BtreeInsert()
   51920 **      sqlite3BtreeDelete()
   51921 **      sqlite3BtreeUpdateMeta()
   51922 **
   51923 ** If an initial attempt to acquire the lock fails because of lock contention
   51924 ** and the database was previously unlocked, then invoke the busy handler
   51925 ** if there is one.  But if there was previously a read-lock, do not
   51926 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   51927 ** returned when there is already a read-lock in order to avoid a deadlock.
   51928 **
   51929 ** Suppose there are two processes A and B.  A has a read lock and B has
   51930 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   51931 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   51932 ** One or the other of the two processes must give way or there can be
   51933 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   51934 ** when A already has a read lock, we encourage A to give up and let B
   51935 ** proceed.
   51936 */
   51937 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   51938   sqlite3 *pBlock = 0;
   51939   BtShared *pBt = p->pBt;
   51940   int rc = SQLITE_OK;
   51941 
   51942   sqlite3BtreeEnter(p);
   51943   btreeIntegrity(p);
   51944 
   51945   /* If the btree is already in a write-transaction, or it
   51946   ** is already in a read-transaction and a read-transaction
   51947   ** is requested, this is a no-op.
   51948   */
   51949   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   51950     goto trans_begun;
   51951   }
   51952 
   51953   /* Write transactions are not possible on a read-only database */
   51954   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
   51955     rc = SQLITE_READONLY;
   51956     goto trans_begun;
   51957   }
   51958 
   51959 #ifndef SQLITE_OMIT_SHARED_CACHE
   51960   /* If another database handle has already opened a write transaction
   51961   ** on this shared-btree structure and a second write transaction is
   51962   ** requested, return SQLITE_LOCKED.
   51963   */
   51964   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
   51965    || (pBt->btsFlags & BTS_PENDING)!=0
   51966   ){
   51967     pBlock = pBt->pWriter->db;
   51968   }else if( wrflag>1 ){
   51969     BtLock *pIter;
   51970     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51971       if( pIter->pBtree!=p ){
   51972         pBlock = pIter->pBtree->db;
   51973         break;
   51974       }
   51975     }
   51976   }
   51977   if( pBlock ){
   51978     sqlite3ConnectionBlocked(p->db, pBlock);
   51979     rc = SQLITE_LOCKED_SHAREDCACHE;
   51980     goto trans_begun;
   51981   }
   51982 #endif
   51983 
   51984   /* Any read-only or read-write transaction implies a read-lock on
   51985   ** page 1. So if some other shared-cache client already has a write-lock
   51986   ** on page 1, the transaction cannot be opened. */
   51987   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   51988   if( SQLITE_OK!=rc ) goto trans_begun;
   51989 
   51990   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   51991   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   51992   do {
   51993     /* Call lockBtree() until either pBt->pPage1 is populated or
   51994     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   51995     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   51996     ** reading page 1 it discovers that the page-size of the database
   51997     ** file is not pBt->pageSize. In this case lockBtree() will update
   51998     ** pBt->pageSize to the page-size of the file on disk.
   51999     */
   52000     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   52001 
   52002     if( rc==SQLITE_OK && wrflag ){
   52003       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
   52004         rc = SQLITE_READONLY;
   52005       }else{
   52006         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   52007         if( rc==SQLITE_OK ){
   52008           rc = newDatabase(pBt);
   52009         }
   52010       }
   52011     }
   52012 
   52013     if( rc!=SQLITE_OK ){
   52014       unlockBtreeIfUnused(pBt);
   52015     }
   52016   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   52017           btreeInvokeBusyHandler(pBt) );
   52018 
   52019   if( rc==SQLITE_OK ){
   52020     if( p->inTrans==TRANS_NONE ){
   52021       pBt->nTransaction++;
   52022 #ifndef SQLITE_OMIT_SHARED_CACHE
   52023       if( p->sharable ){
   52024 	assert( p->lock.pBtree==p && p->lock.iTable==1 );
   52025         p->lock.eLock = READ_LOCK;
   52026         p->lock.pNext = pBt->pLock;
   52027         pBt->pLock = &p->lock;
   52028       }
   52029 #endif
   52030     }
   52031     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   52032     if( p->inTrans>pBt->inTransaction ){
   52033       pBt->inTransaction = p->inTrans;
   52034     }
   52035     if( wrflag ){
   52036       MemPage *pPage1 = pBt->pPage1;
   52037 #ifndef SQLITE_OMIT_SHARED_CACHE
   52038       assert( !pBt->pWriter );
   52039       pBt->pWriter = p;
   52040       pBt->btsFlags &= ~BTS_EXCLUSIVE;
   52041       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
   52042 #endif
   52043 
   52044       /* If the db-size header field is incorrect (as it may be if an old
   52045       ** client has been writing the database file), update it now. Doing
   52046       ** this sooner rather than later means the database size can safely
   52047       ** re-read the database size from page 1 if a savepoint or transaction
   52048       ** rollback occurs within the transaction.
   52049       */
   52050       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   52051         rc = sqlite3PagerWrite(pPage1->pDbPage);
   52052         if( rc==SQLITE_OK ){
   52053           put4byte(&pPage1->aData[28], pBt->nPage);
   52054         }
   52055       }
   52056     }
   52057   }
   52058 
   52059 
   52060 trans_begun:
   52061   if( rc==SQLITE_OK && wrflag ){
   52062     /* This call makes sure that the pager has the correct number of
   52063     ** open savepoints. If the second parameter is greater than 0 and
   52064     ** the sub-journal is not already open, then it will be opened here.
   52065     */
   52066     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   52067   }
   52068 
   52069   btreeIntegrity(p);
   52070   sqlite3BtreeLeave(p);
   52071   return rc;
   52072 }
   52073 
   52074 #ifndef SQLITE_OMIT_AUTOVACUUM
   52075 
   52076 /*
   52077 ** Set the pointer-map entries for all children of page pPage. Also, if
   52078 ** pPage contains cells that point to overflow pages, set the pointer
   52079 ** map entries for the overflow pages as well.
   52080 */
   52081 static int setChildPtrmaps(MemPage *pPage){
   52082   int i;                             /* Counter variable */
   52083   int nCell;                         /* Number of cells in page pPage */
   52084   int rc;                            /* Return code */
   52085   BtShared *pBt = pPage->pBt;
   52086   u8 isInitOrig = pPage->isInit;
   52087   Pgno pgno = pPage->pgno;
   52088 
   52089   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52090   rc = btreeInitPage(pPage);
   52091   if( rc!=SQLITE_OK ){
   52092     goto set_child_ptrmaps_out;
   52093   }
   52094   nCell = pPage->nCell;
   52095 
   52096   for(i=0; i<nCell; i++){
   52097     u8 *pCell = findCell(pPage, i);
   52098 
   52099     ptrmapPutOvflPtr(pPage, pCell, &rc);
   52100 
   52101     if( !pPage->leaf ){
   52102       Pgno childPgno = get4byte(pCell);
   52103       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   52104     }
   52105   }
   52106 
   52107   if( !pPage->leaf ){
   52108     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   52109     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   52110   }
   52111 
   52112 set_child_ptrmaps_out:
   52113   pPage->isInit = isInitOrig;
   52114   return rc;
   52115 }
   52116 
   52117 /*
   52118 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   52119 ** that it points to iTo. Parameter eType describes the type of pointer to
   52120 ** be modified, as  follows:
   52121 **
   52122 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   52123 **                   page of pPage.
   52124 **
   52125 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   52126 **                   page pointed to by one of the cells on pPage.
   52127 **
   52128 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   52129 **                   overflow page in the list.
   52130 */
   52131 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   52132   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52133   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52134   if( eType==PTRMAP_OVERFLOW2 ){
   52135     /* The pointer is always the first 4 bytes of the page in this case.  */
   52136     if( get4byte(pPage->aData)!=iFrom ){
   52137       return SQLITE_CORRUPT_BKPT;
   52138     }
   52139     put4byte(pPage->aData, iTo);
   52140   }else{
   52141     u8 isInitOrig = pPage->isInit;
   52142     int i;
   52143     int nCell;
   52144 
   52145     btreeInitPage(pPage);
   52146     nCell = pPage->nCell;
   52147 
   52148     for(i=0; i<nCell; i++){
   52149       u8 *pCell = findCell(pPage, i);
   52150       if( eType==PTRMAP_OVERFLOW1 ){
   52151         CellInfo info;
   52152         btreeParseCellPtr(pPage, pCell, &info);
   52153         if( info.iOverflow
   52154          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
   52155          && iFrom==get4byte(&pCell[info.iOverflow])
   52156         ){
   52157           put4byte(&pCell[info.iOverflow], iTo);
   52158           break;
   52159         }
   52160       }else{
   52161         if( get4byte(pCell)==iFrom ){
   52162           put4byte(pCell, iTo);
   52163           break;
   52164         }
   52165       }
   52166     }
   52167 
   52168     if( i==nCell ){
   52169       if( eType!=PTRMAP_BTREE ||
   52170           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   52171         return SQLITE_CORRUPT_BKPT;
   52172       }
   52173       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   52174     }
   52175 
   52176     pPage->isInit = isInitOrig;
   52177   }
   52178   return SQLITE_OK;
   52179 }
   52180 
   52181 
   52182 /*
   52183 ** Move the open database page pDbPage to location iFreePage in the
   52184 ** database. The pDbPage reference remains valid.
   52185 **
   52186 ** The isCommit flag indicates that there is no need to remember that
   52187 ** the journal needs to be sync()ed before database page pDbPage->pgno
   52188 ** can be written to. The caller has already promised not to write to that
   52189 ** page.
   52190 */
   52191 static int relocatePage(
   52192   BtShared *pBt,           /* Btree */
   52193   MemPage *pDbPage,        /* Open page to move */
   52194   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   52195   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   52196   Pgno iFreePage,          /* The location to move pDbPage to */
   52197   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   52198 ){
   52199   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   52200   Pgno iDbPage = pDbPage->pgno;
   52201   Pager *pPager = pBt->pPager;
   52202   int rc;
   52203 
   52204   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   52205       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   52206   assert( sqlite3_mutex_held(pBt->mutex) );
   52207   assert( pDbPage->pBt==pBt );
   52208 
   52209   /* Move page iDbPage from its current location to page number iFreePage */
   52210   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   52211       iDbPage, iFreePage, iPtrPage, eType));
   52212   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   52213   if( rc!=SQLITE_OK ){
   52214     return rc;
   52215   }
   52216   pDbPage->pgno = iFreePage;
   52217 
   52218   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   52219   ** that point to overflow pages. The pointer map entries for all these
   52220   ** pages need to be changed.
   52221   **
   52222   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   52223   ** pointer to a subsequent overflow page. If this is the case, then
   52224   ** the pointer map needs to be updated for the subsequent overflow page.
   52225   */
   52226   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   52227     rc = setChildPtrmaps(pDbPage);
   52228     if( rc!=SQLITE_OK ){
   52229       return rc;
   52230     }
   52231   }else{
   52232     Pgno nextOvfl = get4byte(pDbPage->aData);
   52233     if( nextOvfl!=0 ){
   52234       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   52235       if( rc!=SQLITE_OK ){
   52236         return rc;
   52237       }
   52238     }
   52239   }
   52240 
   52241   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   52242   ** that it points at iFreePage. Also fix the pointer map entry for
   52243   ** iPtrPage.
   52244   */
   52245   if( eType!=PTRMAP_ROOTPAGE ){
   52246     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   52247     if( rc!=SQLITE_OK ){
   52248       return rc;
   52249     }
   52250     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   52251     if( rc!=SQLITE_OK ){
   52252       releasePage(pPtrPage);
   52253       return rc;
   52254     }
   52255     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   52256     releasePage(pPtrPage);
   52257     if( rc==SQLITE_OK ){
   52258       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   52259     }
   52260   }
   52261   return rc;
   52262 }
   52263 
   52264 /* Forward declaration required by incrVacuumStep(). */
   52265 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   52266 
   52267 /*
   52268 ** Perform a single step of an incremental-vacuum. If successful,
   52269 ** return SQLITE_OK. If there is no work to do (and therefore no
   52270 ** point in calling this function again), return SQLITE_DONE.
   52271 **
   52272 ** More specificly, this function attempts to re-organize the
   52273 ** database so that the last page of the file currently in use
   52274 ** is no longer in use.
   52275 **
   52276 ** If the nFin parameter is non-zero, this function assumes
   52277 ** that the caller will keep calling incrVacuumStep() until
   52278 ** it returns SQLITE_DONE or an error, and that nFin is the
   52279 ** number of pages the database file will contain after this
   52280 ** process is complete.  If nFin is zero, it is assumed that
   52281 ** incrVacuumStep() will be called a finite amount of times
   52282 ** which may or may not empty the freelist.  A full autovacuum
   52283 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
   52284 */
   52285 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
   52286   Pgno nFreeList;           /* Number of pages still on the free-list */
   52287   int rc;
   52288 
   52289   assert( sqlite3_mutex_held(pBt->mutex) );
   52290   assert( iLastPg>nFin );
   52291 
   52292   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   52293     u8 eType;
   52294     Pgno iPtrPage;
   52295 
   52296     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   52297     if( nFreeList==0 ){
   52298       return SQLITE_DONE;
   52299     }
   52300 
   52301     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   52302     if( rc!=SQLITE_OK ){
   52303       return rc;
   52304     }
   52305     if( eType==PTRMAP_ROOTPAGE ){
   52306       return SQLITE_CORRUPT_BKPT;
   52307     }
   52308 
   52309     if( eType==PTRMAP_FREEPAGE ){
   52310       if( nFin==0 ){
   52311         /* Remove the page from the files free-list. This is not required
   52312         ** if nFin is non-zero. In that case, the free-list will be
   52313         ** truncated to zero after this function returns, so it doesn't
   52314         ** matter if it still contains some garbage entries.
   52315         */
   52316         Pgno iFreePg;
   52317         MemPage *pFreePg;
   52318         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
   52319         if( rc!=SQLITE_OK ){
   52320           return rc;
   52321         }
   52322         assert( iFreePg==iLastPg );
   52323         releasePage(pFreePg);
   52324       }
   52325     } else {
   52326       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   52327       MemPage *pLastPg;
   52328 
   52329       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   52330       if( rc!=SQLITE_OK ){
   52331         return rc;
   52332       }
   52333 
   52334       /* If nFin is zero, this loop runs exactly once and page pLastPg
   52335       ** is swapped with the first free page pulled off the free list.
   52336       **
   52337       ** On the other hand, if nFin is greater than zero, then keep
   52338       ** looping until a free-page located within the first nFin pages
   52339       ** of the file is found.
   52340       */
   52341       do {
   52342         MemPage *pFreePg;
   52343         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
   52344         if( rc!=SQLITE_OK ){
   52345           releasePage(pLastPg);
   52346           return rc;
   52347         }
   52348         releasePage(pFreePg);
   52349       }while( nFin!=0 && iFreePg>nFin );
   52350       assert( iFreePg<iLastPg );
   52351 
   52352       rc = sqlite3PagerWrite(pLastPg->pDbPage);
   52353       if( rc==SQLITE_OK ){
   52354         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
   52355       }
   52356       releasePage(pLastPg);
   52357       if( rc!=SQLITE_OK ){
   52358         return rc;
   52359       }
   52360     }
   52361   }
   52362 
   52363   if( nFin==0 ){
   52364     iLastPg--;
   52365     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
   52366       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
   52367         MemPage *pPg;
   52368         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
   52369         if( rc!=SQLITE_OK ){
   52370           return rc;
   52371         }
   52372         rc = sqlite3PagerWrite(pPg->pDbPage);
   52373         releasePage(pPg);
   52374         if( rc!=SQLITE_OK ){
   52375           return rc;
   52376         }
   52377       }
   52378       iLastPg--;
   52379     }
   52380     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
   52381     pBt->nPage = iLastPg;
   52382   }
   52383   return SQLITE_OK;
   52384 }
   52385 
   52386 /*
   52387 ** A write-transaction must be opened before calling this function.
   52388 ** It performs a single unit of work towards an incremental vacuum.
   52389 **
   52390 ** If the incremental vacuum is finished after this function has run,
   52391 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   52392 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   52393 */
   52394 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   52395   int rc;
   52396   BtShared *pBt = p->pBt;
   52397 
   52398   sqlite3BtreeEnter(p);
   52399   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   52400   if( !pBt->autoVacuum ){
   52401     rc = SQLITE_DONE;
   52402   }else{
   52403     invalidateAllOverflowCache(pBt);
   52404     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
   52405     if( rc==SQLITE_OK ){
   52406       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   52407       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   52408     }
   52409   }
   52410   sqlite3BtreeLeave(p);
   52411   return rc;
   52412 }
   52413 
   52414 /*
   52415 ** This routine is called prior to sqlite3PagerCommit when a transaction
   52416 ** is commited for an auto-vacuum database.
   52417 **
   52418 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   52419 ** the database file should be truncated to during the commit process.
   52420 ** i.e. the database has been reorganized so that only the first *pnTrunc
   52421 ** pages are in use.
   52422 */
   52423 static int autoVacuumCommit(BtShared *pBt){
   52424   int rc = SQLITE_OK;
   52425   Pager *pPager = pBt->pPager;
   52426   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   52427 
   52428   assert( sqlite3_mutex_held(pBt->mutex) );
   52429   invalidateAllOverflowCache(pBt);
   52430   assert(pBt->autoVacuum);
   52431   if( !pBt->incrVacuum ){
   52432     Pgno nFin;         /* Number of pages in database after autovacuuming */
   52433     Pgno nFree;        /* Number of pages on the freelist initially */
   52434     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
   52435     Pgno iFree;        /* The next page to be freed */
   52436     int nEntry;        /* Number of entries on one ptrmap page */
   52437     Pgno nOrig;        /* Database size before freeing */
   52438 
   52439     nOrig = btreePagecount(pBt);
   52440     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   52441       /* It is not possible to create a database for which the final page
   52442       ** is either a pointer-map page or the pending-byte page. If one
   52443       ** is encountered, this indicates corruption.
   52444       */
   52445       return SQLITE_CORRUPT_BKPT;
   52446     }
   52447 
   52448     nFree = get4byte(&pBt->pPage1->aData[36]);
   52449     nEntry = pBt->usableSize/5;
   52450     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   52451     nFin = nOrig - nFree - nPtrmap;
   52452     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   52453       nFin--;
   52454     }
   52455     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   52456       nFin--;
   52457     }
   52458     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   52459 
   52460     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   52461       rc = incrVacuumStep(pBt, nFin, iFree);
   52462     }
   52463     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   52464       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   52465       put4byte(&pBt->pPage1->aData[32], 0);
   52466       put4byte(&pBt->pPage1->aData[36], 0);
   52467       put4byte(&pBt->pPage1->aData[28], nFin);
   52468       sqlite3PagerTruncateImage(pBt->pPager, nFin);
   52469       pBt->nPage = nFin;
   52470     }
   52471     if( rc!=SQLITE_OK ){
   52472       sqlite3PagerRollback(pPager);
   52473     }
   52474   }
   52475 
   52476   assert( nRef==sqlite3PagerRefcount(pPager) );
   52477   return rc;
   52478 }
   52479 
   52480 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   52481 # define setChildPtrmaps(x) SQLITE_OK
   52482 #endif
   52483 
   52484 /*
   52485 ** This routine does the first phase of a two-phase commit.  This routine
   52486 ** causes a rollback journal to be created (if it does not already exist)
   52487 ** and populated with enough information so that if a power loss occurs
   52488 ** the database can be restored to its original state by playing back
   52489 ** the journal.  Then the contents of the journal are flushed out to
   52490 ** the disk.  After the journal is safely on oxide, the changes to the
   52491 ** database are written into the database file and flushed to oxide.
   52492 ** At the end of this call, the rollback journal still exists on the
   52493 ** disk and we are still holding all locks, so the transaction has not
   52494 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   52495 ** commit process.
   52496 **
   52497 ** This call is a no-op if no write-transaction is currently active on pBt.
   52498 **
   52499 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   52500 ** the name of a master journal file that should be written into the
   52501 ** individual journal file, or is NULL, indicating no master journal file
   52502 ** (single database transaction).
   52503 **
   52504 ** When this is called, the master journal should already have been
   52505 ** created, populated with this journal pointer and synced to disk.
   52506 **
   52507 ** Once this is routine has returned, the only thing required to commit
   52508 ** the write-transaction for this database file is to delete the journal.
   52509 */
   52510 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   52511   int rc = SQLITE_OK;
   52512   if( p->inTrans==TRANS_WRITE ){
   52513     BtShared *pBt = p->pBt;
   52514     sqlite3BtreeEnter(p);
   52515 #ifndef SQLITE_OMIT_AUTOVACUUM
   52516     if( pBt->autoVacuum ){
   52517       rc = autoVacuumCommit(pBt);
   52518       if( rc!=SQLITE_OK ){
   52519         sqlite3BtreeLeave(p);
   52520         return rc;
   52521       }
   52522     }
   52523 #endif
   52524     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   52525     sqlite3BtreeLeave(p);
   52526   }
   52527   return rc;
   52528 }
   52529 
   52530 /*
   52531 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   52532 ** at the conclusion of a transaction.
   52533 */
   52534 static void btreeEndTransaction(Btree *p){
   52535   BtShared *pBt = p->pBt;
   52536   assert( sqlite3BtreeHoldsMutex(p) );
   52537 
   52538   btreeClearHasContent(pBt);
   52539   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
   52540     /* If there are other active statements that belong to this database
   52541     ** handle, downgrade to a read-only transaction. The other statements
   52542     ** may still be reading from the database.  */
   52543     downgradeAllSharedCacheTableLocks(p);
   52544     p->inTrans = TRANS_READ;
   52545   }else{
   52546     /* If the handle had any kind of transaction open, decrement the
   52547     ** transaction count of the shared btree. If the transaction count
   52548     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   52549     ** call below will unlock the pager.  */
   52550     if( p->inTrans!=TRANS_NONE ){
   52551       clearAllSharedCacheTableLocks(p);
   52552       pBt->nTransaction--;
   52553       if( 0==pBt->nTransaction ){
   52554         pBt->inTransaction = TRANS_NONE;
   52555       }
   52556     }
   52557 
   52558     /* Set the current transaction state to TRANS_NONE and unlock the
   52559     ** pager if this call closed the only read or write transaction.  */
   52560     p->inTrans = TRANS_NONE;
   52561     unlockBtreeIfUnused(pBt);
   52562   }
   52563 
   52564   btreeIntegrity(p);
   52565 }
   52566 
   52567 /*
   52568 ** Commit the transaction currently in progress.
   52569 **
   52570 ** This routine implements the second phase of a 2-phase commit.  The
   52571 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   52572 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   52573 ** routine did all the work of writing information out to disk and flushing the
   52574 ** contents so that they are written onto the disk platter.  All this
   52575 ** routine has to do is delete or truncate or zero the header in the
   52576 ** the rollback journal (which causes the transaction to commit) and
   52577 ** drop locks.
   52578 **
   52579 ** Normally, if an error occurs while the pager layer is attempting to
   52580 ** finalize the underlying journal file, this function returns an error and
   52581 ** the upper layer will attempt a rollback. However, if the second argument
   52582 ** is non-zero then this b-tree transaction is part of a multi-file
   52583 ** transaction. In this case, the transaction has already been committed
   52584 ** (by deleting a master journal file) and the caller will ignore this
   52585 ** functions return code. So, even if an error occurs in the pager layer,
   52586 ** reset the b-tree objects internal state to indicate that the write
   52587 ** transaction has been closed. This is quite safe, as the pager will have
   52588 ** transitioned to the error state.
   52589 **
   52590 ** This will release the write lock on the database file.  If there
   52591 ** are no active cursors, it also releases the read lock.
   52592 */
   52593 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   52594 
   52595   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   52596   sqlite3BtreeEnter(p);
   52597   btreeIntegrity(p);
   52598 
   52599   /* If the handle has a write-transaction open, commit the shared-btrees
   52600   ** transaction and set the shared state to TRANS_READ.
   52601   */
   52602   if( p->inTrans==TRANS_WRITE ){
   52603     int rc;
   52604     BtShared *pBt = p->pBt;
   52605     assert( pBt->inTransaction==TRANS_WRITE );
   52606     assert( pBt->nTransaction>0 );
   52607     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   52608     if( rc!=SQLITE_OK && bCleanup==0 ){
   52609       sqlite3BtreeLeave(p);
   52610       return rc;
   52611     }
   52612     pBt->inTransaction = TRANS_READ;
   52613   }
   52614 
   52615   btreeEndTransaction(p);
   52616   sqlite3BtreeLeave(p);
   52617   return SQLITE_OK;
   52618 }
   52619 
   52620 /*
   52621 ** Do both phases of a commit.
   52622 */
   52623 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   52624   int rc;
   52625   sqlite3BtreeEnter(p);
   52626   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   52627   if( rc==SQLITE_OK ){
   52628     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
   52629   }
   52630   sqlite3BtreeLeave(p);
   52631   return rc;
   52632 }
   52633 
   52634 #ifndef NDEBUG
   52635 /*
   52636 ** Return the number of write-cursors open on this handle. This is for use
   52637 ** in assert() expressions, so it is only compiled if NDEBUG is not
   52638 ** defined.
   52639 **
   52640 ** For the purposes of this routine, a write-cursor is any cursor that
   52641 ** is capable of writing to the databse.  That means the cursor was
   52642 ** originally opened for writing and the cursor has not be disabled
   52643 ** by having its state changed to CURSOR_FAULT.
   52644 */
   52645 static int countWriteCursors(BtShared *pBt){
   52646   BtCursor *pCur;
   52647   int r = 0;
   52648   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   52649     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
   52650   }
   52651   return r;
   52652 }
   52653 #endif
   52654 
   52655 /*
   52656 ** This routine sets the state to CURSOR_FAULT and the error
   52657 ** code to errCode for every cursor on BtShared that pBtree
   52658 ** references.
   52659 **
   52660 ** Every cursor is tripped, including cursors that belong
   52661 ** to other database connections that happen to be sharing
   52662 ** the cache with pBtree.
   52663 **
   52664 ** This routine gets called when a rollback occurs.
   52665 ** All cursors using the same cache must be tripped
   52666 ** to prevent them from trying to use the btree after
   52667 ** the rollback.  The rollback may have deleted tables
   52668 ** or moved root pages, so it is not sufficient to
   52669 ** save the state of the cursor.  The cursor must be
   52670 ** invalidated.
   52671 */
   52672 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   52673   BtCursor *p;
   52674   if( pBtree==0 ) return;
   52675   sqlite3BtreeEnter(pBtree);
   52676   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   52677     int i;
   52678     sqlite3BtreeClearCursor(p);
   52679     p->eState = CURSOR_FAULT;
   52680     p->skipNext = errCode;
   52681     for(i=0; i<=p->iPage; i++){
   52682       releasePage(p->apPage[i]);
   52683       p->apPage[i] = 0;
   52684     }
   52685   }
   52686   sqlite3BtreeLeave(pBtree);
   52687 }
   52688 
   52689 /*
   52690 ** Rollback the transaction in progress.  All cursors will be
   52691 ** invalided by this operation.  Any attempt to use a cursor
   52692 ** that was open at the beginning of this operation will result
   52693 ** in an error.
   52694 **
   52695 ** This will release the write lock on the database file.  If there
   52696 ** are no active cursors, it also releases the read lock.
   52697 */
   52698 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
   52699   int rc;
   52700   BtShared *pBt = p->pBt;
   52701   MemPage *pPage1;
   52702 
   52703   sqlite3BtreeEnter(p);
   52704   if( tripCode==SQLITE_OK ){
   52705     rc = tripCode = saveAllCursors(pBt, 0, 0);
   52706   }else{
   52707     rc = SQLITE_OK;
   52708   }
   52709   if( tripCode ){
   52710     sqlite3BtreeTripAllCursors(p, tripCode);
   52711   }
   52712   btreeIntegrity(p);
   52713 
   52714   if( p->inTrans==TRANS_WRITE ){
   52715     int rc2;
   52716 
   52717     assert( TRANS_WRITE==pBt->inTransaction );
   52718     rc2 = sqlite3PagerRollback(pBt->pPager);
   52719     if( rc2!=SQLITE_OK ){
   52720       rc = rc2;
   52721     }
   52722 
   52723     /* The rollback may have destroyed the pPage1->aData value.  So
   52724     ** call btreeGetPage() on page 1 again to make
   52725     ** sure pPage1->aData is set correctly. */
   52726     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   52727       int nPage = get4byte(28+(u8*)pPage1->aData);
   52728       testcase( nPage==0 );
   52729       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   52730       testcase( pBt->nPage!=nPage );
   52731       pBt->nPage = nPage;
   52732       releasePage(pPage1);
   52733     }
   52734     assert( countWriteCursors(pBt)==0 );
   52735     pBt->inTransaction = TRANS_READ;
   52736   }
   52737 
   52738   btreeEndTransaction(p);
   52739   sqlite3BtreeLeave(p);
   52740   return rc;
   52741 }
   52742 
   52743 /*
   52744 ** Start a statement subtransaction. The subtransaction can can be rolled
   52745 ** back independently of the main transaction. You must start a transaction
   52746 ** before starting a subtransaction. The subtransaction is ended automatically
   52747 ** if the main transaction commits or rolls back.
   52748 **
   52749 ** Statement subtransactions are used around individual SQL statements
   52750 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   52751 ** error occurs within the statement, the effect of that one statement
   52752 ** can be rolled back without having to rollback the entire transaction.
   52753 **
   52754 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   52755 ** value passed as the second parameter is the total number of savepoints,
   52756 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   52757 ** are no active savepoints and no other statement-transactions open,
   52758 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   52759 ** using the sqlite3BtreeSavepoint() function.
   52760 */
   52761 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   52762   int rc;
   52763   BtShared *pBt = p->pBt;
   52764   sqlite3BtreeEnter(p);
   52765   assert( p->inTrans==TRANS_WRITE );
   52766   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   52767   assert( iStatement>0 );
   52768   assert( iStatement>p->db->nSavepoint );
   52769   assert( pBt->inTransaction==TRANS_WRITE );
   52770   /* At the pager level, a statement transaction is a savepoint with
   52771   ** an index greater than all savepoints created explicitly using
   52772   ** SQL statements. It is illegal to open, release or rollback any
   52773   ** such savepoints while the statement transaction savepoint is active.
   52774   */
   52775   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   52776   sqlite3BtreeLeave(p);
   52777   return rc;
   52778 }
   52779 
   52780 /*
   52781 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   52782 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   52783 ** savepoint identified by parameter iSavepoint, depending on the value
   52784 ** of op.
   52785 **
   52786 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   52787 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   52788 ** contents of the entire transaction are rolled back. This is different
   52789 ** from a normal transaction rollback, as no locks are released and the
   52790 ** transaction remains open.
   52791 */
   52792 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   52793   int rc = SQLITE_OK;
   52794   if( p && p->inTrans==TRANS_WRITE ){
   52795     BtShared *pBt = p->pBt;
   52796     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   52797     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   52798     sqlite3BtreeEnter(p);
   52799     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   52800     if( rc==SQLITE_OK ){
   52801       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
   52802         pBt->nPage = 0;
   52803       }
   52804       rc = newDatabase(pBt);
   52805       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   52806 
   52807       /* The database size was written into the offset 28 of the header
   52808       ** when the transaction started, so we know that the value at offset
   52809       ** 28 is nonzero. */
   52810       assert( pBt->nPage>0 );
   52811     }
   52812     sqlite3BtreeLeave(p);
   52813   }
   52814   return rc;
   52815 }
   52816 
   52817 /*
   52818 ** Create a new cursor for the BTree whose root is on the page
   52819 ** iTable. If a read-only cursor is requested, it is assumed that
   52820 ** the caller already has at least a read-only transaction open
   52821 ** on the database already. If a write-cursor is requested, then
   52822 ** the caller is assumed to have an open write transaction.
   52823 **
   52824 ** If wrFlag==0, then the cursor can only be used for reading.
   52825 ** If wrFlag==1, then the cursor can be used for reading or for
   52826 ** writing if other conditions for writing are also met.  These
   52827 ** are the conditions that must be met in order for writing to
   52828 ** be allowed:
   52829 **
   52830 ** 1:  The cursor must have been opened with wrFlag==1
   52831 **
   52832 ** 2:  Other database connections that share the same pager cache
   52833 **     but which are not in the READ_UNCOMMITTED state may not have
   52834 **     cursors open with wrFlag==0 on the same table.  Otherwise
   52835 **     the changes made by this write cursor would be visible to
   52836 **     the read cursors in the other database connection.
   52837 **
   52838 ** 3:  The database must be writable (not on read-only media)
   52839 **
   52840 ** 4:  There must be an active transaction.
   52841 **
   52842 ** No checking is done to make sure that page iTable really is the
   52843 ** root page of a b-tree.  If it is not, then the cursor acquired
   52844 ** will not work correctly.
   52845 **
   52846 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   52847 ** on pCur to initialize the memory space prior to invoking this routine.
   52848 */
   52849 static int btreeCursor(
   52850   Btree *p,                              /* The btree */
   52851   int iTable,                            /* Root page of table to open */
   52852   int wrFlag,                            /* 1 to write. 0 read-only */
   52853   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   52854   BtCursor *pCur                         /* Space for new cursor */
   52855 ){
   52856   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   52857 
   52858   assert( sqlite3BtreeHoldsMutex(p) );
   52859   assert( wrFlag==0 || wrFlag==1 );
   52860 
   52861   /* The following assert statements verify that if this is a sharable
   52862   ** b-tree database, the connection is holding the required table locks,
   52863   ** and that no other connection has any open cursor that conflicts with
   52864   ** this lock.  */
   52865   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   52866   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   52867 
   52868   /* Assert that the caller has opened the required transaction. */
   52869   assert( p->inTrans>TRANS_NONE );
   52870   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   52871   assert( pBt->pPage1 && pBt->pPage1->aData );
   52872 
   52873   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
   52874     return SQLITE_READONLY;
   52875   }
   52876   if( iTable==1 && btreePagecount(pBt)==0 ){
   52877     assert( wrFlag==0 );
   52878     iTable = 0;
   52879   }
   52880 
   52881   /* Now that no other errors can occur, finish filling in the BtCursor
   52882   ** variables and link the cursor into the BtShared list.  */
   52883   pCur->pgnoRoot = (Pgno)iTable;
   52884   pCur->iPage = -1;
   52885   pCur->pKeyInfo = pKeyInfo;
   52886   pCur->pBtree = p;
   52887   pCur->pBt = pBt;
   52888   pCur->wrFlag = (u8)wrFlag;
   52889   pCur->pNext = pBt->pCursor;
   52890   if( pCur->pNext ){
   52891     pCur->pNext->pPrev = pCur;
   52892   }
   52893   pBt->pCursor = pCur;
   52894   pCur->eState = CURSOR_INVALID;
   52895   pCur->cachedRowid = 0;
   52896   return SQLITE_OK;
   52897 }
   52898 SQLITE_PRIVATE int sqlite3BtreeCursor(
   52899   Btree *p,                                   /* The btree */
   52900   int iTable,                                 /* Root page of table to open */
   52901   int wrFlag,                                 /* 1 to write. 0 read-only */
   52902   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   52903   BtCursor *pCur                              /* Write new cursor here */
   52904 ){
   52905   int rc;
   52906   sqlite3BtreeEnter(p);
   52907   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   52908   sqlite3BtreeLeave(p);
   52909   return rc;
   52910 }
   52911 
   52912 /*
   52913 ** Return the size of a BtCursor object in bytes.
   52914 **
   52915 ** This interfaces is needed so that users of cursors can preallocate
   52916 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   52917 ** to users so they cannot do the sizeof() themselves - they must call
   52918 ** this routine.
   52919 */
   52920 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   52921   return ROUND8(sizeof(BtCursor));
   52922 }
   52923 
   52924 /*
   52925 ** Initialize memory that will be converted into a BtCursor object.
   52926 **
   52927 ** The simple approach here would be to memset() the entire object
   52928 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   52929 ** do not need to be zeroed and they are large, so we can save a lot
   52930 ** of run-time by skipping the initialization of those elements.
   52931 */
   52932 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   52933   memset(p, 0, offsetof(BtCursor, iPage));
   52934 }
   52935 
   52936 /*
   52937 ** Set the cached rowid value of every cursor in the same database file
   52938 ** as pCur and having the same root page number as pCur.  The value is
   52939 ** set to iRowid.
   52940 **
   52941 ** Only positive rowid values are considered valid for this cache.
   52942 ** The cache is initialized to zero, indicating an invalid cache.
   52943 ** A btree will work fine with zero or negative rowids.  We just cannot
   52944 ** cache zero or negative rowids, which means tables that use zero or
   52945 ** negative rowids might run a little slower.  But in practice, zero
   52946 ** or negative rowids are very uncommon so this should not be a problem.
   52947 */
   52948 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
   52949   BtCursor *p;
   52950   for(p=pCur->pBt->pCursor; p; p=p->pNext){
   52951     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
   52952   }
   52953   assert( pCur->cachedRowid==iRowid );
   52954 }
   52955 
   52956 /*
   52957 ** Return the cached rowid for the given cursor.  A negative or zero
   52958 ** return value indicates that the rowid cache is invalid and should be
   52959 ** ignored.  If the rowid cache has never before been set, then a
   52960 ** zero is returned.
   52961 */
   52962 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
   52963   return pCur->cachedRowid;
   52964 }
   52965 
   52966 /*
   52967 ** Close a cursor.  The read lock on the database file is released
   52968 ** when the last cursor is closed.
   52969 */
   52970 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   52971   Btree *pBtree = pCur->pBtree;
   52972   if( pBtree ){
   52973     int i;
   52974     BtShared *pBt = pCur->pBt;
   52975     sqlite3BtreeEnter(pBtree);
   52976     sqlite3BtreeClearCursor(pCur);
   52977     if( pCur->pPrev ){
   52978       pCur->pPrev->pNext = pCur->pNext;
   52979     }else{
   52980       pBt->pCursor = pCur->pNext;
   52981     }
   52982     if( pCur->pNext ){
   52983       pCur->pNext->pPrev = pCur->pPrev;
   52984     }
   52985     for(i=0; i<=pCur->iPage; i++){
   52986       releasePage(pCur->apPage[i]);
   52987     }
   52988     unlockBtreeIfUnused(pBt);
   52989     invalidateOverflowCache(pCur);
   52990     /* sqlite3_free(pCur); */
   52991     sqlite3BtreeLeave(pBtree);
   52992   }
   52993   return SQLITE_OK;
   52994 }
   52995 
   52996 /*
   52997 ** Make sure the BtCursor* given in the argument has a valid
   52998 ** BtCursor.info structure.  If it is not already valid, call
   52999 ** btreeParseCell() to fill it in.
   53000 **
   53001 ** BtCursor.info is a cache of the information in the current cell.
   53002 ** Using this cache reduces the number of calls to btreeParseCell().
   53003 **
   53004 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   53005 ** compiler to crash when getCellInfo() is implemented as a macro.
   53006 ** But there is a measureable speed advantage to using the macro on gcc
   53007 ** (when less compiler optimizations like -Os or -O0 are used and the
   53008 ** compiler is not doing agressive inlining.)  So we use a real function
   53009 ** for MSVC and a macro for everything else.  Ticket #2457.
   53010 */
   53011 #ifndef NDEBUG
   53012   static void assertCellInfo(BtCursor *pCur){
   53013     CellInfo info;
   53014     int iPage = pCur->iPage;
   53015     memset(&info, 0, sizeof(info));
   53016     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   53017     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
   53018   }
   53019 #else
   53020   #define assertCellInfo(x)
   53021 #endif
   53022 #ifdef _MSC_VER
   53023   /* Use a real function in MSVC to work around bugs in that compiler. */
   53024   static void getCellInfo(BtCursor *pCur){
   53025     if( pCur->info.nSize==0 ){
   53026       int iPage = pCur->iPage;
   53027       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   53028       pCur->validNKey = 1;
   53029     }else{
   53030       assertCellInfo(pCur);
   53031     }
   53032   }
   53033 #else /* if not _MSC_VER */
   53034   /* Use a macro in all other compilers so that the function is inlined */
   53035 #define getCellInfo(pCur)                                                      \
   53036   if( pCur->info.nSize==0 ){                                                   \
   53037     int iPage = pCur->iPage;                                                   \
   53038     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
   53039     pCur->validNKey = 1;                                                       \
   53040   }else{                                                                       \
   53041     assertCellInfo(pCur);                                                      \
   53042   }
   53043 #endif /* _MSC_VER */
   53044 
   53045 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   53046 /*
   53047 ** Return true if the given BtCursor is valid.  A valid cursor is one
   53048 ** that is currently pointing to a row in a (non-empty) table.
   53049 ** This is a verification routine is used only within assert() statements.
   53050 */
   53051 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   53052   return pCur && pCur->eState==CURSOR_VALID;
   53053 }
   53054 #endif /* NDEBUG */
   53055 
   53056 /*
   53057 ** Set *pSize to the size of the buffer needed to hold the value of
   53058 ** the key for the current entry.  If the cursor is not pointing
   53059 ** to a valid entry, *pSize is set to 0.
   53060 **
   53061 ** For a table with the INTKEY flag set, this routine returns the key
   53062 ** itself, not the number of bytes in the key.
   53063 **
   53064 ** The caller must position the cursor prior to invoking this routine.
   53065 **
   53066 ** This routine cannot fail.  It always returns SQLITE_OK.
   53067 */
   53068 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   53069   assert( cursorHoldsMutex(pCur) );
   53070   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   53071   if( pCur->eState!=CURSOR_VALID ){
   53072     *pSize = 0;
   53073   }else{
   53074     getCellInfo(pCur);
   53075     *pSize = pCur->info.nKey;
   53076   }
   53077   return SQLITE_OK;
   53078 }
   53079 
   53080 /*
   53081 ** Set *pSize to the number of bytes of data in the entry the
   53082 ** cursor currently points to.
   53083 **
   53084 ** The caller must guarantee that the cursor is pointing to a non-NULL
   53085 ** valid entry.  In other words, the calling procedure must guarantee
   53086 ** that the cursor has Cursor.eState==CURSOR_VALID.
   53087 **
   53088 ** Failure is not possible.  This function always returns SQLITE_OK.
   53089 ** It might just as well be a procedure (returning void) but we continue
   53090 ** to return an integer result code for historical reasons.
   53091 */
   53092 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   53093   assert( cursorHoldsMutex(pCur) );
   53094   assert( pCur->eState==CURSOR_VALID );
   53095   getCellInfo(pCur);
   53096   *pSize = pCur->info.nData;
   53097   return SQLITE_OK;
   53098 }
   53099 
   53100 /*
   53101 ** Given the page number of an overflow page in the database (parameter
   53102 ** ovfl), this function finds the page number of the next page in the
   53103 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   53104 ** pointer-map data instead of reading the content of page ovfl to do so.
   53105 **
   53106 ** If an error occurs an SQLite error code is returned. Otherwise:
   53107 **
   53108 ** The page number of the next overflow page in the linked list is
   53109 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   53110 ** list, *pPgnoNext is set to zero.
   53111 **
   53112 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   53113 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   53114 ** reference. It is the responsibility of the caller to call releasePage()
   53115 ** on *ppPage to free the reference. In no reference was obtained (because
   53116 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   53117 ** *ppPage is set to zero.
   53118 */
   53119 static int getOverflowPage(
   53120   BtShared *pBt,               /* The database file */
   53121   Pgno ovfl,                   /* Current overflow page number */
   53122   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   53123   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   53124 ){
   53125   Pgno next = 0;
   53126   MemPage *pPage = 0;
   53127   int rc = SQLITE_OK;
   53128 
   53129   assert( sqlite3_mutex_held(pBt->mutex) );
   53130   assert(pPgnoNext);
   53131 
   53132 #ifndef SQLITE_OMIT_AUTOVACUUM
   53133   /* Try to find the next page in the overflow list using the
   53134   ** autovacuum pointer-map pages. Guess that the next page in
   53135   ** the overflow list is page number (ovfl+1). If that guess turns
   53136   ** out to be wrong, fall back to loading the data of page
   53137   ** number ovfl to determine the next page number.
   53138   */
   53139   if( pBt->autoVacuum ){
   53140     Pgno pgno;
   53141     Pgno iGuess = ovfl+1;
   53142     u8 eType;
   53143 
   53144     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   53145       iGuess++;
   53146     }
   53147 
   53148     if( iGuess<=btreePagecount(pBt) ){
   53149       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   53150       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   53151         next = iGuess;
   53152         rc = SQLITE_DONE;
   53153       }
   53154     }
   53155   }
   53156 #endif
   53157 
   53158   assert( next==0 || rc==SQLITE_DONE );
   53159   if( rc==SQLITE_OK ){
   53160     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
   53161     assert( rc==SQLITE_OK || pPage==0 );
   53162     if( rc==SQLITE_OK ){
   53163       next = get4byte(pPage->aData);
   53164     }
   53165   }
   53166 
   53167   *pPgnoNext = next;
   53168   if( ppPage ){
   53169     *ppPage = pPage;
   53170   }else{
   53171     releasePage(pPage);
   53172   }
   53173   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   53174 }
   53175 
   53176 /*
   53177 ** Copy data from a buffer to a page, or from a page to a buffer.
   53178 **
   53179 ** pPayload is a pointer to data stored on database page pDbPage.
   53180 ** If argument eOp is false, then nByte bytes of data are copied
   53181 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   53182 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   53183 ** of data are copied from the buffer pBuf to pPayload.
   53184 **
   53185 ** SQLITE_OK is returned on success, otherwise an error code.
   53186 */
   53187 static int copyPayload(
   53188   void *pPayload,           /* Pointer to page data */
   53189   void *pBuf,               /* Pointer to buffer */
   53190   int nByte,                /* Number of bytes to copy */
   53191   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   53192   DbPage *pDbPage           /* Page containing pPayload */
   53193 ){
   53194   if( eOp ){
   53195     /* Copy data from buffer to page (a write operation) */
   53196     int rc = sqlite3PagerWrite(pDbPage);
   53197     if( rc!=SQLITE_OK ){
   53198       return rc;
   53199     }
   53200     memcpy(pPayload, pBuf, nByte);
   53201   }else{
   53202     /* Copy data from page to buffer (a read operation) */
   53203     memcpy(pBuf, pPayload, nByte);
   53204   }
   53205   return SQLITE_OK;
   53206 }
   53207 
   53208 /*
   53209 ** This function is used to read or overwrite payload information
   53210 ** for the entry that the pCur cursor is pointing to. If the eOp
   53211 ** parameter is 0, this is a read operation (data copied into
   53212 ** buffer pBuf). If it is non-zero, a write (data copied from
   53213 ** buffer pBuf).
   53214 **
   53215 ** A total of "amt" bytes are read or written beginning at "offset".
   53216 ** Data is read to or from the buffer pBuf.
   53217 **
   53218 ** The content being read or written might appear on the main page
   53219 ** or be scattered out on multiple overflow pages.
   53220 **
   53221 ** If the BtCursor.isIncrblobHandle flag is set, and the current
   53222 ** cursor entry uses one or more overflow pages, this function
   53223 ** allocates space for and lazily popluates the overflow page-list
   53224 ** cache array (BtCursor.aOverflow). Subsequent calls use this
   53225 ** cache to make seeking to the supplied offset more efficient.
   53226 **
   53227 ** Once an overflow page-list cache has been allocated, it may be
   53228 ** invalidated if some other cursor writes to the same table, or if
   53229 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   53230 ** mode, the following events may invalidate an overflow page-list cache.
   53231 **
   53232 **   * An incremental vacuum,
   53233 **   * A commit in auto_vacuum="full" mode,
   53234 **   * Creating a table (may require moving an overflow page).
   53235 */
   53236 static int accessPayload(
   53237   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   53238   u32 offset,          /* Begin reading this far into payload */
   53239   u32 amt,             /* Read this many bytes */
   53240   unsigned char *pBuf, /* Write the bytes into this buffer */
   53241   int eOp              /* zero to read. non-zero to write. */
   53242 ){
   53243   unsigned char *aPayload;
   53244   int rc = SQLITE_OK;
   53245   u32 nKey;
   53246   int iIdx = 0;
   53247   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   53248   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   53249 
   53250   assert( pPage );
   53251   assert( pCur->eState==CURSOR_VALID );
   53252   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53253   assert( cursorHoldsMutex(pCur) );
   53254 
   53255   getCellInfo(pCur);
   53256   aPayload = pCur->info.pCell + pCur->info.nHeader;
   53257   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   53258 
   53259   if( NEVER(offset+amt > nKey+pCur->info.nData)
   53260    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   53261   ){
   53262     /* Trying to read or write past the end of the data is an error */
   53263     return SQLITE_CORRUPT_BKPT;
   53264   }
   53265 
   53266   /* Check if data must be read/written to/from the btree page itself. */
   53267   if( offset<pCur->info.nLocal ){
   53268     int a = amt;
   53269     if( a+offset>pCur->info.nLocal ){
   53270       a = pCur->info.nLocal - offset;
   53271     }
   53272     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
   53273     offset = 0;
   53274     pBuf += a;
   53275     amt -= a;
   53276   }else{
   53277     offset -= pCur->info.nLocal;
   53278   }
   53279 
   53280   if( rc==SQLITE_OK && amt>0 ){
   53281     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   53282     Pgno nextPage;
   53283 
   53284     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   53285 
   53286 #ifndef SQLITE_OMIT_INCRBLOB
   53287     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
   53288     ** has not been allocated, allocate it now. The array is sized at
   53289     ** one entry for each overflow page in the overflow chain. The
   53290     ** page number of the first overflow page is stored in aOverflow[0],
   53291     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
   53292     ** (the cache is lazily populated).
   53293     */
   53294     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
   53295       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   53296       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
   53297       /* nOvfl is always positive.  If it were zero, fetchPayload would have
   53298       ** been used instead of this routine. */
   53299       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
   53300         rc = SQLITE_NOMEM;
   53301       }
   53302     }
   53303 
   53304     /* If the overflow page-list cache has been allocated and the
   53305     ** entry for the first required overflow page is valid, skip
   53306     ** directly to it.
   53307     */
   53308     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
   53309       iIdx = (offset/ovflSize);
   53310       nextPage = pCur->aOverflow[iIdx];
   53311       offset = (offset%ovflSize);
   53312     }
   53313 #endif
   53314 
   53315     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   53316 
   53317 #ifndef SQLITE_OMIT_INCRBLOB
   53318       /* If required, populate the overflow page-list cache. */
   53319       if( pCur->aOverflow ){
   53320         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   53321         pCur->aOverflow[iIdx] = nextPage;
   53322       }
   53323 #endif
   53324 
   53325       if( offset>=ovflSize ){
   53326         /* The only reason to read this page is to obtain the page
   53327         ** number for the next page in the overflow chain. The page
   53328         ** data is not required. So first try to lookup the overflow
   53329         ** page-list cache, if any, then fall back to the getOverflowPage()
   53330         ** function.
   53331         */
   53332 #ifndef SQLITE_OMIT_INCRBLOB
   53333         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
   53334           nextPage = pCur->aOverflow[iIdx+1];
   53335         } else
   53336 #endif
   53337           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   53338         offset -= ovflSize;
   53339       }else{
   53340         /* Need to read this page properly. It contains some of the
   53341         ** range of data that is being read (eOp==0) or written (eOp!=0).
   53342         */
   53343 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   53344         sqlite3_file *fd;
   53345 #endif
   53346         int a = amt;
   53347         if( a + offset > ovflSize ){
   53348           a = ovflSize - offset;
   53349         }
   53350 
   53351 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   53352         /* If all the following are true:
   53353         **
   53354         **   1) this is a read operation, and
   53355         **   2) data is required from the start of this overflow page, and
   53356         **   3) the database is file-backed, and
   53357         **   4) there is no open write-transaction, and
   53358         **   5) the database is not a WAL database,
   53359         **
   53360         ** then data can be read directly from the database file into the
   53361         ** output buffer, bypassing the page-cache altogether. This speeds
   53362         ** up loading large records that span many overflow pages.
   53363         */
   53364         if( eOp==0                                             /* (1) */
   53365          && offset==0                                          /* (2) */
   53366          && pBt->inTransaction==TRANS_READ                     /* (4) */
   53367          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
   53368          && pBt->pPage1->aData[19]==0x01                       /* (5) */
   53369         ){
   53370           u8 aSave[4];
   53371           u8 *aWrite = &pBuf[-4];
   53372           memcpy(aSave, aWrite, 4);
   53373           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
   53374           nextPage = get4byte(aWrite);
   53375           memcpy(aWrite, aSave, 4);
   53376         }else
   53377 #endif
   53378 
   53379         {
   53380           DbPage *pDbPage;
   53381           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
   53382           if( rc==SQLITE_OK ){
   53383             aPayload = sqlite3PagerGetData(pDbPage);
   53384             nextPage = get4byte(aPayload);
   53385             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
   53386             sqlite3PagerUnref(pDbPage);
   53387             offset = 0;
   53388           }
   53389         }
   53390         amt -= a;
   53391         pBuf += a;
   53392       }
   53393     }
   53394   }
   53395 
   53396   if( rc==SQLITE_OK && amt>0 ){
   53397     return SQLITE_CORRUPT_BKPT;
   53398   }
   53399   return rc;
   53400 }
   53401 
   53402 /*
   53403 ** Read part of the key associated with cursor pCur.  Exactly
   53404 ** "amt" bytes will be transfered into pBuf[].  The transfer
   53405 ** begins at "offset".
   53406 **
   53407 ** The caller must ensure that pCur is pointing to a valid row
   53408 ** in the table.
   53409 **
   53410 ** Return SQLITE_OK on success or an error code if anything goes
   53411 ** wrong.  An error is returned if "offset+amt" is larger than
   53412 ** the available payload.
   53413 */
   53414 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   53415   assert( cursorHoldsMutex(pCur) );
   53416   assert( pCur->eState==CURSOR_VALID );
   53417   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   53418   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   53419   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   53420 }
   53421 
   53422 /*
   53423 ** Read part of the data associated with cursor pCur.  Exactly
   53424 ** "amt" bytes will be transfered into pBuf[].  The transfer
   53425 ** begins at "offset".
   53426 **
   53427 ** Return SQLITE_OK on success or an error code if anything goes
   53428 ** wrong.  An error is returned if "offset+amt" is larger than
   53429 ** the available payload.
   53430 */
   53431 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   53432   int rc;
   53433 
   53434 #ifndef SQLITE_OMIT_INCRBLOB
   53435   if ( pCur->eState==CURSOR_INVALID ){
   53436     return SQLITE_ABORT;
   53437   }
   53438 #endif
   53439 
   53440   assert( cursorHoldsMutex(pCur) );
   53441   rc = restoreCursorPosition(pCur);
   53442   if( rc==SQLITE_OK ){
   53443     assert( pCur->eState==CURSOR_VALID );
   53444     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   53445     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   53446     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   53447   }
   53448   return rc;
   53449 }
   53450 
   53451 /*
   53452 ** Return a pointer to payload information from the entry that the
   53453 ** pCur cursor is pointing to.  The pointer is to the beginning of
   53454 ** the key if skipKey==0 and it points to the beginning of data if
   53455 ** skipKey==1.  The number of bytes of available key/data is written
   53456 ** into *pAmt.  If *pAmt==0, then the value returned will not be
   53457 ** a valid pointer.
   53458 **
   53459 ** This routine is an optimization.  It is common for the entire key
   53460 ** and data to fit on the local page and for there to be no overflow
   53461 ** pages.  When that is so, this routine can be used to access the
   53462 ** key and data without making a copy.  If the key and/or data spills
   53463 ** onto overflow pages, then accessPayload() must be used to reassemble
   53464 ** the key/data and copy it into a preallocated buffer.
   53465 **
   53466 ** The pointer returned by this routine looks directly into the cached
   53467 ** page of the database.  The data might change or move the next time
   53468 ** any btree routine is called.
   53469 */
   53470 static const unsigned char *fetchPayload(
   53471   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   53472   int *pAmt,           /* Write the number of available bytes here */
   53473   int skipKey          /* read beginning at data if this is true */
   53474 ){
   53475   unsigned char *aPayload;
   53476   MemPage *pPage;
   53477   u32 nKey;
   53478   u32 nLocal;
   53479 
   53480   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   53481   assert( pCur->eState==CURSOR_VALID );
   53482   assert( cursorHoldsMutex(pCur) );
   53483   pPage = pCur->apPage[pCur->iPage];
   53484   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53485   if( NEVER(pCur->info.nSize==0) ){
   53486     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
   53487                    &pCur->info);
   53488   }
   53489   aPayload = pCur->info.pCell;
   53490   aPayload += pCur->info.nHeader;
   53491   if( pPage->intKey ){
   53492     nKey = 0;
   53493   }else{
   53494     nKey = (int)pCur->info.nKey;
   53495   }
   53496   if( skipKey ){
   53497     aPayload += nKey;
   53498     nLocal = pCur->info.nLocal - nKey;
   53499   }else{
   53500     nLocal = pCur->info.nLocal;
   53501     assert( nLocal<=nKey );
   53502   }
   53503   *pAmt = nLocal;
   53504   return aPayload;
   53505 }
   53506 
   53507 
   53508 /*
   53509 ** For the entry that cursor pCur is point to, return as
   53510 ** many bytes of the key or data as are available on the local
   53511 ** b-tree page.  Write the number of available bytes into *pAmt.
   53512 **
   53513 ** The pointer returned is ephemeral.  The key/data may move
   53514 ** or be destroyed on the next call to any Btree routine,
   53515 ** including calls from other threads against the same cache.
   53516 ** Hence, a mutex on the BtShared should be held prior to calling
   53517 ** this routine.
   53518 **
   53519 ** These routines is used to get quick access to key and data
   53520 ** in the common case where no overflow pages are used.
   53521 */
   53522 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
   53523   const void *p = 0;
   53524   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53525   assert( cursorHoldsMutex(pCur) );
   53526   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   53527     p = (const void*)fetchPayload(pCur, pAmt, 0);
   53528   }
   53529   return p;
   53530 }
   53531 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
   53532   const void *p = 0;
   53533   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53534   assert( cursorHoldsMutex(pCur) );
   53535   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   53536     p = (const void*)fetchPayload(pCur, pAmt, 1);
   53537   }
   53538   return p;
   53539 }
   53540 
   53541 
   53542 /*
   53543 ** Move the cursor down to a new child page.  The newPgno argument is the
   53544 ** page number of the child page to move to.
   53545 **
   53546 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   53547 ** the new child page does not match the flags field of the parent (i.e.
   53548 ** if an intkey page appears to be the parent of a non-intkey page, or
   53549 ** vice-versa).
   53550 */
   53551 static int moveToChild(BtCursor *pCur, u32 newPgno){
   53552   int rc;
   53553   int i = pCur->iPage;
   53554   MemPage *pNewPage;
   53555   BtShared *pBt = pCur->pBt;
   53556 
   53557   assert( cursorHoldsMutex(pCur) );
   53558   assert( pCur->eState==CURSOR_VALID );
   53559   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   53560   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   53561     return SQLITE_CORRUPT_BKPT;
   53562   }
   53563   rc = getAndInitPage(pBt, newPgno, &pNewPage);
   53564   if( rc ) return rc;
   53565   pCur->apPage[i+1] = pNewPage;
   53566   pCur->aiIdx[i+1] = 0;
   53567   pCur->iPage++;
   53568 
   53569   pCur->info.nSize = 0;
   53570   pCur->validNKey = 0;
   53571   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   53572     return SQLITE_CORRUPT_BKPT;
   53573   }
   53574   return SQLITE_OK;
   53575 }
   53576 
   53577 #if 0
   53578 /*
   53579 ** Page pParent is an internal (non-leaf) tree page. This function
   53580 ** asserts that page number iChild is the left-child if the iIdx'th
   53581 ** cell in page pParent. Or, if iIdx is equal to the total number of
   53582 ** cells in pParent, that page number iChild is the right-child of
   53583 ** the page.
   53584 */
   53585 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   53586   assert( iIdx<=pParent->nCell );
   53587   if( iIdx==pParent->nCell ){
   53588     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   53589   }else{
   53590     assert( get4byte(findCell(pParent, iIdx))==iChild );
   53591   }
   53592 }
   53593 #else
   53594 #  define assertParentIndex(x,y,z)
   53595 #endif
   53596 
   53597 /*
   53598 ** Move the cursor up to the parent page.
   53599 **
   53600 ** pCur->idx is set to the cell index that contains the pointer
   53601 ** to the page we are coming from.  If we are coming from the
   53602 ** right-most child page then pCur->idx is set to one more than
   53603 ** the largest cell index.
   53604 */
   53605 static void moveToParent(BtCursor *pCur){
   53606   assert( cursorHoldsMutex(pCur) );
   53607   assert( pCur->eState==CURSOR_VALID );
   53608   assert( pCur->iPage>0 );
   53609   assert( pCur->apPage[pCur->iPage] );
   53610 
   53611   /* UPDATE: It is actually possible for the condition tested by the assert
   53612   ** below to be untrue if the database file is corrupt. This can occur if
   53613   ** one cursor has modified page pParent while a reference to it is held
   53614   ** by a second cursor. Which can only happen if a single page is linked
   53615   ** into more than one b-tree structure in a corrupt database.  */
   53616 #if 0
   53617   assertParentIndex(
   53618     pCur->apPage[pCur->iPage-1],
   53619     pCur->aiIdx[pCur->iPage-1],
   53620     pCur->apPage[pCur->iPage]->pgno
   53621   );
   53622 #endif
   53623   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
   53624 
   53625   releasePage(pCur->apPage[pCur->iPage]);
   53626   pCur->iPage--;
   53627   pCur->info.nSize = 0;
   53628   pCur->validNKey = 0;
   53629 }
   53630 
   53631 /*
   53632 ** Move the cursor to point to the root page of its b-tree structure.
   53633 **
   53634 ** If the table has a virtual root page, then the cursor is moved to point
   53635 ** to the virtual root page instead of the actual root page. A table has a
   53636 ** virtual root page when the actual root page contains no cells and a
   53637 ** single child page. This can only happen with the table rooted at page 1.
   53638 **
   53639 ** If the b-tree structure is empty, the cursor state is set to
   53640 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   53641 ** cell located on the root (or virtual root) page and the cursor state
   53642 ** is set to CURSOR_VALID.
   53643 **
   53644 ** If this function returns successfully, it may be assumed that the
   53645 ** page-header flags indicate that the [virtual] root-page is the expected
   53646 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   53647 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   53648 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   53649 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   53650 ** b-tree).
   53651 */
   53652 static int moveToRoot(BtCursor *pCur){
   53653   MemPage *pRoot;
   53654   int rc = SQLITE_OK;
   53655   Btree *p = pCur->pBtree;
   53656   BtShared *pBt = p->pBt;
   53657 
   53658   assert( cursorHoldsMutex(pCur) );
   53659   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   53660   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   53661   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   53662   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   53663     if( pCur->eState==CURSOR_FAULT ){
   53664       assert( pCur->skipNext!=SQLITE_OK );
   53665       return pCur->skipNext;
   53666     }
   53667     sqlite3BtreeClearCursor(pCur);
   53668   }
   53669 
   53670   if( pCur->iPage>=0 ){
   53671     int i;
   53672     for(i=1; i<=pCur->iPage; i++){
   53673       releasePage(pCur->apPage[i]);
   53674     }
   53675     pCur->iPage = 0;
   53676   }else if( pCur->pgnoRoot==0 ){
   53677     pCur->eState = CURSOR_INVALID;
   53678     return SQLITE_OK;
   53679   }else{
   53680     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
   53681     if( rc!=SQLITE_OK ){
   53682       pCur->eState = CURSOR_INVALID;
   53683       return rc;
   53684     }
   53685     pCur->iPage = 0;
   53686 
   53687     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   53688     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   53689     ** NULL, the caller expects a table b-tree. If this is not the case,
   53690     ** return an SQLITE_CORRUPT error.  */
   53691     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
   53692     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
   53693       return SQLITE_CORRUPT_BKPT;
   53694     }
   53695   }
   53696 
   53697   /* Assert that the root page is of the correct type. This must be the
   53698   ** case as the call to this function that loaded the root-page (either
   53699   ** this call or a previous invocation) would have detected corruption
   53700   ** if the assumption were not true, and it is not possible for the flags
   53701   ** byte to have been modified while this cursor is holding a reference
   53702   ** to the page.  */
   53703   pRoot = pCur->apPage[0];
   53704   assert( pRoot->pgno==pCur->pgnoRoot );
   53705   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
   53706 
   53707   pCur->aiIdx[0] = 0;
   53708   pCur->info.nSize = 0;
   53709   pCur->atLast = 0;
   53710   pCur->validNKey = 0;
   53711 
   53712   if( pRoot->nCell==0 && !pRoot->leaf ){
   53713     Pgno subpage;
   53714     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   53715     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   53716     pCur->eState = CURSOR_VALID;
   53717     rc = moveToChild(pCur, subpage);
   53718   }else{
   53719     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
   53720   }
   53721   return rc;
   53722 }
   53723 
   53724 /*
   53725 ** Move the cursor down to the left-most leaf entry beneath the
   53726 ** entry to which it is currently pointing.
   53727 **
   53728 ** The left-most leaf is the one with the smallest key - the first
   53729 ** in ascending order.
   53730 */
   53731 static int moveToLeftmost(BtCursor *pCur){
   53732   Pgno pgno;
   53733   int rc = SQLITE_OK;
   53734   MemPage *pPage;
   53735 
   53736   assert( cursorHoldsMutex(pCur) );
   53737   assert( pCur->eState==CURSOR_VALID );
   53738   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   53739     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53740     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   53741     rc = moveToChild(pCur, pgno);
   53742   }
   53743   return rc;
   53744 }
   53745 
   53746 /*
   53747 ** Move the cursor down to the right-most leaf entry beneath the
   53748 ** page to which it is currently pointing.  Notice the difference
   53749 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   53750 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   53751 ** finds the right-most entry beneath the *page*.
   53752 **
   53753 ** The right-most entry is the one with the largest key - the last
   53754 ** key in ascending order.
   53755 */
   53756 static int moveToRightmost(BtCursor *pCur){
   53757   Pgno pgno;
   53758   int rc = SQLITE_OK;
   53759   MemPage *pPage = 0;
   53760 
   53761   assert( cursorHoldsMutex(pCur) );
   53762   assert( pCur->eState==CURSOR_VALID );
   53763   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   53764     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   53765     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   53766     rc = moveToChild(pCur, pgno);
   53767   }
   53768   if( rc==SQLITE_OK ){
   53769     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   53770     pCur->info.nSize = 0;
   53771     pCur->validNKey = 0;
   53772   }
   53773   return rc;
   53774 }
   53775 
   53776 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   53777 ** on success.  Set *pRes to 0 if the cursor actually points to something
   53778 ** or set *pRes to 1 if the table is empty.
   53779 */
   53780 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   53781   int rc;
   53782 
   53783   assert( cursorHoldsMutex(pCur) );
   53784   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53785   rc = moveToRoot(pCur);
   53786   if( rc==SQLITE_OK ){
   53787     if( pCur->eState==CURSOR_INVALID ){
   53788       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53789       *pRes = 1;
   53790     }else{
   53791       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   53792       *pRes = 0;
   53793       rc = moveToLeftmost(pCur);
   53794     }
   53795   }
   53796   return rc;
   53797 }
   53798 
   53799 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   53800 ** on success.  Set *pRes to 0 if the cursor actually points to something
   53801 ** or set *pRes to 1 if the table is empty.
   53802 */
   53803 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   53804   int rc;
   53805 
   53806   assert( cursorHoldsMutex(pCur) );
   53807   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53808 
   53809   /* If the cursor already points to the last entry, this is a no-op. */
   53810   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
   53811 #ifdef SQLITE_DEBUG
   53812     /* This block serves to assert() that the cursor really does point
   53813     ** to the last entry in the b-tree. */
   53814     int ii;
   53815     for(ii=0; ii<pCur->iPage; ii++){
   53816       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   53817     }
   53818     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   53819     assert( pCur->apPage[pCur->iPage]->leaf );
   53820 #endif
   53821     return SQLITE_OK;
   53822   }
   53823 
   53824   rc = moveToRoot(pCur);
   53825   if( rc==SQLITE_OK ){
   53826     if( CURSOR_INVALID==pCur->eState ){
   53827       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53828       *pRes = 1;
   53829     }else{
   53830       assert( pCur->eState==CURSOR_VALID );
   53831       *pRes = 0;
   53832       rc = moveToRightmost(pCur);
   53833       pCur->atLast = rc==SQLITE_OK ?1:0;
   53834     }
   53835   }
   53836   return rc;
   53837 }
   53838 
   53839 /* Move the cursor so that it points to an entry near the key
   53840 ** specified by pIdxKey or intKey.   Return a success code.
   53841 **
   53842 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   53843 ** must be NULL.  For index tables, pIdxKey is used and intKey
   53844 ** is ignored.
   53845 **
   53846 ** If an exact match is not found, then the cursor is always
   53847 ** left pointing at a leaf page which would hold the entry if it
   53848 ** were present.  The cursor might point to an entry that comes
   53849 ** before or after the key.
   53850 **
   53851 ** An integer is written into *pRes which is the result of
   53852 ** comparing the key with the entry to which the cursor is
   53853 ** pointing.  The meaning of the integer written into
   53854 ** *pRes is as follows:
   53855 **
   53856 **     *pRes<0      The cursor is left pointing at an entry that
   53857 **                  is smaller than intKey/pIdxKey or if the table is empty
   53858 **                  and the cursor is therefore left point to nothing.
   53859 **
   53860 **     *pRes==0     The cursor is left pointing at an entry that
   53861 **                  exactly matches intKey/pIdxKey.
   53862 **
   53863 **     *pRes>0      The cursor is left pointing at an entry that
   53864 **                  is larger than intKey/pIdxKey.
   53865 **
   53866 */
   53867 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   53868   BtCursor *pCur,          /* The cursor to be moved */
   53869   UnpackedRecord *pIdxKey, /* Unpacked index key */
   53870   i64 intKey,              /* The table key */
   53871   int biasRight,           /* If true, bias the search to the high end */
   53872   int *pRes                /* Write search results here */
   53873 ){
   53874   int rc;
   53875 
   53876   assert( cursorHoldsMutex(pCur) );
   53877   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53878   assert( pRes );
   53879   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   53880 
   53881   /* If the cursor is already positioned at the point we are trying
   53882   ** to move to, then just return without doing any work */
   53883   if( pCur->eState==CURSOR_VALID && pCur->validNKey
   53884    && pCur->apPage[0]->intKey
   53885   ){
   53886     if( pCur->info.nKey==intKey ){
   53887       *pRes = 0;
   53888       return SQLITE_OK;
   53889     }
   53890     if( pCur->atLast && pCur->info.nKey<intKey ){
   53891       *pRes = -1;
   53892       return SQLITE_OK;
   53893     }
   53894   }
   53895 
   53896   rc = moveToRoot(pCur);
   53897   if( rc ){
   53898     return rc;
   53899   }
   53900   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
   53901   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
   53902   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
   53903   if( pCur->eState==CURSOR_INVALID ){
   53904     *pRes = -1;
   53905     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53906     return SQLITE_OK;
   53907   }
   53908   assert( pCur->apPage[0]->intKey || pIdxKey );
   53909   for(;;){
   53910     int lwr, upr, idx;
   53911     Pgno chldPg;
   53912     MemPage *pPage = pCur->apPage[pCur->iPage];
   53913     int c;
   53914 
   53915     /* pPage->nCell must be greater than zero. If this is the root-page
   53916     ** the cursor would have been INVALID above and this for(;;) loop
   53917     ** not run. If this is not the root-page, then the moveToChild() routine
   53918     ** would have already detected db corruption. Similarly, pPage must
   53919     ** be the right kind (index or table) of b-tree page. Otherwise
   53920     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   53921     assert( pPage->nCell>0 );
   53922     assert( pPage->intKey==(pIdxKey==0) );
   53923     lwr = 0;
   53924     upr = pPage->nCell-1;
   53925     if( biasRight ){
   53926       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
   53927     }else{
   53928       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
   53929     }
   53930     for(;;){
   53931       u8 *pCell;                          /* Pointer to current cell in pPage */
   53932 
   53933       assert( idx==pCur->aiIdx[pCur->iPage] );
   53934       pCur->info.nSize = 0;
   53935       pCell = findCell(pPage, idx) + pPage->childPtrSize;
   53936       if( pPage->intKey ){
   53937         i64 nCellKey;
   53938         if( pPage->hasData ){
   53939           u32 dummy;
   53940           pCell += getVarint32(pCell, dummy);
   53941         }
   53942         getVarint(pCell, (u64*)&nCellKey);
   53943         if( nCellKey==intKey ){
   53944           c = 0;
   53945         }else if( nCellKey<intKey ){
   53946           c = -1;
   53947         }else{
   53948           assert( nCellKey>intKey );
   53949           c = +1;
   53950         }
   53951         pCur->validNKey = 1;
   53952         pCur->info.nKey = nCellKey;
   53953       }else{
   53954         /* The maximum supported page-size is 65536 bytes. This means that
   53955         ** the maximum number of record bytes stored on an index B-Tree
   53956         ** page is less than 16384 bytes and may be stored as a 2-byte
   53957         ** varint. This information is used to attempt to avoid parsing
   53958         ** the entire cell by checking for the cases where the record is
   53959         ** stored entirely within the b-tree page by inspecting the first
   53960         ** 2 bytes of the cell.
   53961         */
   53962         int nCell = pCell[0];
   53963         if( nCell<=pPage->max1bytePayload
   53964          /* && (pCell+nCell)<pPage->aDataEnd */
   53965         ){
   53966           /* This branch runs if the record-size field of the cell is a
   53967           ** single byte varint and the record fits entirely on the main
   53968           ** b-tree page.  */
   53969           testcase( pCell+nCell+1==pPage->aDataEnd );
   53970           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
   53971         }else if( !(pCell[1] & 0x80)
   53972           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   53973           /* && (pCell+nCell+2)<=pPage->aDataEnd */
   53974         ){
   53975           /* The record-size field is a 2 byte varint and the record
   53976           ** fits entirely on the main b-tree page.  */
   53977           testcase( pCell+nCell+2==pPage->aDataEnd );
   53978           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
   53979         }else{
   53980           /* The record flows over onto one or more overflow pages. In
   53981           ** this case the whole cell needs to be parsed, a buffer allocated
   53982           ** and accessPayload() used to retrieve the record into the
   53983           ** buffer before VdbeRecordCompare() can be called. */
   53984           void *pCellKey;
   53985           u8 * const pCellBody = pCell - pPage->childPtrSize;
   53986           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   53987           nCell = (int)pCur->info.nKey;
   53988           pCellKey = sqlite3Malloc( nCell );
   53989           if( pCellKey==0 ){
   53990             rc = SQLITE_NOMEM;
   53991             goto moveto_finish;
   53992           }
   53993           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
   53994           if( rc ){
   53995             sqlite3_free(pCellKey);
   53996             goto moveto_finish;
   53997           }
   53998           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
   53999           sqlite3_free(pCellKey);
   54000         }
   54001       }
   54002       if( c==0 ){
   54003         if( pPage->intKey && !pPage->leaf ){
   54004           lwr = idx;
   54005           break;
   54006         }else{
   54007           *pRes = 0;
   54008           rc = SQLITE_OK;
   54009           goto moveto_finish;
   54010         }
   54011       }
   54012       if( c<0 ){
   54013         lwr = idx+1;
   54014       }else{
   54015         upr = idx-1;
   54016       }
   54017       if( lwr>upr ){
   54018         break;
   54019       }
   54020       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
   54021     }
   54022     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
   54023     assert( pPage->isInit );
   54024     if( pPage->leaf ){
   54025       chldPg = 0;
   54026     }else if( lwr>=pPage->nCell ){
   54027       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   54028     }else{
   54029       chldPg = get4byte(findCell(pPage, lwr));
   54030     }
   54031     if( chldPg==0 ){
   54032       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   54033       *pRes = c;
   54034       rc = SQLITE_OK;
   54035       goto moveto_finish;
   54036     }
   54037     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   54038     pCur->info.nSize = 0;
   54039     pCur->validNKey = 0;
   54040     rc = moveToChild(pCur, chldPg);
   54041     if( rc ) goto moveto_finish;
   54042   }
   54043 moveto_finish:
   54044   return rc;
   54045 }
   54046 
   54047 
   54048 /*
   54049 ** Return TRUE if the cursor is not pointing at an entry of the table.
   54050 **
   54051 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   54052 ** past the last entry in the table or sqlite3BtreePrev() moves past
   54053 ** the first entry.  TRUE is also returned if the table is empty.
   54054 */
   54055 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   54056   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   54057   ** have been deleted? This API will need to change to return an error code
   54058   ** as well as the boolean result value.
   54059   */
   54060   return (CURSOR_VALID!=pCur->eState);
   54061 }
   54062 
   54063 /*
   54064 ** Advance the cursor to the next entry in the database.  If
   54065 ** successful then set *pRes=0.  If the cursor
   54066 ** was already pointing to the last entry in the database before
   54067 ** this routine was called, then set *pRes=1.
   54068 */
   54069 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   54070   int rc;
   54071   int idx;
   54072   MemPage *pPage;
   54073 
   54074   assert( cursorHoldsMutex(pCur) );
   54075   rc = restoreCursorPosition(pCur);
   54076   if( rc!=SQLITE_OK ){
   54077     return rc;
   54078   }
   54079   assert( pRes!=0 );
   54080   if( CURSOR_INVALID==pCur->eState ){
   54081     *pRes = 1;
   54082     return SQLITE_OK;
   54083   }
   54084   if( pCur->skipNext>0 ){
   54085     pCur->skipNext = 0;
   54086     *pRes = 0;
   54087     return SQLITE_OK;
   54088   }
   54089   pCur->skipNext = 0;
   54090 
   54091   pPage = pCur->apPage[pCur->iPage];
   54092   idx = ++pCur->aiIdx[pCur->iPage];
   54093   assert( pPage->isInit );
   54094 
   54095   /* If the database file is corrupt, it is possible for the value of idx
   54096   ** to be invalid here. This can only occur if a second cursor modifies
   54097   ** the page while cursor pCur is holding a reference to it. Which can
   54098   ** only happen if the database is corrupt in such a way as to link the
   54099   ** page into more than one b-tree structure. */
   54100   testcase( idx>pPage->nCell );
   54101 
   54102   pCur->info.nSize = 0;
   54103   pCur->validNKey = 0;
   54104   if( idx>=pPage->nCell ){
   54105     if( !pPage->leaf ){
   54106       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   54107       if( rc ) return rc;
   54108       rc = moveToLeftmost(pCur);
   54109       *pRes = 0;
   54110       return rc;
   54111     }
   54112     do{
   54113       if( pCur->iPage==0 ){
   54114         *pRes = 1;
   54115         pCur->eState = CURSOR_INVALID;
   54116         return SQLITE_OK;
   54117       }
   54118       moveToParent(pCur);
   54119       pPage = pCur->apPage[pCur->iPage];
   54120     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   54121     *pRes = 0;
   54122     if( pPage->intKey ){
   54123       rc = sqlite3BtreeNext(pCur, pRes);
   54124     }else{
   54125       rc = SQLITE_OK;
   54126     }
   54127     return rc;
   54128   }
   54129   *pRes = 0;
   54130   if( pPage->leaf ){
   54131     return SQLITE_OK;
   54132   }
   54133   rc = moveToLeftmost(pCur);
   54134   return rc;
   54135 }
   54136 
   54137 
   54138 /*
   54139 ** Step the cursor to the back to the previous entry in the database.  If
   54140 ** successful then set *pRes=0.  If the cursor
   54141 ** was already pointing to the first entry in the database before
   54142 ** this routine was called, then set *pRes=1.
   54143 */
   54144 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   54145   int rc;
   54146   MemPage *pPage;
   54147 
   54148   assert( cursorHoldsMutex(pCur) );
   54149   rc = restoreCursorPosition(pCur);
   54150   if( rc!=SQLITE_OK ){
   54151     return rc;
   54152   }
   54153   pCur->atLast = 0;
   54154   if( CURSOR_INVALID==pCur->eState ){
   54155     *pRes = 1;
   54156     return SQLITE_OK;
   54157   }
   54158   if( pCur->skipNext<0 ){
   54159     pCur->skipNext = 0;
   54160     *pRes = 0;
   54161     return SQLITE_OK;
   54162   }
   54163   pCur->skipNext = 0;
   54164 
   54165   pPage = pCur->apPage[pCur->iPage];
   54166   assert( pPage->isInit );
   54167   if( !pPage->leaf ){
   54168     int idx = pCur->aiIdx[pCur->iPage];
   54169     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   54170     if( rc ){
   54171       return rc;
   54172     }
   54173     rc = moveToRightmost(pCur);
   54174   }else{
   54175     while( pCur->aiIdx[pCur->iPage]==0 ){
   54176       if( pCur->iPage==0 ){
   54177         pCur->eState = CURSOR_INVALID;
   54178         *pRes = 1;
   54179         return SQLITE_OK;
   54180       }
   54181       moveToParent(pCur);
   54182     }
   54183     pCur->info.nSize = 0;
   54184     pCur->validNKey = 0;
   54185 
   54186     pCur->aiIdx[pCur->iPage]--;
   54187     pPage = pCur->apPage[pCur->iPage];
   54188     if( pPage->intKey && !pPage->leaf ){
   54189       rc = sqlite3BtreePrevious(pCur, pRes);
   54190     }else{
   54191       rc = SQLITE_OK;
   54192     }
   54193   }
   54194   *pRes = 0;
   54195   return rc;
   54196 }
   54197 
   54198 /*
   54199 ** Allocate a new page from the database file.
   54200 **
   54201 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   54202 ** has already been called on the new page.)  The new page has also
   54203 ** been referenced and the calling routine is responsible for calling
   54204 ** sqlite3PagerUnref() on the new page when it is done.
   54205 **
   54206 ** SQLITE_OK is returned on success.  Any other return value indicates
   54207 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   54208 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   54209 **
   54210 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
   54211 ** locate a page close to the page number "nearby".  This can be used in an
   54212 ** attempt to keep related pages close to each other in the database file,
   54213 ** which in turn can make database access faster.
   54214 **
   54215 ** If the "exact" parameter is not 0, and the page-number nearby exists
   54216 ** anywhere on the free-list, then it is guarenteed to be returned. This
   54217 ** is only used by auto-vacuum databases when allocating a new table.
   54218 */
   54219 static int allocateBtreePage(
   54220   BtShared *pBt,
   54221   MemPage **ppPage,
   54222   Pgno *pPgno,
   54223   Pgno nearby,
   54224   u8 exact
   54225 ){
   54226   MemPage *pPage1;
   54227   int rc;
   54228   u32 n;     /* Number of pages on the freelist */
   54229   u32 k;     /* Number of leaves on the trunk of the freelist */
   54230   MemPage *pTrunk = 0;
   54231   MemPage *pPrevTrunk = 0;
   54232   Pgno mxPage;     /* Total size of the database file */
   54233 
   54234   assert( sqlite3_mutex_held(pBt->mutex) );
   54235   pPage1 = pBt->pPage1;
   54236   mxPage = btreePagecount(pBt);
   54237   n = get4byte(&pPage1->aData[36]);
   54238   testcase( n==mxPage-1 );
   54239   if( n>=mxPage ){
   54240     return SQLITE_CORRUPT_BKPT;
   54241   }
   54242   if( n>0 ){
   54243     /* There are pages on the freelist.  Reuse one of those pages. */
   54244     Pgno iTrunk;
   54245     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   54246 
   54247     /* If the 'exact' parameter was true and a query of the pointer-map
   54248     ** shows that the page 'nearby' is somewhere on the free-list, then
   54249     ** the entire-list will be searched for that page.
   54250     */
   54251 #ifndef SQLITE_OMIT_AUTOVACUUM
   54252     if( exact && nearby<=mxPage ){
   54253       u8 eType;
   54254       assert( nearby>0 );
   54255       assert( pBt->autoVacuum );
   54256       rc = ptrmapGet(pBt, nearby, &eType, 0);
   54257       if( rc ) return rc;
   54258       if( eType==PTRMAP_FREEPAGE ){
   54259         searchList = 1;
   54260       }
   54261       *pPgno = nearby;
   54262     }
   54263 #endif
   54264 
   54265     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   54266     ** first free-list trunk page. iPrevTrunk is initially 1.
   54267     */
   54268     rc = sqlite3PagerWrite(pPage1->pDbPage);
   54269     if( rc ) return rc;
   54270     put4byte(&pPage1->aData[36], n-1);
   54271 
   54272     /* The code within this loop is run only once if the 'searchList' variable
   54273     ** is not true. Otherwise, it runs once for each trunk-page on the
   54274     ** free-list until the page 'nearby' is located.
   54275     */
   54276     do {
   54277       pPrevTrunk = pTrunk;
   54278       if( pPrevTrunk ){
   54279         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   54280       }else{
   54281         iTrunk = get4byte(&pPage1->aData[32]);
   54282       }
   54283       testcase( iTrunk==mxPage );
   54284       if( iTrunk>mxPage ){
   54285         rc = SQLITE_CORRUPT_BKPT;
   54286       }else{
   54287         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   54288       }
   54289       if( rc ){
   54290         pTrunk = 0;
   54291         goto end_allocate_page;
   54292       }
   54293       assert( pTrunk!=0 );
   54294       assert( pTrunk->aData!=0 );
   54295 
   54296       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
   54297       if( k==0 && !searchList ){
   54298         /* The trunk has no leaves and the list is not being searched.
   54299         ** So extract the trunk page itself and use it as the newly
   54300         ** allocated page */
   54301         assert( pPrevTrunk==0 );
   54302         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54303         if( rc ){
   54304           goto end_allocate_page;
   54305         }
   54306         *pPgno = iTrunk;
   54307         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   54308         *ppPage = pTrunk;
   54309         pTrunk = 0;
   54310         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   54311       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   54312         /* Value of k is out of range.  Database corruption */
   54313         rc = SQLITE_CORRUPT_BKPT;
   54314         goto end_allocate_page;
   54315 #ifndef SQLITE_OMIT_AUTOVACUUM
   54316       }else if( searchList && nearby==iTrunk ){
   54317         /* The list is being searched and this trunk page is the page
   54318         ** to allocate, regardless of whether it has leaves.
   54319         */
   54320         assert( *pPgno==iTrunk );
   54321         *ppPage = pTrunk;
   54322         searchList = 0;
   54323         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54324         if( rc ){
   54325           goto end_allocate_page;
   54326         }
   54327         if( k==0 ){
   54328           if( !pPrevTrunk ){
   54329             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   54330           }else{
   54331             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   54332             if( rc!=SQLITE_OK ){
   54333               goto end_allocate_page;
   54334             }
   54335             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   54336           }
   54337         }else{
   54338           /* The trunk page is required by the caller but it contains
   54339           ** pointers to free-list leaves. The first leaf becomes a trunk
   54340           ** page in this case.
   54341           */
   54342           MemPage *pNewTrunk;
   54343           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   54344           if( iNewTrunk>mxPage ){
   54345             rc = SQLITE_CORRUPT_BKPT;
   54346             goto end_allocate_page;
   54347           }
   54348           testcase( iNewTrunk==mxPage );
   54349           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   54350           if( rc!=SQLITE_OK ){
   54351             goto end_allocate_page;
   54352           }
   54353           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   54354           if( rc!=SQLITE_OK ){
   54355             releasePage(pNewTrunk);
   54356             goto end_allocate_page;
   54357           }
   54358           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   54359           put4byte(&pNewTrunk->aData[4], k-1);
   54360           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   54361           releasePage(pNewTrunk);
   54362           if( !pPrevTrunk ){
   54363             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   54364             put4byte(&pPage1->aData[32], iNewTrunk);
   54365           }else{
   54366             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   54367             if( rc ){
   54368               goto end_allocate_page;
   54369             }
   54370             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   54371           }
   54372         }
   54373         pTrunk = 0;
   54374         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   54375 #endif
   54376       }else if( k>0 ){
   54377         /* Extract a leaf from the trunk */
   54378         u32 closest;
   54379         Pgno iPage;
   54380         unsigned char *aData = pTrunk->aData;
   54381         if( nearby>0 ){
   54382           u32 i;
   54383           int dist;
   54384           closest = 0;
   54385           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
   54386           for(i=1; i<k; i++){
   54387             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
   54388             if( d2<dist ){
   54389               closest = i;
   54390               dist = d2;
   54391             }
   54392           }
   54393         }else{
   54394           closest = 0;
   54395         }
   54396 
   54397         iPage = get4byte(&aData[8+closest*4]);
   54398         testcase( iPage==mxPage );
   54399         if( iPage>mxPage ){
   54400           rc = SQLITE_CORRUPT_BKPT;
   54401           goto end_allocate_page;
   54402         }
   54403         testcase( iPage==mxPage );
   54404         if( !searchList || iPage==nearby ){
   54405           int noContent;
   54406           *pPgno = iPage;
   54407           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   54408                  ": %d more free pages\n",
   54409                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   54410           rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54411           if( rc ) goto end_allocate_page;
   54412           if( closest<k-1 ){
   54413             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   54414           }
   54415           put4byte(&aData[4], k-1);
   54416           noContent = !btreeGetHasContent(pBt, *pPgno);
   54417           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   54418           if( rc==SQLITE_OK ){
   54419             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   54420             if( rc!=SQLITE_OK ){
   54421               releasePage(*ppPage);
   54422             }
   54423           }
   54424           searchList = 0;
   54425         }
   54426       }
   54427       releasePage(pPrevTrunk);
   54428       pPrevTrunk = 0;
   54429     }while( searchList );
   54430   }else{
   54431     /* There are no pages on the freelist, so create a new page at the
   54432     ** end of the file */
   54433     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54434     if( rc ) return rc;
   54435     pBt->nPage++;
   54436     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   54437 
   54438 #ifndef SQLITE_OMIT_AUTOVACUUM
   54439     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   54440       /* If *pPgno refers to a pointer-map page, allocate two new pages
   54441       ** at the end of the file instead of one. The first allocated page
   54442       ** becomes a new pointer-map page, the second is used by the caller.
   54443       */
   54444       MemPage *pPg = 0;
   54445       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   54446       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   54447       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
   54448       if( rc==SQLITE_OK ){
   54449         rc = sqlite3PagerWrite(pPg->pDbPage);
   54450         releasePage(pPg);
   54451       }
   54452       if( rc ) return rc;
   54453       pBt->nPage++;
   54454       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   54455     }
   54456 #endif
   54457     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   54458     *pPgno = pBt->nPage;
   54459 
   54460     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   54461     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
   54462     if( rc ) return rc;
   54463     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   54464     if( rc!=SQLITE_OK ){
   54465       releasePage(*ppPage);
   54466     }
   54467     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   54468   }
   54469 
   54470   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   54471 
   54472 end_allocate_page:
   54473   releasePage(pTrunk);
   54474   releasePage(pPrevTrunk);
   54475   if( rc==SQLITE_OK ){
   54476     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   54477       releasePage(*ppPage);
   54478       return SQLITE_CORRUPT_BKPT;
   54479     }
   54480     (*ppPage)->isInit = 0;
   54481   }else{
   54482     *ppPage = 0;
   54483   }
   54484   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
   54485   return rc;
   54486 }
   54487 
   54488 /*
   54489 ** This function is used to add page iPage to the database file free-list.
   54490 ** It is assumed that the page is not already a part of the free-list.
   54491 **
   54492 ** The value passed as the second argument to this function is optional.
   54493 ** If the caller happens to have a pointer to the MemPage object
   54494 ** corresponding to page iPage handy, it may pass it as the second value.
   54495 ** Otherwise, it may pass NULL.
   54496 **
   54497 ** If a pointer to a MemPage object is passed as the second argument,
   54498 ** its reference count is not altered by this function.
   54499 */
   54500 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   54501   MemPage *pTrunk = 0;                /* Free-list trunk page */
   54502   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   54503   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   54504   MemPage *pPage;                     /* Page being freed. May be NULL. */
   54505   int rc;                             /* Return Code */
   54506   int nFree;                          /* Initial number of pages on free-list */
   54507 
   54508   assert( sqlite3_mutex_held(pBt->mutex) );
   54509   assert( iPage>1 );
   54510   assert( !pMemPage || pMemPage->pgno==iPage );
   54511 
   54512   if( pMemPage ){
   54513     pPage = pMemPage;
   54514     sqlite3PagerRef(pPage->pDbPage);
   54515   }else{
   54516     pPage = btreePageLookup(pBt, iPage);
   54517   }
   54518 
   54519   /* Increment the free page count on pPage1 */
   54520   rc = sqlite3PagerWrite(pPage1->pDbPage);
   54521   if( rc ) goto freepage_out;
   54522   nFree = get4byte(&pPage1->aData[36]);
   54523   put4byte(&pPage1->aData[36], nFree+1);
   54524 
   54525   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   54526     /* If the secure_delete option is enabled, then
   54527     ** always fully overwrite deleted information with zeros.
   54528     */
   54529     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   54530      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   54531     ){
   54532       goto freepage_out;
   54533     }
   54534     memset(pPage->aData, 0, pPage->pBt->pageSize);
   54535   }
   54536 
   54537   /* If the database supports auto-vacuum, write an entry in the pointer-map
   54538   ** to indicate that the page is free.
   54539   */
   54540   if( ISAUTOVACUUM ){
   54541     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   54542     if( rc ) goto freepage_out;
   54543   }
   54544 
   54545   /* Now manipulate the actual database free-list structure. There are two
   54546   ** possibilities. If the free-list is currently empty, or if the first
   54547   ** trunk page in the free-list is full, then this page will become a
   54548   ** new free-list trunk page. Otherwise, it will become a leaf of the
   54549   ** first trunk page in the current free-list. This block tests if it
   54550   ** is possible to add the page as a new free-list leaf.
   54551   */
   54552   if( nFree!=0 ){
   54553     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   54554 
   54555     iTrunk = get4byte(&pPage1->aData[32]);
   54556     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   54557     if( rc!=SQLITE_OK ){
   54558       goto freepage_out;
   54559     }
   54560 
   54561     nLeaf = get4byte(&pTrunk->aData[4]);
   54562     assert( pBt->usableSize>32 );
   54563     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   54564       rc = SQLITE_CORRUPT_BKPT;
   54565       goto freepage_out;
   54566     }
   54567     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   54568       /* In this case there is room on the trunk page to insert the page
   54569       ** being freed as a new leaf.
   54570       **
   54571       ** Note that the trunk page is not really full until it contains
   54572       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   54573       ** coded.  But due to a coding error in versions of SQLite prior to
   54574       ** 3.6.0, databases with freelist trunk pages holding more than
   54575       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   54576       ** to maintain backwards compatibility with older versions of SQLite,
   54577       ** we will continue to restrict the number of entries to usableSize/4 - 8
   54578       ** for now.  At some point in the future (once everyone has upgraded
   54579       ** to 3.6.0 or later) we should consider fixing the conditional above
   54580       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   54581       */
   54582       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54583       if( rc==SQLITE_OK ){
   54584         put4byte(&pTrunk->aData[4], nLeaf+1);
   54585         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   54586         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
   54587           sqlite3PagerDontWrite(pPage->pDbPage);
   54588         }
   54589         rc = btreeSetHasContent(pBt, iPage);
   54590       }
   54591       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   54592       goto freepage_out;
   54593     }
   54594   }
   54595 
   54596   /* If control flows to this point, then it was not possible to add the
   54597   ** the page being freed as a leaf page of the first trunk in the free-list.
   54598   ** Possibly because the free-list is empty, or possibly because the
   54599   ** first trunk in the free-list is full. Either way, the page being freed
   54600   ** will become the new first trunk page in the free-list.
   54601   */
   54602   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   54603     goto freepage_out;
   54604   }
   54605   rc = sqlite3PagerWrite(pPage->pDbPage);
   54606   if( rc!=SQLITE_OK ){
   54607     goto freepage_out;
   54608   }
   54609   put4byte(pPage->aData, iTrunk);
   54610   put4byte(&pPage->aData[4], 0);
   54611   put4byte(&pPage1->aData[32], iPage);
   54612   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   54613 
   54614 freepage_out:
   54615   if( pPage ){
   54616     pPage->isInit = 0;
   54617   }
   54618   releasePage(pPage);
   54619   releasePage(pTrunk);
   54620   return rc;
   54621 }
   54622 static void freePage(MemPage *pPage, int *pRC){
   54623   if( (*pRC)==SQLITE_OK ){
   54624     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   54625   }
   54626 }
   54627 
   54628 /*
   54629 ** Free any overflow pages associated with the given Cell.
   54630 */
   54631 static int clearCell(MemPage *pPage, unsigned char *pCell){
   54632   BtShared *pBt = pPage->pBt;
   54633   CellInfo info;
   54634   Pgno ovflPgno;
   54635   int rc;
   54636   int nOvfl;
   54637   u32 ovflPageSize;
   54638 
   54639   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54640   btreeParseCellPtr(pPage, pCell, &info);
   54641   if( info.iOverflow==0 ){
   54642     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   54643   }
   54644   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
   54645     return SQLITE_CORRUPT;  /* Cell extends past end of page */
   54646   }
   54647   ovflPgno = get4byte(&pCell[info.iOverflow]);
   54648   assert( pBt->usableSize > 4 );
   54649   ovflPageSize = pBt->usableSize - 4;
   54650   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   54651   assert( ovflPgno==0 || nOvfl>0 );
   54652   while( nOvfl-- ){
   54653     Pgno iNext = 0;
   54654     MemPage *pOvfl = 0;
   54655     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   54656       /* 0 is not a legal page number and page 1 cannot be an
   54657       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   54658       ** file the database must be corrupt. */
   54659       return SQLITE_CORRUPT_BKPT;
   54660     }
   54661     if( nOvfl ){
   54662       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   54663       if( rc ) return rc;
   54664     }
   54665 
   54666     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   54667      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   54668     ){
   54669       /* There is no reason any cursor should have an outstanding reference
   54670       ** to an overflow page belonging to a cell that is being deleted/updated.
   54671       ** So if there exists more than one reference to this page, then it
   54672       ** must not really be an overflow page and the database must be corrupt.
   54673       ** It is helpful to detect this before calling freePage2(), as
   54674       ** freePage2() may zero the page contents if secure-delete mode is
   54675       ** enabled. If this 'overflow' page happens to be a page that the
   54676       ** caller is iterating through or using in some other way, this
   54677       ** can be problematic.
   54678       */
   54679       rc = SQLITE_CORRUPT_BKPT;
   54680     }else{
   54681       rc = freePage2(pBt, pOvfl, ovflPgno);
   54682     }
   54683 
   54684     if( pOvfl ){
   54685       sqlite3PagerUnref(pOvfl->pDbPage);
   54686     }
   54687     if( rc ) return rc;
   54688     ovflPgno = iNext;
   54689   }
   54690   return SQLITE_OK;
   54691 }
   54692 
   54693 /*
   54694 ** Create the byte sequence used to represent a cell on page pPage
   54695 ** and write that byte sequence into pCell[].  Overflow pages are
   54696 ** allocated and filled in as necessary.  The calling procedure
   54697 ** is responsible for making sure sufficient space has been allocated
   54698 ** for pCell[].
   54699 **
   54700 ** Note that pCell does not necessary need to point to the pPage->aData
   54701 ** area.  pCell might point to some temporary storage.  The cell will
   54702 ** be constructed in this temporary area then copied into pPage->aData
   54703 ** later.
   54704 */
   54705 static int fillInCell(
   54706   MemPage *pPage,                /* The page that contains the cell */
   54707   unsigned char *pCell,          /* Complete text of the cell */
   54708   const void *pKey, i64 nKey,    /* The key */
   54709   const void *pData,int nData,   /* The data */
   54710   int nZero,                     /* Extra zero bytes to append to pData */
   54711   int *pnSize                    /* Write cell size here */
   54712 ){
   54713   int nPayload;
   54714   const u8 *pSrc;
   54715   int nSrc, n, rc;
   54716   int spaceLeft;
   54717   MemPage *pOvfl = 0;
   54718   MemPage *pToRelease = 0;
   54719   unsigned char *pPrior;
   54720   unsigned char *pPayload;
   54721   BtShared *pBt = pPage->pBt;
   54722   Pgno pgnoOvfl = 0;
   54723   int nHeader;
   54724   CellInfo info;
   54725 
   54726   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54727 
   54728   /* pPage is not necessarily writeable since pCell might be auxiliary
   54729   ** buffer space that is separate from the pPage buffer area */
   54730   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   54731             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54732 
   54733   /* Fill in the header. */
   54734   nHeader = 0;
   54735   if( !pPage->leaf ){
   54736     nHeader += 4;
   54737   }
   54738   if( pPage->hasData ){
   54739     nHeader += putVarint(&pCell[nHeader], nData+nZero);
   54740   }else{
   54741     nData = nZero = 0;
   54742   }
   54743   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   54744   btreeParseCellPtr(pPage, pCell, &info);
   54745   assert( info.nHeader==nHeader );
   54746   assert( info.nKey==nKey );
   54747   assert( info.nData==(u32)(nData+nZero) );
   54748 
   54749   /* Fill in the payload */
   54750   nPayload = nData + nZero;
   54751   if( pPage->intKey ){
   54752     pSrc = pData;
   54753     nSrc = nData;
   54754     nData = 0;
   54755   }else{
   54756     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   54757       return SQLITE_CORRUPT_BKPT;
   54758     }
   54759     nPayload += (int)nKey;
   54760     pSrc = pKey;
   54761     nSrc = (int)nKey;
   54762   }
   54763   *pnSize = info.nSize;
   54764   spaceLeft = info.nLocal;
   54765   pPayload = &pCell[nHeader];
   54766   pPrior = &pCell[info.iOverflow];
   54767 
   54768   while( nPayload>0 ){
   54769     if( spaceLeft==0 ){
   54770 #ifndef SQLITE_OMIT_AUTOVACUUM
   54771       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   54772       if( pBt->autoVacuum ){
   54773         do{
   54774           pgnoOvfl++;
   54775         } while(
   54776           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   54777         );
   54778       }
   54779 #endif
   54780       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   54781 #ifndef SQLITE_OMIT_AUTOVACUUM
   54782       /* If the database supports auto-vacuum, and the second or subsequent
   54783       ** overflow page is being allocated, add an entry to the pointer-map
   54784       ** for that page now.
   54785       **
   54786       ** If this is the first overflow page, then write a partial entry
   54787       ** to the pointer-map. If we write nothing to this pointer-map slot,
   54788       ** then the optimistic overflow chain processing in clearCell()
   54789       ** may misinterpret the uninitialised values and delete the
   54790       ** wrong pages from the database.
   54791       */
   54792       if( pBt->autoVacuum && rc==SQLITE_OK ){
   54793         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   54794         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   54795         if( rc ){
   54796           releasePage(pOvfl);
   54797         }
   54798       }
   54799 #endif
   54800       if( rc ){
   54801         releasePage(pToRelease);
   54802         return rc;
   54803       }
   54804 
   54805       /* If pToRelease is not zero than pPrior points into the data area
   54806       ** of pToRelease.  Make sure pToRelease is still writeable. */
   54807       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   54808 
   54809       /* If pPrior is part of the data area of pPage, then make sure pPage
   54810       ** is still writeable */
   54811       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   54812             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54813 
   54814       put4byte(pPrior, pgnoOvfl);
   54815       releasePage(pToRelease);
   54816       pToRelease = pOvfl;
   54817       pPrior = pOvfl->aData;
   54818       put4byte(pPrior, 0);
   54819       pPayload = &pOvfl->aData[4];
   54820       spaceLeft = pBt->usableSize - 4;
   54821     }
   54822     n = nPayload;
   54823     if( n>spaceLeft ) n = spaceLeft;
   54824 
   54825     /* If pToRelease is not zero than pPayload points into the data area
   54826     ** of pToRelease.  Make sure pToRelease is still writeable. */
   54827     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   54828 
   54829     /* If pPayload is part of the data area of pPage, then make sure pPage
   54830     ** is still writeable */
   54831     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   54832             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54833 
   54834     if( nSrc>0 ){
   54835       if( n>nSrc ) n = nSrc;
   54836       assert( pSrc );
   54837       memcpy(pPayload, pSrc, n);
   54838     }else{
   54839       memset(pPayload, 0, n);
   54840     }
   54841     nPayload -= n;
   54842     pPayload += n;
   54843     pSrc += n;
   54844     nSrc -= n;
   54845     spaceLeft -= n;
   54846     if( nSrc==0 ){
   54847       nSrc = nData;
   54848       pSrc = pData;
   54849     }
   54850   }
   54851   releasePage(pToRelease);
   54852   return SQLITE_OK;
   54853 }
   54854 
   54855 /*
   54856 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   54857 ** The cell content is not freed or deallocated.  It is assumed that
   54858 ** the cell content has been copied someplace else.  This routine just
   54859 ** removes the reference to the cell from pPage.
   54860 **
   54861 ** "sz" must be the number of bytes in the cell.
   54862 */
   54863 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   54864   u32 pc;         /* Offset to cell content of cell being deleted */
   54865   u8 *data;       /* pPage->aData */
   54866   u8 *ptr;        /* Used to move bytes around within data[] */
   54867   u8 *endPtr;     /* End of loop */
   54868   int rc;         /* The return code */
   54869   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   54870 
   54871   if( *pRC ) return;
   54872 
   54873   assert( idx>=0 && idx<pPage->nCell );
   54874   assert( sz==cellSize(pPage, idx) );
   54875   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54876   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54877   data = pPage->aData;
   54878   ptr = &pPage->aCellIdx[2*idx];
   54879   pc = get2byte(ptr);
   54880   hdr = pPage->hdrOffset;
   54881   testcase( pc==get2byte(&data[hdr+5]) );
   54882   testcase( pc+sz==pPage->pBt->usableSize );
   54883   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   54884     *pRC = SQLITE_CORRUPT_BKPT;
   54885     return;
   54886   }
   54887   rc = freeSpace(pPage, pc, sz);
   54888   if( rc ){
   54889     *pRC = rc;
   54890     return;
   54891   }
   54892   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
   54893   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
   54894   while( ptr<endPtr ){
   54895     *(u16*)ptr = *(u16*)&ptr[2];
   54896     ptr += 2;
   54897   }
   54898   pPage->nCell--;
   54899   put2byte(&data[hdr+3], pPage->nCell);
   54900   pPage->nFree += 2;
   54901 }
   54902 
   54903 /*
   54904 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   54905 ** content of the cell.
   54906 **
   54907 ** If the cell content will fit on the page, then put it there.  If it
   54908 ** will not fit, then make a copy of the cell content into pTemp if
   54909 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   54910 ** in pPage->apOvfl[] and make it point to the cell content (either
   54911 ** in pTemp or the original pCell) and also record its index.
   54912 ** Allocating a new entry in pPage->aCell[] implies that
   54913 ** pPage->nOverflow is incremented.
   54914 **
   54915 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   54916 ** cell. The caller will overwrite them after this function returns. If
   54917 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   54918 ** (but pCell+nSkip is always valid).
   54919 */
   54920 static void insertCell(
   54921   MemPage *pPage,   /* Page into which we are copying */
   54922   int i,            /* New cell becomes the i-th cell of the page */
   54923   u8 *pCell,        /* Content of the new cell */
   54924   int sz,           /* Bytes of content in pCell */
   54925   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   54926   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   54927   int *pRC          /* Read and write return code from here */
   54928 ){
   54929   int idx = 0;      /* Where to write new cell content in data[] */
   54930   int j;            /* Loop counter */
   54931   int end;          /* First byte past the last cell pointer in data[] */
   54932   int ins;          /* Index in data[] where new cell pointer is inserted */
   54933   int cellOffset;   /* Address of first cell pointer in data[] */
   54934   u8 *data;         /* The content of the whole page */
   54935   u8 *ptr;          /* Used for moving information around in data[] */
   54936   u8 *endPtr;       /* End of the loop */
   54937 
   54938   int nSkip = (iChild ? 4 : 0);
   54939 
   54940   if( *pRC ) return;
   54941 
   54942   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   54943   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
   54944   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
   54945   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
   54946   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54947   /* The cell should normally be sized correctly.  However, when moving a
   54948   ** malformed cell from a leaf page to an interior page, if the cell size
   54949   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   54950   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   54951   ** the term after the || in the following assert(). */
   54952   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   54953   if( pPage->nOverflow || sz+2>pPage->nFree ){
   54954     if( pTemp ){
   54955       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   54956       pCell = pTemp;
   54957     }
   54958     if( iChild ){
   54959       put4byte(pCell, iChild);
   54960     }
   54961     j = pPage->nOverflow++;
   54962     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
   54963     pPage->apOvfl[j] = pCell;
   54964     pPage->aiOvfl[j] = (u16)i;
   54965   }else{
   54966     int rc = sqlite3PagerWrite(pPage->pDbPage);
   54967     if( rc!=SQLITE_OK ){
   54968       *pRC = rc;
   54969       return;
   54970     }
   54971     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54972     data = pPage->aData;
   54973     cellOffset = pPage->cellOffset;
   54974     end = cellOffset + 2*pPage->nCell;
   54975     ins = cellOffset + 2*i;
   54976     rc = allocateSpace(pPage, sz, &idx);
   54977     if( rc ){ *pRC = rc; return; }
   54978     /* The allocateSpace() routine guarantees the following two properties
   54979     ** if it returns success */
   54980     assert( idx >= end+2 );
   54981     assert( idx+sz <= (int)pPage->pBt->usableSize );
   54982     pPage->nCell++;
   54983     pPage->nFree -= (u16)(2 + sz);
   54984     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   54985     if( iChild ){
   54986       put4byte(&data[idx], iChild);
   54987     }
   54988     ptr = &data[end];
   54989     endPtr = &data[ins];
   54990     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
   54991     while( ptr>endPtr ){
   54992       *(u16*)ptr = *(u16*)&ptr[-2];
   54993       ptr -= 2;
   54994     }
   54995     put2byte(&data[ins], idx);
   54996     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   54997 #ifndef SQLITE_OMIT_AUTOVACUUM
   54998     if( pPage->pBt->autoVacuum ){
   54999       /* The cell may contain a pointer to an overflow page. If so, write
   55000       ** the entry for the overflow page into the pointer map.
   55001       */
   55002       ptrmapPutOvflPtr(pPage, pCell, pRC);
   55003     }
   55004 #endif
   55005   }
   55006 }
   55007 
   55008 /*
   55009 ** Add a list of cells to a page.  The page should be initially empty.
   55010 ** The cells are guaranteed to fit on the page.
   55011 */
   55012 static void assemblePage(
   55013   MemPage *pPage,   /* The page to be assemblied */
   55014   int nCell,        /* The number of cells to add to this page */
   55015   u8 **apCell,      /* Pointers to cell bodies */
   55016   u16 *aSize        /* Sizes of the cells */
   55017 ){
   55018   int i;            /* Loop counter */
   55019   u8 *pCellptr;     /* Address of next cell pointer */
   55020   int cellbody;     /* Address of next cell body */
   55021   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   55022   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   55023   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   55024 
   55025   assert( pPage->nOverflow==0 );
   55026   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   55027   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
   55028             && (int)MX_CELL(pPage->pBt)<=10921);
   55029   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   55030 
   55031   /* Check that the page has just been zeroed by zeroPage() */
   55032   assert( pPage->nCell==0 );
   55033   assert( get2byteNotZero(&data[hdr+5])==nUsable );
   55034 
   55035   pCellptr = &pPage->aCellIdx[nCell*2];
   55036   cellbody = nUsable;
   55037   for(i=nCell-1; i>=0; i--){
   55038     u16 sz = aSize[i];
   55039     pCellptr -= 2;
   55040     cellbody -= sz;
   55041     put2byte(pCellptr, cellbody);
   55042     memcpy(&data[cellbody], apCell[i], sz);
   55043   }
   55044   put2byte(&data[hdr+3], nCell);
   55045   put2byte(&data[hdr+5], cellbody);
   55046   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   55047   pPage->nCell = (u16)nCell;
   55048 }
   55049 
   55050 /*
   55051 ** The following parameters determine how many adjacent pages get involved
   55052 ** in a balancing operation.  NN is the number of neighbors on either side
   55053 ** of the page that participate in the balancing operation.  NB is the
   55054 ** total number of pages that participate, including the target page and
   55055 ** NN neighbors on either side.
   55056 **
   55057 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   55058 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   55059 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   55060 ** The value of NN appears to give the best results overall.
   55061 */
   55062 #define NN 1             /* Number of neighbors on either side of pPage */
   55063 #define NB (NN*2+1)      /* Total pages involved in the balance */
   55064 
   55065 
   55066 #ifndef SQLITE_OMIT_QUICKBALANCE
   55067 /*
   55068 ** This version of balance() handles the common special case where
   55069 ** a new entry is being inserted on the extreme right-end of the
   55070 ** tree, in other words, when the new entry will become the largest
   55071 ** entry in the tree.
   55072 **
   55073 ** Instead of trying to balance the 3 right-most leaf pages, just add
   55074 ** a new page to the right-hand side and put the one new entry in
   55075 ** that page.  This leaves the right side of the tree somewhat
   55076 ** unbalanced.  But odds are that we will be inserting new entries
   55077 ** at the end soon afterwards so the nearly empty page will quickly
   55078 ** fill up.  On average.
   55079 **
   55080 ** pPage is the leaf page which is the right-most page in the tree.
   55081 ** pParent is its parent.  pPage must have a single overflow entry
   55082 ** which is also the right-most entry on the page.
   55083 **
   55084 ** The pSpace buffer is used to store a temporary copy of the divider
   55085 ** cell that will be inserted into pParent. Such a cell consists of a 4
   55086 ** byte page number followed by a variable length integer. In other
   55087 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   55088 ** least 13 bytes in size.
   55089 */
   55090 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   55091   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   55092   MemPage *pNew;                       /* Newly allocated page */
   55093   int rc;                              /* Return Code */
   55094   Pgno pgnoNew;                        /* Page number of pNew */
   55095 
   55096   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   55097   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55098   assert( pPage->nOverflow==1 );
   55099 
   55100   /* This error condition is now caught prior to reaching this function */
   55101   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
   55102 
   55103   /* Allocate a new page. This page will become the right-sibling of
   55104   ** pPage. Make the parent page writable, so that the new divider cell
   55105   ** may be inserted. If both these operations are successful, proceed.
   55106   */
   55107   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   55108 
   55109   if( rc==SQLITE_OK ){
   55110 
   55111     u8 *pOut = &pSpace[4];
   55112     u8 *pCell = pPage->apOvfl[0];
   55113     u16 szCell = cellSizePtr(pPage, pCell);
   55114     u8 *pStop;
   55115 
   55116     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   55117     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   55118     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   55119     assemblePage(pNew, 1, &pCell, &szCell);
   55120 
   55121     /* If this is an auto-vacuum database, update the pointer map
   55122     ** with entries for the new page, and any pointer from the
   55123     ** cell on the page to an overflow page. If either of these
   55124     ** operations fails, the return code is set, but the contents
   55125     ** of the parent page are still manipulated by thh code below.
   55126     ** That is Ok, at this point the parent page is guaranteed to
   55127     ** be marked as dirty. Returning an error code will cause a
   55128     ** rollback, undoing any changes made to the parent page.
   55129     */
   55130     if( ISAUTOVACUUM ){
   55131       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   55132       if( szCell>pNew->minLocal ){
   55133         ptrmapPutOvflPtr(pNew, pCell, &rc);
   55134       }
   55135     }
   55136 
   55137     /* Create a divider cell to insert into pParent. The divider cell
   55138     ** consists of a 4-byte page number (the page number of pPage) and
   55139     ** a variable length key value (which must be the same value as the
   55140     ** largest key on pPage).
   55141     **
   55142     ** To find the largest key value on pPage, first find the right-most
   55143     ** cell on pPage. The first two fields of this cell are the
   55144     ** record-length (a variable length integer at most 32-bits in size)
   55145     ** and the key value (a variable length integer, may have any value).
   55146     ** The first of the while(...) loops below skips over the record-length
   55147     ** field. The second while(...) loop copies the key value from the
   55148     ** cell on pPage into the pSpace buffer.
   55149     */
   55150     pCell = findCell(pPage, pPage->nCell-1);
   55151     pStop = &pCell[9];
   55152     while( (*(pCell++)&0x80) && pCell<pStop );
   55153     pStop = &pCell[9];
   55154     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   55155 
   55156     /* Insert the new divider cell into pParent. */
   55157     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   55158                0, pPage->pgno, &rc);
   55159 
   55160     /* Set the right-child pointer of pParent to point to the new page. */
   55161     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   55162 
   55163     /* Release the reference to the new page. */
   55164     releasePage(pNew);
   55165   }
   55166 
   55167   return rc;
   55168 }
   55169 #endif /* SQLITE_OMIT_QUICKBALANCE */
   55170 
   55171 #if 0
   55172 /*
   55173 ** This function does not contribute anything to the operation of SQLite.
   55174 ** it is sometimes activated temporarily while debugging code responsible
   55175 ** for setting pointer-map entries.
   55176 */
   55177 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   55178   int i, j;
   55179   for(i=0; i<nPage; i++){
   55180     Pgno n;
   55181     u8 e;
   55182     MemPage *pPage = apPage[i];
   55183     BtShared *pBt = pPage->pBt;
   55184     assert( pPage->isInit );
   55185 
   55186     for(j=0; j<pPage->nCell; j++){
   55187       CellInfo info;
   55188       u8 *z;
   55189 
   55190       z = findCell(pPage, j);
   55191       btreeParseCellPtr(pPage, z, &info);
   55192       if( info.iOverflow ){
   55193         Pgno ovfl = get4byte(&z[info.iOverflow]);
   55194         ptrmapGet(pBt, ovfl, &e, &n);
   55195         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   55196       }
   55197       if( !pPage->leaf ){
   55198         Pgno child = get4byte(z);
   55199         ptrmapGet(pBt, child, &e, &n);
   55200         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   55201       }
   55202     }
   55203     if( !pPage->leaf ){
   55204       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   55205       ptrmapGet(pBt, child, &e, &n);
   55206       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   55207     }
   55208   }
   55209   return 1;
   55210 }
   55211 #endif
   55212 
   55213 /*
   55214 ** This function is used to copy the contents of the b-tree node stored
   55215 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   55216 ** the pointer-map entries for each child page are updated so that the
   55217 ** parent page stored in the pointer map is page pTo. If pFrom contained
   55218 ** any cells with overflow page pointers, then the corresponding pointer
   55219 ** map entries are also updated so that the parent page is page pTo.
   55220 **
   55221 ** If pFrom is currently carrying any overflow cells (entries in the
   55222 ** MemPage.apOvfl[] array), they are not copied to pTo.
   55223 **
   55224 ** Before returning, page pTo is reinitialized using btreeInitPage().
   55225 **
   55226 ** The performance of this function is not critical. It is only used by
   55227 ** the balance_shallower() and balance_deeper() procedures, neither of
   55228 ** which are called often under normal circumstances.
   55229 */
   55230 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   55231   if( (*pRC)==SQLITE_OK ){
   55232     BtShared * const pBt = pFrom->pBt;
   55233     u8 * const aFrom = pFrom->aData;
   55234     u8 * const aTo = pTo->aData;
   55235     int const iFromHdr = pFrom->hdrOffset;
   55236     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   55237     int rc;
   55238     int iData;
   55239 
   55240 
   55241     assert( pFrom->isInit );
   55242     assert( pFrom->nFree>=iToHdr );
   55243     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
   55244 
   55245     /* Copy the b-tree node content from page pFrom to page pTo. */
   55246     iData = get2byte(&aFrom[iFromHdr+5]);
   55247     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   55248     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   55249 
   55250     /* Reinitialize page pTo so that the contents of the MemPage structure
   55251     ** match the new data. The initialization of pTo can actually fail under
   55252     ** fairly obscure circumstances, even though it is a copy of initialized
   55253     ** page pFrom.
   55254     */
   55255     pTo->isInit = 0;
   55256     rc = btreeInitPage(pTo);
   55257     if( rc!=SQLITE_OK ){
   55258       *pRC = rc;
   55259       return;
   55260     }
   55261 
   55262     /* If this is an auto-vacuum database, update the pointer-map entries
   55263     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   55264     */
   55265     if( ISAUTOVACUUM ){
   55266       *pRC = setChildPtrmaps(pTo);
   55267     }
   55268   }
   55269 }
   55270 
   55271 /*
   55272 ** This routine redistributes cells on the iParentIdx'th child of pParent
   55273 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   55274 ** same amount of free space. Usually a single sibling on either side of the
   55275 ** page are used in the balancing, though both siblings might come from one
   55276 ** side if the page is the first or last child of its parent. If the page
   55277 ** has fewer than 2 siblings (something which can only happen if the page
   55278 ** is a root page or a child of a root page) then all available siblings
   55279 ** participate in the balancing.
   55280 **
   55281 ** The number of siblings of the page might be increased or decreased by
   55282 ** one or two in an effort to keep pages nearly full but not over full.
   55283 **
   55284 ** Note that when this routine is called, some of the cells on the page
   55285 ** might not actually be stored in MemPage.aData[]. This can happen
   55286 ** if the page is overfull. This routine ensures that all cells allocated
   55287 ** to the page and its siblings fit into MemPage.aData[] before returning.
   55288 **
   55289 ** In the course of balancing the page and its siblings, cells may be
   55290 ** inserted into or removed from the parent page (pParent). Doing so
   55291 ** may cause the parent page to become overfull or underfull. If this
   55292 ** happens, it is the responsibility of the caller to invoke the correct
   55293 ** balancing routine to fix this problem (see the balance() routine).
   55294 **
   55295 ** If this routine fails for any reason, it might leave the database
   55296 ** in a corrupted state. So if this routine fails, the database should
   55297 ** be rolled back.
   55298 **
   55299 ** The third argument to this function, aOvflSpace, is a pointer to a
   55300 ** buffer big enough to hold one page. If while inserting cells into the parent
   55301 ** page (pParent) the parent page becomes overfull, this buffer is
   55302 ** used to store the parent's overflow cells. Because this function inserts
   55303 ** a maximum of four divider cells into the parent page, and the maximum
   55304 ** size of a cell stored within an internal node is always less than 1/4
   55305 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   55306 ** enough for all overflow cells.
   55307 **
   55308 ** If aOvflSpace is set to a null pointer, this function returns
   55309 ** SQLITE_NOMEM.
   55310 */
   55311 static int balance_nonroot(
   55312   MemPage *pParent,               /* Parent page of siblings being balanced */
   55313   int iParentIdx,                 /* Index of "the page" in pParent */
   55314   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   55315   int isRoot                      /* True if pParent is a root-page */
   55316 ){
   55317   BtShared *pBt;               /* The whole database */
   55318   int nCell = 0;               /* Number of cells in apCell[] */
   55319   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   55320   int nNew = 0;                /* Number of pages in apNew[] */
   55321   int nOld;                    /* Number of pages in apOld[] */
   55322   int i, j, k;                 /* Loop counters */
   55323   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   55324   int rc = SQLITE_OK;          /* The return code */
   55325   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   55326   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   55327   int usableSpace;             /* Bytes in pPage beyond the header */
   55328   int pageFlags;               /* Value of pPage->aData[0] */
   55329   int subtotal;                /* Subtotal of bytes in cells on one page */
   55330   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   55331   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   55332   int szScratch;               /* Size of scratch memory requested */
   55333   MemPage *apOld[NB];          /* pPage and up to two siblings */
   55334   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   55335   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   55336   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   55337   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   55338   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   55339   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   55340   u8 **apCell = 0;             /* All cells begin balanced */
   55341   u16 *szCell;                 /* Local size of all cells in apCell[] */
   55342   u8 *aSpace1;                 /* Space for copies of dividers cells */
   55343   Pgno pgno;                   /* Temp var to store a page number in */
   55344 
   55345   pBt = pParent->pBt;
   55346   assert( sqlite3_mutex_held(pBt->mutex) );
   55347   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55348 
   55349 #if 0
   55350   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   55351 #endif
   55352 
   55353   /* At this point pParent may have at most one overflow cell. And if
   55354   ** this overflow cell is present, it must be the cell with
   55355   ** index iParentIdx. This scenario comes about when this function
   55356   ** is called (indirectly) from sqlite3BtreeDelete().
   55357   */
   55358   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   55359   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
   55360 
   55361   if( !aOvflSpace ){
   55362     return SQLITE_NOMEM;
   55363   }
   55364 
   55365   /* Find the sibling pages to balance. Also locate the cells in pParent
   55366   ** that divide the siblings. An attempt is made to find NN siblings on
   55367   ** either side of pPage. More siblings are taken from one side, however,
   55368   ** if there are fewer than NN siblings on the other side. If pParent
   55369   ** has NB or fewer children then all children of pParent are taken.
   55370   **
   55371   ** This loop also drops the divider cells from the parent page. This
   55372   ** way, the remainder of the function does not have to deal with any
   55373   ** overflow cells in the parent page, since if any existed they will
   55374   ** have already been removed.
   55375   */
   55376   i = pParent->nOverflow + pParent->nCell;
   55377   if( i<2 ){
   55378     nxDiv = 0;
   55379     nOld = i+1;
   55380   }else{
   55381     nOld = 3;
   55382     if( iParentIdx==0 ){
   55383       nxDiv = 0;
   55384     }else if( iParentIdx==i ){
   55385       nxDiv = i-2;
   55386     }else{
   55387       nxDiv = iParentIdx-1;
   55388     }
   55389     i = 2;
   55390   }
   55391   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   55392     pRight = &pParent->aData[pParent->hdrOffset+8];
   55393   }else{
   55394     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   55395   }
   55396   pgno = get4byte(pRight);
   55397   while( 1 ){
   55398     rc = getAndInitPage(pBt, pgno, &apOld[i]);
   55399     if( rc ){
   55400       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   55401       goto balance_cleanup;
   55402     }
   55403     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   55404     if( (i--)==0 ) break;
   55405 
   55406     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
   55407       apDiv[i] = pParent->apOvfl[0];
   55408       pgno = get4byte(apDiv[i]);
   55409       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   55410       pParent->nOverflow = 0;
   55411     }else{
   55412       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   55413       pgno = get4byte(apDiv[i]);
   55414       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   55415 
   55416       /* Drop the cell from the parent page. apDiv[i] still points to
   55417       ** the cell within the parent, even though it has been dropped.
   55418       ** This is safe because dropping a cell only overwrites the first
   55419       ** four bytes of it, and this function does not need the first
   55420       ** four bytes of the divider cell. So the pointer is safe to use
   55421       ** later on.
   55422       **
   55423       ** But not if we are in secure-delete mode. In secure-delete mode,
   55424       ** the dropCell() routine will overwrite the entire cell with zeroes.
   55425       ** In this case, temporarily copy the cell into the aOvflSpace[]
   55426       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   55427       ** is allocated.  */
   55428       if( pBt->btsFlags & BTS_SECURE_DELETE ){
   55429         int iOff;
   55430 
   55431         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   55432         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   55433           rc = SQLITE_CORRUPT_BKPT;
   55434           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   55435           goto balance_cleanup;
   55436         }else{
   55437           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   55438           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   55439         }
   55440       }
   55441       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   55442     }
   55443   }
   55444 
   55445   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   55446   ** alignment */
   55447   nMaxCells = (nMaxCells + 3)&~3;
   55448 
   55449   /*
   55450   ** Allocate space for memory structures
   55451   */
   55452   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   55453   szScratch =
   55454        nMaxCells*sizeof(u8*)                       /* apCell */
   55455      + nMaxCells*sizeof(u16)                       /* szCell */
   55456      + pBt->pageSize                               /* aSpace1 */
   55457      + k*nOld;                                     /* Page copies (apCopy) */
   55458   apCell = sqlite3ScratchMalloc( szScratch );
   55459   if( apCell==0 ){
   55460     rc = SQLITE_NOMEM;
   55461     goto balance_cleanup;
   55462   }
   55463   szCell = (u16*)&apCell[nMaxCells];
   55464   aSpace1 = (u8*)&szCell[nMaxCells];
   55465   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   55466 
   55467   /*
   55468   ** Load pointers to all cells on sibling pages and the divider cells
   55469   ** into the local apCell[] array.  Make copies of the divider cells
   55470   ** into space obtained from aSpace1[] and remove the the divider Cells
   55471   ** from pParent.
   55472   **
   55473   ** If the siblings are on leaf pages, then the child pointers of the
   55474   ** divider cells are stripped from the cells before they are copied
   55475   ** into aSpace1[].  In this way, all cells in apCell[] are without
   55476   ** child pointers.  If siblings are not leaves, then all cell in
   55477   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   55478   ** are alike.
   55479   **
   55480   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   55481   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   55482   */
   55483   leafCorrection = apOld[0]->leaf*4;
   55484   leafData = apOld[0]->hasData;
   55485   for(i=0; i<nOld; i++){
   55486     int limit;
   55487 
   55488     /* Before doing anything else, take a copy of the i'th original sibling
   55489     ** The rest of this function will use data from the copies rather
   55490     ** that the original pages since the original pages will be in the
   55491     ** process of being overwritten.  */
   55492     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   55493     memcpy(pOld, apOld[i], sizeof(MemPage));
   55494     pOld->aData = (void*)&pOld[1];
   55495     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   55496 
   55497     limit = pOld->nCell+pOld->nOverflow;
   55498     if( pOld->nOverflow>0 ){
   55499       for(j=0; j<limit; j++){
   55500         assert( nCell<nMaxCells );
   55501         apCell[nCell] = findOverflowCell(pOld, j);
   55502         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   55503         nCell++;
   55504       }
   55505     }else{
   55506       u8 *aData = pOld->aData;
   55507       u16 maskPage = pOld->maskPage;
   55508       u16 cellOffset = pOld->cellOffset;
   55509       for(j=0; j<limit; j++){
   55510         assert( nCell<nMaxCells );
   55511         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
   55512         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   55513         nCell++;
   55514       }
   55515     }
   55516     if( i<nOld-1 && !leafData){
   55517       u16 sz = (u16)szNew[i];
   55518       u8 *pTemp;
   55519       assert( nCell<nMaxCells );
   55520       szCell[nCell] = sz;
   55521       pTemp = &aSpace1[iSpace1];
   55522       iSpace1 += sz;
   55523       assert( sz<=pBt->maxLocal+23 );
   55524       assert( iSpace1 <= (int)pBt->pageSize );
   55525       memcpy(pTemp, apDiv[i], sz);
   55526       apCell[nCell] = pTemp+leafCorrection;
   55527       assert( leafCorrection==0 || leafCorrection==4 );
   55528       szCell[nCell] = szCell[nCell] - leafCorrection;
   55529       if( !pOld->leaf ){
   55530         assert( leafCorrection==0 );
   55531         assert( pOld->hdrOffset==0 );
   55532         /* The right pointer of the child page pOld becomes the left
   55533         ** pointer of the divider cell */
   55534         memcpy(apCell[nCell], &pOld->aData[8], 4);
   55535       }else{
   55536         assert( leafCorrection==4 );
   55537         if( szCell[nCell]<4 ){
   55538           /* Do not allow any cells smaller than 4 bytes. */
   55539           szCell[nCell] = 4;
   55540         }
   55541       }
   55542       nCell++;
   55543     }
   55544   }
   55545 
   55546   /*
   55547   ** Figure out the number of pages needed to hold all nCell cells.
   55548   ** Store this number in "k".  Also compute szNew[] which is the total
   55549   ** size of all cells on the i-th page and cntNew[] which is the index
   55550   ** in apCell[] of the cell that divides page i from page i+1.
   55551   ** cntNew[k] should equal nCell.
   55552   **
   55553   ** Values computed by this block:
   55554   **
   55555   **           k: The total number of sibling pages
   55556   **    szNew[i]: Spaced used on the i-th sibling page.
   55557   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   55558   **              the right of the i-th sibling page.
   55559   ** usableSpace: Number of bytes of space available on each sibling.
   55560   **
   55561   */
   55562   usableSpace = pBt->usableSize - 12 + leafCorrection;
   55563   for(subtotal=k=i=0; i<nCell; i++){
   55564     assert( i<nMaxCells );
   55565     subtotal += szCell[i] + 2;
   55566     if( subtotal > usableSpace ){
   55567       szNew[k] = subtotal - szCell[i];
   55568       cntNew[k] = i;
   55569       if( leafData ){ i--; }
   55570       subtotal = 0;
   55571       k++;
   55572       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   55573     }
   55574   }
   55575   szNew[k] = subtotal;
   55576   cntNew[k] = nCell;
   55577   k++;
   55578 
   55579   /*
   55580   ** The packing computed by the previous block is biased toward the siblings
   55581   ** on the left side.  The left siblings are always nearly full, while the
   55582   ** right-most sibling might be nearly empty.  This block of code attempts
   55583   ** to adjust the packing of siblings to get a better balance.
   55584   **
   55585   ** This adjustment is more than an optimization.  The packing above might
   55586   ** be so out of balance as to be illegal.  For example, the right-most
   55587   ** sibling might be completely empty.  This adjustment is not optional.
   55588   */
   55589   for(i=k-1; i>0; i--){
   55590     int szRight = szNew[i];  /* Size of sibling on the right */
   55591     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   55592     int r;              /* Index of right-most cell in left sibling */
   55593     int d;              /* Index of first cell to the left of right sibling */
   55594 
   55595     r = cntNew[i-1] - 1;
   55596     d = r + 1 - leafData;
   55597     assert( d<nMaxCells );
   55598     assert( r<nMaxCells );
   55599     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
   55600       szRight += szCell[d] + 2;
   55601       szLeft -= szCell[r] + 2;
   55602       cntNew[i-1]--;
   55603       r = cntNew[i-1] - 1;
   55604       d = r + 1 - leafData;
   55605     }
   55606     szNew[i] = szRight;
   55607     szNew[i-1] = szLeft;
   55608   }
   55609 
   55610   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   55611   ** a virtual root page.  A virtual root page is when the real root
   55612   ** page is page 1 and we are the only child of that page.
   55613   **
   55614   ** UPDATE:  The assert() below is not necessarily true if the database
   55615   ** file is corrupt.  The corruption will be detected and reported later
   55616   ** in this procedure so there is no need to act upon it now.
   55617   */
   55618 #if 0
   55619   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   55620 #endif
   55621 
   55622   TRACE(("BALANCE: old: %d %d %d  ",
   55623     apOld[0]->pgno,
   55624     nOld>=2 ? apOld[1]->pgno : 0,
   55625     nOld>=3 ? apOld[2]->pgno : 0
   55626   ));
   55627 
   55628   /*
   55629   ** Allocate k new pages.  Reuse old pages where possible.
   55630   */
   55631   if( apOld[0]->pgno<=1 ){
   55632     rc = SQLITE_CORRUPT_BKPT;
   55633     goto balance_cleanup;
   55634   }
   55635   pageFlags = apOld[0]->aData[0];
   55636   for(i=0; i<k; i++){
   55637     MemPage *pNew;
   55638     if( i<nOld ){
   55639       pNew = apNew[i] = apOld[i];
   55640       apOld[i] = 0;
   55641       rc = sqlite3PagerWrite(pNew->pDbPage);
   55642       nNew++;
   55643       if( rc ) goto balance_cleanup;
   55644     }else{
   55645       assert( i>0 );
   55646       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
   55647       if( rc ) goto balance_cleanup;
   55648       apNew[i] = pNew;
   55649       nNew++;
   55650 
   55651       /* Set the pointer-map entry for the new sibling page. */
   55652       if( ISAUTOVACUUM ){
   55653         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   55654         if( rc!=SQLITE_OK ){
   55655           goto balance_cleanup;
   55656         }
   55657       }
   55658     }
   55659   }
   55660 
   55661   /* Free any old pages that were not reused as new pages.
   55662   */
   55663   while( i<nOld ){
   55664     freePage(apOld[i], &rc);
   55665     if( rc ) goto balance_cleanup;
   55666     releasePage(apOld[i]);
   55667     apOld[i] = 0;
   55668     i++;
   55669   }
   55670 
   55671   /*
   55672   ** Put the new pages in accending order.  This helps to
   55673   ** keep entries in the disk file in order so that a scan
   55674   ** of the table is a linear scan through the file.  That
   55675   ** in turn helps the operating system to deliver pages
   55676   ** from the disk more rapidly.
   55677   **
   55678   ** An O(n^2) insertion sort algorithm is used, but since
   55679   ** n is never more than NB (a small constant), that should
   55680   ** not be a problem.
   55681   **
   55682   ** When NB==3, this one optimization makes the database
   55683   ** about 25% faster for large insertions and deletions.
   55684   */
   55685   for(i=0; i<k-1; i++){
   55686     int minV = apNew[i]->pgno;
   55687     int minI = i;
   55688     for(j=i+1; j<k; j++){
   55689       if( apNew[j]->pgno<(unsigned)minV ){
   55690         minI = j;
   55691         minV = apNew[j]->pgno;
   55692       }
   55693     }
   55694     if( minI>i ){
   55695       MemPage *pT;
   55696       pT = apNew[i];
   55697       apNew[i] = apNew[minI];
   55698       apNew[minI] = pT;
   55699     }
   55700   }
   55701   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   55702     apNew[0]->pgno, szNew[0],
   55703     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   55704     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   55705     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   55706     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   55707 
   55708   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55709   put4byte(pRight, apNew[nNew-1]->pgno);
   55710 
   55711   /*
   55712   ** Evenly distribute the data in apCell[] across the new pages.
   55713   ** Insert divider cells into pParent as necessary.
   55714   */
   55715   j = 0;
   55716   for(i=0; i<nNew; i++){
   55717     /* Assemble the new sibling page. */
   55718     MemPage *pNew = apNew[i];
   55719     assert( j<nMaxCells );
   55720     zeroPage(pNew, pageFlags);
   55721     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   55722     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   55723     assert( pNew->nOverflow==0 );
   55724 
   55725     j = cntNew[i];
   55726 
   55727     /* If the sibling page assembled above was not the right-most sibling,
   55728     ** insert a divider cell into the parent page.
   55729     */
   55730     assert( i<nNew-1 || j==nCell );
   55731     if( j<nCell ){
   55732       u8 *pCell;
   55733       u8 *pTemp;
   55734       int sz;
   55735 
   55736       assert( j<nMaxCells );
   55737       pCell = apCell[j];
   55738       sz = szCell[j] + leafCorrection;
   55739       pTemp = &aOvflSpace[iOvflSpace];
   55740       if( !pNew->leaf ){
   55741         memcpy(&pNew->aData[8], pCell, 4);
   55742       }else if( leafData ){
   55743         /* If the tree is a leaf-data tree, and the siblings are leaves,
   55744         ** then there is no divider cell in apCell[]. Instead, the divider
   55745         ** cell consists of the integer key for the right-most cell of
   55746         ** the sibling-page assembled above only.
   55747         */
   55748         CellInfo info;
   55749         j--;
   55750         btreeParseCellPtr(pNew, apCell[j], &info);
   55751         pCell = pTemp;
   55752         sz = 4 + putVarint(&pCell[4], info.nKey);
   55753         pTemp = 0;
   55754       }else{
   55755         pCell -= 4;
   55756         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   55757         ** previously stored on a leaf node, and its reported size was 4
   55758         ** bytes, then it may actually be smaller than this
   55759         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   55760         ** any cell). But it is important to pass the correct size to
   55761         ** insertCell(), so reparse the cell now.
   55762         **
   55763         ** Note that this can never happen in an SQLite data file, as all
   55764         ** cells are at least 4 bytes. It only happens in b-trees used
   55765         ** to evaluate "IN (SELECT ...)" and similar clauses.
   55766         */
   55767         if( szCell[j]==4 ){
   55768           assert(leafCorrection==4);
   55769           sz = cellSizePtr(pParent, pCell);
   55770         }
   55771       }
   55772       iOvflSpace += sz;
   55773       assert( sz<=pBt->maxLocal+23 );
   55774       assert( iOvflSpace <= (int)pBt->pageSize );
   55775       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   55776       if( rc!=SQLITE_OK ) goto balance_cleanup;
   55777       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55778 
   55779       j++;
   55780       nxDiv++;
   55781     }
   55782   }
   55783   assert( j==nCell );
   55784   assert( nOld>0 );
   55785   assert( nNew>0 );
   55786   if( (pageFlags & PTF_LEAF)==0 ){
   55787     u8 *zChild = &apCopy[nOld-1]->aData[8];
   55788     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   55789   }
   55790 
   55791   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   55792     /* The root page of the b-tree now contains no cells. The only sibling
   55793     ** page is the right-child of the parent. Copy the contents of the
   55794     ** child page into the parent, decreasing the overall height of the
   55795     ** b-tree structure by one. This is described as the "balance-shallower"
   55796     ** sub-algorithm in some documentation.
   55797     **
   55798     ** If this is an auto-vacuum database, the call to copyNodeContent()
   55799     ** sets all pointer-map entries corresponding to database image pages
   55800     ** for which the pointer is stored within the content being copied.
   55801     **
   55802     ** The second assert below verifies that the child page is defragmented
   55803     ** (it must be, as it was just reconstructed using assemblePage()). This
   55804     ** is important if the parent page happens to be page 1 of the database
   55805     ** image.  */
   55806     assert( nNew==1 );
   55807     assert( apNew[0]->nFree ==
   55808         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   55809     );
   55810     copyNodeContent(apNew[0], pParent, &rc);
   55811     freePage(apNew[0], &rc);
   55812   }else if( ISAUTOVACUUM ){
   55813     /* Fix the pointer-map entries for all the cells that were shifted around.
   55814     ** There are several different types of pointer-map entries that need to
   55815     ** be dealt with by this routine. Some of these have been set already, but
   55816     ** many have not. The following is a summary:
   55817     **
   55818     **   1) The entries associated with new sibling pages that were not
   55819     **      siblings when this function was called. These have already
   55820     **      been set. We don't need to worry about old siblings that were
   55821     **      moved to the free-list - the freePage() code has taken care
   55822     **      of those.
   55823     **
   55824     **   2) The pointer-map entries associated with the first overflow
   55825     **      page in any overflow chains used by new divider cells. These
   55826     **      have also already been taken care of by the insertCell() code.
   55827     **
   55828     **   3) If the sibling pages are not leaves, then the child pages of
   55829     **      cells stored on the sibling pages may need to be updated.
   55830     **
   55831     **   4) If the sibling pages are not internal intkey nodes, then any
   55832     **      overflow pages used by these cells may need to be updated
   55833     **      (internal intkey nodes never contain pointers to overflow pages).
   55834     **
   55835     **   5) If the sibling pages are not leaves, then the pointer-map
   55836     **      entries for the right-child pages of each sibling may need
   55837     **      to be updated.
   55838     **
   55839     ** Cases 1 and 2 are dealt with above by other code. The next
   55840     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   55841     ** setting a pointer map entry is a relatively expensive operation, this
   55842     ** code only sets pointer map entries for child or overflow pages that have
   55843     ** actually moved between pages.  */
   55844     MemPage *pNew = apNew[0];
   55845     MemPage *pOld = apCopy[0];
   55846     int nOverflow = pOld->nOverflow;
   55847     int iNextOld = pOld->nCell + nOverflow;
   55848     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
   55849     j = 0;                             /* Current 'old' sibling page */
   55850     k = 0;                             /* Current 'new' sibling page */
   55851     for(i=0; i<nCell; i++){
   55852       int isDivider = 0;
   55853       while( i==iNextOld ){
   55854         /* Cell i is the cell immediately following the last cell on old
   55855         ** sibling page j. If the siblings are not leaf pages of an
   55856         ** intkey b-tree, then cell i was a divider cell. */
   55857         assert( j+1 < ArraySize(apCopy) );
   55858         pOld = apCopy[++j];
   55859         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   55860         if( pOld->nOverflow ){
   55861           nOverflow = pOld->nOverflow;
   55862           iOverflow = i + !leafData + pOld->aiOvfl[0];
   55863         }
   55864         isDivider = !leafData;
   55865       }
   55866 
   55867       assert(nOverflow>0 || iOverflow<i );
   55868       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
   55869       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
   55870       if( i==iOverflow ){
   55871         isDivider = 1;
   55872         if( (--nOverflow)>0 ){
   55873           iOverflow++;
   55874         }
   55875       }
   55876 
   55877       if( i==cntNew[k] ){
   55878         /* Cell i is the cell immediately following the last cell on new
   55879         ** sibling page k. If the siblings are not leaf pages of an
   55880         ** intkey b-tree, then cell i is a divider cell.  */
   55881         pNew = apNew[++k];
   55882         if( !leafData ) continue;
   55883       }
   55884       assert( j<nOld );
   55885       assert( k<nNew );
   55886 
   55887       /* If the cell was originally divider cell (and is not now) or
   55888       ** an overflow cell, or if the cell was located on a different sibling
   55889       ** page before the balancing, then the pointer map entries associated
   55890       ** with any child or overflow pages need to be updated.  */
   55891       if( isDivider || pOld->pgno!=pNew->pgno ){
   55892         if( !leafCorrection ){
   55893           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   55894         }
   55895         if( szCell[i]>pNew->minLocal ){
   55896           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   55897         }
   55898       }
   55899     }
   55900 
   55901     if( !leafCorrection ){
   55902       for(i=0; i<nNew; i++){
   55903         u32 key = get4byte(&apNew[i]->aData[8]);
   55904         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   55905       }
   55906     }
   55907 
   55908 #if 0
   55909     /* The ptrmapCheckPages() contains assert() statements that verify that
   55910     ** all pointer map pages are set correctly. This is helpful while
   55911     ** debugging. This is usually disabled because a corrupt database may
   55912     ** cause an assert() statement to fail.  */
   55913     ptrmapCheckPages(apNew, nNew);
   55914     ptrmapCheckPages(&pParent, 1);
   55915 #endif
   55916   }
   55917 
   55918   assert( pParent->isInit );
   55919   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   55920           nOld, nNew, nCell));
   55921 
   55922   /*
   55923   ** Cleanup before returning.
   55924   */
   55925 balance_cleanup:
   55926   sqlite3ScratchFree(apCell);
   55927   for(i=0; i<nOld; i++){
   55928     releasePage(apOld[i]);
   55929   }
   55930   for(i=0; i<nNew; i++){
   55931     releasePage(apNew[i]);
   55932   }
   55933 
   55934   return rc;
   55935 }
   55936 
   55937 
   55938 /*
   55939 ** This function is called when the root page of a b-tree structure is
   55940 ** overfull (has one or more overflow pages).
   55941 **
   55942 ** A new child page is allocated and the contents of the current root
   55943 ** page, including overflow cells, are copied into the child. The root
   55944 ** page is then overwritten to make it an empty page with the right-child
   55945 ** pointer pointing to the new page.
   55946 **
   55947 ** Before returning, all pointer-map entries corresponding to pages
   55948 ** that the new child-page now contains pointers to are updated. The
   55949 ** entry corresponding to the new right-child pointer of the root
   55950 ** page is also updated.
   55951 **
   55952 ** If successful, *ppChild is set to contain a reference to the child
   55953 ** page and SQLITE_OK is returned. In this case the caller is required
   55954 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   55955 ** an error code is returned and *ppChild is set to 0.
   55956 */
   55957 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   55958   int rc;                        /* Return value from subprocedures */
   55959   MemPage *pChild = 0;           /* Pointer to a new child page */
   55960   Pgno pgnoChild = 0;            /* Page number of the new child page */
   55961   BtShared *pBt = pRoot->pBt;    /* The BTree */
   55962 
   55963   assert( pRoot->nOverflow>0 );
   55964   assert( sqlite3_mutex_held(pBt->mutex) );
   55965 
   55966   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   55967   ** page that will become the new right-child of pPage. Copy the contents
   55968   ** of the node stored on pRoot into the new child page.
   55969   */
   55970   rc = sqlite3PagerWrite(pRoot->pDbPage);
   55971   if( rc==SQLITE_OK ){
   55972     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   55973     copyNodeContent(pRoot, pChild, &rc);
   55974     if( ISAUTOVACUUM ){
   55975       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   55976     }
   55977   }
   55978   if( rc ){
   55979     *ppChild = 0;
   55980     releasePage(pChild);
   55981     return rc;
   55982   }
   55983   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   55984   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   55985   assert( pChild->nCell==pRoot->nCell );
   55986 
   55987   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   55988 
   55989   /* Copy the overflow cells from pRoot to pChild */
   55990   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
   55991          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
   55992   memcpy(pChild->apOvfl, pRoot->apOvfl,
   55993          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
   55994   pChild->nOverflow = pRoot->nOverflow;
   55995 
   55996   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   55997   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   55998   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   55999 
   56000   *ppChild = pChild;
   56001   return SQLITE_OK;
   56002 }
   56003 
   56004 /*
   56005 ** The page that pCur currently points to has just been modified in
   56006 ** some way. This function figures out if this modification means the
   56007 ** tree needs to be balanced, and if so calls the appropriate balancing
   56008 ** routine. Balancing routines are:
   56009 **
   56010 **   balance_quick()
   56011 **   balance_deeper()
   56012 **   balance_nonroot()
   56013 */
   56014 static int balance(BtCursor *pCur){
   56015   int rc = SQLITE_OK;
   56016   const int nMin = pCur->pBt->usableSize * 2 / 3;
   56017   u8 aBalanceQuickSpace[13];
   56018   u8 *pFree = 0;
   56019 
   56020   TESTONLY( int balance_quick_called = 0 );
   56021   TESTONLY( int balance_deeper_called = 0 );
   56022 
   56023   do {
   56024     int iPage = pCur->iPage;
   56025     MemPage *pPage = pCur->apPage[iPage];
   56026 
   56027     if( iPage==0 ){
   56028       if( pPage->nOverflow ){
   56029         /* The root page of the b-tree is overfull. In this case call the
   56030         ** balance_deeper() function to create a new child for the root-page
   56031         ** and copy the current contents of the root-page to it. The
   56032         ** next iteration of the do-loop will balance the child page.
   56033         */
   56034         assert( (balance_deeper_called++)==0 );
   56035         rc = balance_deeper(pPage, &pCur->apPage[1]);
   56036         if( rc==SQLITE_OK ){
   56037           pCur->iPage = 1;
   56038           pCur->aiIdx[0] = 0;
   56039           pCur->aiIdx[1] = 0;
   56040           assert( pCur->apPage[1]->nOverflow );
   56041         }
   56042       }else{
   56043         break;
   56044       }
   56045     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   56046       break;
   56047     }else{
   56048       MemPage * const pParent = pCur->apPage[iPage-1];
   56049       int const iIdx = pCur->aiIdx[iPage-1];
   56050 
   56051       rc = sqlite3PagerWrite(pParent->pDbPage);
   56052       if( rc==SQLITE_OK ){
   56053 #ifndef SQLITE_OMIT_QUICKBALANCE
   56054         if( pPage->hasData
   56055          && pPage->nOverflow==1
   56056          && pPage->aiOvfl[0]==pPage->nCell
   56057          && pParent->pgno!=1
   56058          && pParent->nCell==iIdx
   56059         ){
   56060           /* Call balance_quick() to create a new sibling of pPage on which
   56061           ** to store the overflow cell. balance_quick() inserts a new cell
   56062           ** into pParent, which may cause pParent overflow. If this
   56063           ** happens, the next interation of the do-loop will balance pParent
   56064           ** use either balance_nonroot() or balance_deeper(). Until this
   56065           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   56066           ** buffer.
   56067           **
   56068           ** The purpose of the following assert() is to check that only a
   56069           ** single call to balance_quick() is made for each call to this
   56070           ** function. If this were not verified, a subtle bug involving reuse
   56071           ** of the aBalanceQuickSpace[] might sneak in.
   56072           */
   56073           assert( (balance_quick_called++)==0 );
   56074           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   56075         }else
   56076 #endif
   56077         {
   56078           /* In this case, call balance_nonroot() to redistribute cells
   56079           ** between pPage and up to 2 of its sibling pages. This involves
   56080           ** modifying the contents of pParent, which may cause pParent to
   56081           ** become overfull or underfull. The next iteration of the do-loop
   56082           ** will balance the parent page to correct this.
   56083           **
   56084           ** If the parent page becomes overfull, the overflow cell or cells
   56085           ** are stored in the pSpace buffer allocated immediately below.
   56086           ** A subsequent iteration of the do-loop will deal with this by
   56087           ** calling balance_nonroot() (balance_deeper() may be called first,
   56088           ** but it doesn't deal with overflow cells - just moves them to a
   56089           ** different page). Once this subsequent call to balance_nonroot()
   56090           ** has completed, it is safe to release the pSpace buffer used by
   56091           ** the previous call, as the overflow cell data will have been
   56092           ** copied either into the body of a database page or into the new
   56093           ** pSpace buffer passed to the latter call to balance_nonroot().
   56094           */
   56095           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   56096           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
   56097           if( pFree ){
   56098             /* If pFree is not NULL, it points to the pSpace buffer used
   56099             ** by a previous call to balance_nonroot(). Its contents are
   56100             ** now stored either on real database pages or within the
   56101             ** new pSpace buffer, so it may be safely freed here. */
   56102             sqlite3PageFree(pFree);
   56103           }
   56104 
   56105           /* The pSpace buffer will be freed after the next call to
   56106           ** balance_nonroot(), or just before this function returns, whichever
   56107           ** comes first. */
   56108           pFree = pSpace;
   56109         }
   56110       }
   56111 
   56112       pPage->nOverflow = 0;
   56113 
   56114       /* The next iteration of the do-loop balances the parent page. */
   56115       releasePage(pPage);
   56116       pCur->iPage--;
   56117     }
   56118   }while( rc==SQLITE_OK );
   56119 
   56120   if( pFree ){
   56121     sqlite3PageFree(pFree);
   56122   }
   56123   return rc;
   56124 }
   56125 
   56126 
   56127 /*
   56128 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   56129 ** and the data is given by (pData,nData).  The cursor is used only to
   56130 ** define what table the record should be inserted into.  The cursor
   56131 ** is left pointing at a random location.
   56132 **
   56133 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   56134 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   56135 **
   56136 ** If the seekResult parameter is non-zero, then a successful call to
   56137 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   56138 ** been performed. seekResult is the search result returned (a negative
   56139 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   56140 ** a positive value if pCur points at an etry that is larger than
   56141 ** (pKey, nKey)).
   56142 **
   56143 ** If the seekResult parameter is non-zero, then the caller guarantees that
   56144 ** cursor pCur is pointing at the existing copy of a row that is to be
   56145 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   56146 ** point to any entry or to no entry at all and so this function has to seek
   56147 ** the cursor before the new key can be inserted.
   56148 */
   56149 SQLITE_PRIVATE int sqlite3BtreeInsert(
   56150   BtCursor *pCur,                /* Insert data into the table of this cursor */
   56151   const void *pKey, i64 nKey,    /* The key of the new record */
   56152   const void *pData, int nData,  /* The data of the new record */
   56153   int nZero,                     /* Number of extra 0 bytes to append to data */
   56154   int appendBias,                /* True if this is likely an append */
   56155   int seekResult                 /* Result of prior MovetoUnpacked() call */
   56156 ){
   56157   int rc;
   56158   int loc = seekResult;          /* -1: before desired location  +1: after */
   56159   int szNew = 0;
   56160   int idx;
   56161   MemPage *pPage;
   56162   Btree *p = pCur->pBtree;
   56163   BtShared *pBt = p->pBt;
   56164   unsigned char *oldCell;
   56165   unsigned char *newCell = 0;
   56166 
   56167   if( pCur->eState==CURSOR_FAULT ){
   56168     assert( pCur->skipNext!=SQLITE_OK );
   56169     return pCur->skipNext;
   56170   }
   56171 
   56172   assert( cursorHoldsMutex(pCur) );
   56173   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
   56174               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56175   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   56176 
   56177   /* Assert that the caller has been consistent. If this cursor was opened
   56178   ** expecting an index b-tree, then the caller should be inserting blob
   56179   ** keys with no associated data. If the cursor was opened expecting an
   56180   ** intkey table, the caller should be inserting integer keys with a
   56181   ** blob of associated data.  */
   56182   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   56183 
   56184   /* If this is an insert into a table b-tree, invalidate any incrblob
   56185   ** cursors open on the row being replaced (assuming this is a replace
   56186   ** operation - if it is not, the following is a no-op).  */
   56187   if( pCur->pKeyInfo==0 ){
   56188     invalidateIncrblobCursors(p, nKey, 0);
   56189   }
   56190 
   56191   /* Save the positions of any other cursors open on this table.
   56192   **
   56193   ** In some cases, the call to btreeMoveto() below is a no-op. For
   56194   ** example, when inserting data into a table with auto-generated integer
   56195   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   56196   ** integer key to use. It then calls this function to actually insert the
   56197   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   56198   ** that the cursor is already where it needs to be and returns without
   56199   ** doing any work. To avoid thwarting these optimizations, it is important
   56200   ** not to clear the cursor here.
   56201   */
   56202   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   56203   if( rc ) return rc;
   56204   if( !loc ){
   56205     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   56206     if( rc ) return rc;
   56207   }
   56208   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   56209 
   56210   pPage = pCur->apPage[pCur->iPage];
   56211   assert( pPage->intKey || nKey>=0 );
   56212   assert( pPage->leaf || !pPage->intKey );
   56213 
   56214   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   56215           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   56216           loc==0 ? "overwrite" : "new entry"));
   56217   assert( pPage->isInit );
   56218   allocateTempSpace(pBt);
   56219   newCell = pBt->pTmpSpace;
   56220   if( newCell==0 ) return SQLITE_NOMEM;
   56221   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   56222   if( rc ) goto end_insert;
   56223   assert( szNew==cellSizePtr(pPage, newCell) );
   56224   assert( szNew <= MX_CELL_SIZE(pBt) );
   56225   idx = pCur->aiIdx[pCur->iPage];
   56226   if( loc==0 ){
   56227     u16 szOld;
   56228     assert( idx<pPage->nCell );
   56229     rc = sqlite3PagerWrite(pPage->pDbPage);
   56230     if( rc ){
   56231       goto end_insert;
   56232     }
   56233     oldCell = findCell(pPage, idx);
   56234     if( !pPage->leaf ){
   56235       memcpy(newCell, oldCell, 4);
   56236     }
   56237     szOld = cellSizePtr(pPage, oldCell);
   56238     rc = clearCell(pPage, oldCell);
   56239     dropCell(pPage, idx, szOld, &rc);
   56240     if( rc ) goto end_insert;
   56241   }else if( loc<0 && pPage->nCell>0 ){
   56242     assert( pPage->leaf );
   56243     idx = ++pCur->aiIdx[pCur->iPage];
   56244   }else{
   56245     assert( pPage->leaf );
   56246   }
   56247   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   56248   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   56249 
   56250   /* If no error has occured and pPage has an overflow cell, call balance()
   56251   ** to redistribute the cells within the tree. Since balance() may move
   56252   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
   56253   ** variables.
   56254   **
   56255   ** Previous versions of SQLite called moveToRoot() to move the cursor
   56256   ** back to the root page as balance() used to invalidate the contents
   56257   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   56258   ** set the cursor state to "invalid". This makes common insert operations
   56259   ** slightly faster.
   56260   **
   56261   ** There is a subtle but important optimization here too. When inserting
   56262   ** multiple records into an intkey b-tree using a single cursor (as can
   56263   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   56264   ** is advantageous to leave the cursor pointing to the last entry in
   56265   ** the b-tree if possible. If the cursor is left pointing to the last
   56266   ** entry in the table, and the next row inserted has an integer key
   56267   ** larger than the largest existing key, it is possible to insert the
   56268   ** row without seeking the cursor. This can be a big performance boost.
   56269   */
   56270   pCur->info.nSize = 0;
   56271   pCur->validNKey = 0;
   56272   if( rc==SQLITE_OK && pPage->nOverflow ){
   56273     rc = balance(pCur);
   56274 
   56275     /* Must make sure nOverflow is reset to zero even if the balance()
   56276     ** fails. Internal data structure corruption will result otherwise.
   56277     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   56278     ** from trying to save the current position of the cursor.  */
   56279     pCur->apPage[pCur->iPage]->nOverflow = 0;
   56280     pCur->eState = CURSOR_INVALID;
   56281   }
   56282   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   56283 
   56284 end_insert:
   56285   return rc;
   56286 }
   56287 
   56288 /*
   56289 ** Delete the entry that the cursor is pointing to.  The cursor
   56290 ** is left pointing at a arbitrary location.
   56291 */
   56292 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   56293   Btree *p = pCur->pBtree;
   56294   BtShared *pBt = p->pBt;
   56295   int rc;                              /* Return code */
   56296   MemPage *pPage;                      /* Page to delete cell from */
   56297   unsigned char *pCell;                /* Pointer to cell to delete */
   56298   int iCellIdx;                        /* Index of cell to delete */
   56299   int iCellDepth;                      /* Depth of node containing pCell */
   56300 
   56301   assert( cursorHoldsMutex(pCur) );
   56302   assert( pBt->inTransaction==TRANS_WRITE );
   56303   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56304   assert( pCur->wrFlag );
   56305   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   56306   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   56307 
   56308   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   56309    || NEVER(pCur->eState!=CURSOR_VALID)
   56310   ){
   56311     return SQLITE_ERROR;  /* Something has gone awry. */
   56312   }
   56313 
   56314   /* If this is a delete operation to remove a row from a table b-tree,
   56315   ** invalidate any incrblob cursors open on the row being deleted.  */
   56316   if( pCur->pKeyInfo==0 ){
   56317     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   56318   }
   56319 
   56320   iCellDepth = pCur->iPage;
   56321   iCellIdx = pCur->aiIdx[iCellDepth];
   56322   pPage = pCur->apPage[iCellDepth];
   56323   pCell = findCell(pPage, iCellIdx);
   56324 
   56325   /* If the page containing the entry to delete is not a leaf page, move
   56326   ** the cursor to the largest entry in the tree that is smaller than
   56327   ** the entry being deleted. This cell will replace the cell being deleted
   56328   ** from the internal node. The 'previous' entry is used for this instead
   56329   ** of the 'next' entry, as the previous entry is always a part of the
   56330   ** sub-tree headed by the child page of the cell being deleted. This makes
   56331   ** balancing the tree following the delete operation easier.  */
   56332   if( !pPage->leaf ){
   56333     int notUsed;
   56334     rc = sqlite3BtreePrevious(pCur, &notUsed);
   56335     if( rc ) return rc;
   56336   }
   56337 
   56338   /* Save the positions of any other cursors open on this table before
   56339   ** making any modifications. Make the page containing the entry to be
   56340   ** deleted writable. Then free any overflow pages associated with the
   56341   ** entry and finally remove the cell itself from within the page.
   56342   */
   56343   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   56344   if( rc ) return rc;
   56345   rc = sqlite3PagerWrite(pPage->pDbPage);
   56346   if( rc ) return rc;
   56347   rc = clearCell(pPage, pCell);
   56348   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   56349   if( rc ) return rc;
   56350 
   56351   /* If the cell deleted was not located on a leaf page, then the cursor
   56352   ** is currently pointing to the largest entry in the sub-tree headed
   56353   ** by the child-page of the cell that was just deleted from an internal
   56354   ** node. The cell from the leaf node needs to be moved to the internal
   56355   ** node to replace the deleted cell.  */
   56356   if( !pPage->leaf ){
   56357     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   56358     int nCell;
   56359     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   56360     unsigned char *pTmp;
   56361 
   56362     pCell = findCell(pLeaf, pLeaf->nCell-1);
   56363     nCell = cellSizePtr(pLeaf, pCell);
   56364     assert( MX_CELL_SIZE(pBt) >= nCell );
   56365 
   56366     allocateTempSpace(pBt);
   56367     pTmp = pBt->pTmpSpace;
   56368 
   56369     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   56370     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   56371     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   56372     if( rc ) return rc;
   56373   }
   56374 
   56375   /* Balance the tree. If the entry deleted was located on a leaf page,
   56376   ** then the cursor still points to that page. In this case the first
   56377   ** call to balance() repairs the tree, and the if(...) condition is
   56378   ** never true.
   56379   **
   56380   ** Otherwise, if the entry deleted was on an internal node page, then
   56381   ** pCur is pointing to the leaf page from which a cell was removed to
   56382   ** replace the cell deleted from the internal node. This is slightly
   56383   ** tricky as the leaf node may be underfull, and the internal node may
   56384   ** be either under or overfull. In this case run the balancing algorithm
   56385   ** on the leaf node first. If the balance proceeds far enough up the
   56386   ** tree that we can be sure that any problem in the internal node has
   56387   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   56388   ** walk the cursor up the tree to the internal node and balance it as
   56389   ** well.  */
   56390   rc = balance(pCur);
   56391   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   56392     while( pCur->iPage>iCellDepth ){
   56393       releasePage(pCur->apPage[pCur->iPage--]);
   56394     }
   56395     rc = balance(pCur);
   56396   }
   56397 
   56398   if( rc==SQLITE_OK ){
   56399     moveToRoot(pCur);
   56400   }
   56401   return rc;
   56402 }
   56403 
   56404 /*
   56405 ** Create a new BTree table.  Write into *piTable the page
   56406 ** number for the root page of the new table.
   56407 **
   56408 ** The type of type is determined by the flags parameter.  Only the
   56409 ** following values of flags are currently in use.  Other values for
   56410 ** flags might not work:
   56411 **
   56412 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   56413 **     BTREE_ZERODATA                  Used for SQL indices
   56414 */
   56415 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   56416   BtShared *pBt = p->pBt;
   56417   MemPage *pRoot;
   56418   Pgno pgnoRoot;
   56419   int rc;
   56420   int ptfFlags;          /* Page-type flage for the root page of new table */
   56421 
   56422   assert( sqlite3BtreeHoldsMutex(p) );
   56423   assert( pBt->inTransaction==TRANS_WRITE );
   56424   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56425 
   56426 #ifdef SQLITE_OMIT_AUTOVACUUM
   56427   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   56428   if( rc ){
   56429     return rc;
   56430   }
   56431 #else
   56432   if( pBt->autoVacuum ){
   56433     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   56434     MemPage *pPageMove; /* The page to move to. */
   56435 
   56436     /* Creating a new table may probably require moving an existing database
   56437     ** to make room for the new tables root page. In case this page turns
   56438     ** out to be an overflow page, delete all overflow page-map caches
   56439     ** held by open cursors.
   56440     */
   56441     invalidateAllOverflowCache(pBt);
   56442 
   56443     /* Read the value of meta[3] from the database to determine where the
   56444     ** root page of the new table should go. meta[3] is the largest root-page
   56445     ** created so far, so the new root-page is (meta[3]+1).
   56446     */
   56447     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   56448     pgnoRoot++;
   56449 
   56450     /* The new root-page may not be allocated on a pointer-map page, or the
   56451     ** PENDING_BYTE page.
   56452     */
   56453     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   56454         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   56455       pgnoRoot++;
   56456     }
   56457     assert( pgnoRoot>=3 );
   56458 
   56459     /* Allocate a page. The page that currently resides at pgnoRoot will
   56460     ** be moved to the allocated page (unless the allocated page happens
   56461     ** to reside at pgnoRoot).
   56462     */
   56463     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
   56464     if( rc!=SQLITE_OK ){
   56465       return rc;
   56466     }
   56467 
   56468     if( pgnoMove!=pgnoRoot ){
   56469       /* pgnoRoot is the page that will be used for the root-page of
   56470       ** the new table (assuming an error did not occur). But we were
   56471       ** allocated pgnoMove. If required (i.e. if it was not allocated
   56472       ** by extending the file), the current page at position pgnoMove
   56473       ** is already journaled.
   56474       */
   56475       u8 eType = 0;
   56476       Pgno iPtrPage = 0;
   56477 
   56478       releasePage(pPageMove);
   56479 
   56480       /* Move the page currently at pgnoRoot to pgnoMove. */
   56481       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   56482       if( rc!=SQLITE_OK ){
   56483         return rc;
   56484       }
   56485       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   56486       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   56487         rc = SQLITE_CORRUPT_BKPT;
   56488       }
   56489       if( rc!=SQLITE_OK ){
   56490         releasePage(pRoot);
   56491         return rc;
   56492       }
   56493       assert( eType!=PTRMAP_ROOTPAGE );
   56494       assert( eType!=PTRMAP_FREEPAGE );
   56495       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   56496       releasePage(pRoot);
   56497 
   56498       /* Obtain the page at pgnoRoot */
   56499       if( rc!=SQLITE_OK ){
   56500         return rc;
   56501       }
   56502       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   56503       if( rc!=SQLITE_OK ){
   56504         return rc;
   56505       }
   56506       rc = sqlite3PagerWrite(pRoot->pDbPage);
   56507       if( rc!=SQLITE_OK ){
   56508         releasePage(pRoot);
   56509         return rc;
   56510       }
   56511     }else{
   56512       pRoot = pPageMove;
   56513     }
   56514 
   56515     /* Update the pointer-map and meta-data with the new root-page number. */
   56516     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   56517     if( rc ){
   56518       releasePage(pRoot);
   56519       return rc;
   56520     }
   56521 
   56522     /* When the new root page was allocated, page 1 was made writable in
   56523     ** order either to increase the database filesize, or to decrement the
   56524     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   56525     */
   56526     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   56527     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   56528     if( NEVER(rc) ){
   56529       releasePage(pRoot);
   56530       return rc;
   56531     }
   56532 
   56533   }else{
   56534     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   56535     if( rc ) return rc;
   56536   }
   56537 #endif
   56538   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   56539   if( createTabFlags & BTREE_INTKEY ){
   56540     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   56541   }else{
   56542     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   56543   }
   56544   zeroPage(pRoot, ptfFlags);
   56545   sqlite3PagerUnref(pRoot->pDbPage);
   56546   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   56547   *piTable = (int)pgnoRoot;
   56548   return SQLITE_OK;
   56549 }
   56550 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   56551   int rc;
   56552   sqlite3BtreeEnter(p);
   56553   rc = btreeCreateTable(p, piTable, flags);
   56554   sqlite3BtreeLeave(p);
   56555   return rc;
   56556 }
   56557 
   56558 /*
   56559 ** Erase the given database page and all its children.  Return
   56560 ** the page to the freelist.
   56561 */
   56562 static int clearDatabasePage(
   56563   BtShared *pBt,           /* The BTree that contains the table */
   56564   Pgno pgno,               /* Page number to clear */
   56565   int freePageFlag,        /* Deallocate page if true */
   56566   int *pnChange            /* Add number of Cells freed to this counter */
   56567 ){
   56568   MemPage *pPage;
   56569   int rc;
   56570   unsigned char *pCell;
   56571   int i;
   56572 
   56573   assert( sqlite3_mutex_held(pBt->mutex) );
   56574   if( pgno>btreePagecount(pBt) ){
   56575     return SQLITE_CORRUPT_BKPT;
   56576   }
   56577 
   56578   rc = getAndInitPage(pBt, pgno, &pPage);
   56579   if( rc ) return rc;
   56580   for(i=0; i<pPage->nCell; i++){
   56581     pCell = findCell(pPage, i);
   56582     if( !pPage->leaf ){
   56583       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   56584       if( rc ) goto cleardatabasepage_out;
   56585     }
   56586     rc = clearCell(pPage, pCell);
   56587     if( rc ) goto cleardatabasepage_out;
   56588   }
   56589   if( !pPage->leaf ){
   56590     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
   56591     if( rc ) goto cleardatabasepage_out;
   56592   }else if( pnChange ){
   56593     assert( pPage->intKey );
   56594     *pnChange += pPage->nCell;
   56595   }
   56596   if( freePageFlag ){
   56597     freePage(pPage, &rc);
   56598   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   56599     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
   56600   }
   56601 
   56602 cleardatabasepage_out:
   56603   releasePage(pPage);
   56604   return rc;
   56605 }
   56606 
   56607 /*
   56608 ** Delete all information from a single table in the database.  iTable is
   56609 ** the page number of the root of the table.  After this routine returns,
   56610 ** the root page is empty, but still exists.
   56611 **
   56612 ** This routine will fail with SQLITE_LOCKED if there are any open
   56613 ** read cursors on the table.  Open write cursors are moved to the
   56614 ** root of the table.
   56615 **
   56616 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   56617 ** integer value pointed to by pnChange is incremented by the number of
   56618 ** entries in the table.
   56619 */
   56620 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   56621   int rc;
   56622   BtShared *pBt = p->pBt;
   56623   sqlite3BtreeEnter(p);
   56624   assert( p->inTrans==TRANS_WRITE );
   56625 
   56626   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   56627   ** is the root of a table b-tree - if it is not, the following call is
   56628   ** a no-op).  */
   56629   invalidateIncrblobCursors(p, 0, 1);
   56630 
   56631   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   56632   if( SQLITE_OK==rc ){
   56633     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   56634   }
   56635   sqlite3BtreeLeave(p);
   56636   return rc;
   56637 }
   56638 
   56639 /*
   56640 ** Erase all information in a table and add the root of the table to
   56641 ** the freelist.  Except, the root of the principle table (the one on
   56642 ** page 1) is never added to the freelist.
   56643 **
   56644 ** This routine will fail with SQLITE_LOCKED if there are any open
   56645 ** cursors on the table.
   56646 **
   56647 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   56648 ** root page in the database file, then the last root page
   56649 ** in the database file is moved into the slot formerly occupied by
   56650 ** iTable and that last slot formerly occupied by the last root page
   56651 ** is added to the freelist instead of iTable.  In this say, all
   56652 ** root pages are kept at the beginning of the database file, which
   56653 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   56654 ** page number that used to be the last root page in the file before
   56655 ** the move.  If no page gets moved, *piMoved is set to 0.
   56656 ** The last root page is recorded in meta[3] and the value of
   56657 ** meta[3] is updated by this procedure.
   56658 */
   56659 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   56660   int rc;
   56661   MemPage *pPage = 0;
   56662   BtShared *pBt = p->pBt;
   56663 
   56664   assert( sqlite3BtreeHoldsMutex(p) );
   56665   assert( p->inTrans==TRANS_WRITE );
   56666 
   56667   /* It is illegal to drop a table if any cursors are open on the
   56668   ** database. This is because in auto-vacuum mode the backend may
   56669   ** need to move another root-page to fill a gap left by the deleted
   56670   ** root page. If an open cursor was using this page a problem would
   56671   ** occur.
   56672   **
   56673   ** This error is caught long before control reaches this point.
   56674   */
   56675   if( NEVER(pBt->pCursor) ){
   56676     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   56677     return SQLITE_LOCKED_SHAREDCACHE;
   56678   }
   56679 
   56680   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   56681   if( rc ) return rc;
   56682   rc = sqlite3BtreeClearTable(p, iTable, 0);
   56683   if( rc ){
   56684     releasePage(pPage);
   56685     return rc;
   56686   }
   56687 
   56688   *piMoved = 0;
   56689 
   56690   if( iTable>1 ){
   56691 #ifdef SQLITE_OMIT_AUTOVACUUM
   56692     freePage(pPage, &rc);
   56693     releasePage(pPage);
   56694 #else
   56695     if( pBt->autoVacuum ){
   56696       Pgno maxRootPgno;
   56697       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   56698 
   56699       if( iTable==maxRootPgno ){
   56700         /* If the table being dropped is the table with the largest root-page
   56701         ** number in the database, put the root page on the free list.
   56702         */
   56703         freePage(pPage, &rc);
   56704         releasePage(pPage);
   56705         if( rc!=SQLITE_OK ){
   56706           return rc;
   56707         }
   56708       }else{
   56709         /* The table being dropped does not have the largest root-page
   56710         ** number in the database. So move the page that does into the
   56711         ** gap left by the deleted root-page.
   56712         */
   56713         MemPage *pMove;
   56714         releasePage(pPage);
   56715         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   56716         if( rc!=SQLITE_OK ){
   56717           return rc;
   56718         }
   56719         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   56720         releasePage(pMove);
   56721         if( rc!=SQLITE_OK ){
   56722           return rc;
   56723         }
   56724         pMove = 0;
   56725         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   56726         freePage(pMove, &rc);
   56727         releasePage(pMove);
   56728         if( rc!=SQLITE_OK ){
   56729           return rc;
   56730         }
   56731         *piMoved = maxRootPgno;
   56732       }
   56733 
   56734       /* Set the new 'max-root-page' value in the database header. This
   56735       ** is the old value less one, less one more if that happens to
   56736       ** be a root-page number, less one again if that is the
   56737       ** PENDING_BYTE_PAGE.
   56738       */
   56739       maxRootPgno--;
   56740       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   56741              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   56742         maxRootPgno--;
   56743       }
   56744       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   56745 
   56746       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   56747     }else{
   56748       freePage(pPage, &rc);
   56749       releasePage(pPage);
   56750     }
   56751 #endif
   56752   }else{
   56753     /* If sqlite3BtreeDropTable was called on page 1.
   56754     ** This really never should happen except in a corrupt
   56755     ** database.
   56756     */
   56757     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   56758     releasePage(pPage);
   56759   }
   56760   return rc;
   56761 }
   56762 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   56763   int rc;
   56764   sqlite3BtreeEnter(p);
   56765   rc = btreeDropTable(p, iTable, piMoved);
   56766   sqlite3BtreeLeave(p);
   56767   return rc;
   56768 }
   56769 
   56770 
   56771 /*
   56772 ** This function may only be called if the b-tree connection already
   56773 ** has a read or write transaction open on the database.
   56774 **
   56775 ** Read the meta-information out of a database file.  Meta[0]
   56776 ** is the number of free pages currently in the database.  Meta[1]
   56777 ** through meta[15] are available for use by higher layers.  Meta[0]
   56778 ** is read-only, the others are read/write.
   56779 **
   56780 ** The schema layer numbers meta values differently.  At the schema
   56781 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   56782 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   56783 */
   56784 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   56785   BtShared *pBt = p->pBt;
   56786 
   56787   sqlite3BtreeEnter(p);
   56788   assert( p->inTrans>TRANS_NONE );
   56789   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   56790   assert( pBt->pPage1 );
   56791   assert( idx>=0 && idx<=15 );
   56792 
   56793   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   56794 
   56795   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   56796   ** database, mark the database as read-only.  */
   56797 #ifdef SQLITE_OMIT_AUTOVACUUM
   56798   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
   56799     pBt->btsFlags |= BTS_READ_ONLY;
   56800   }
   56801 #endif
   56802 
   56803   sqlite3BtreeLeave(p);
   56804 }
   56805 
   56806 /*
   56807 ** Write meta-information back into the database.  Meta[0] is
   56808 ** read-only and may not be written.
   56809 */
   56810 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   56811   BtShared *pBt = p->pBt;
   56812   unsigned char *pP1;
   56813   int rc;
   56814   assert( idx>=1 && idx<=15 );
   56815   sqlite3BtreeEnter(p);
   56816   assert( p->inTrans==TRANS_WRITE );
   56817   assert( pBt->pPage1!=0 );
   56818   pP1 = pBt->pPage1->aData;
   56819   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   56820   if( rc==SQLITE_OK ){
   56821     put4byte(&pP1[36 + idx*4], iMeta);
   56822 #ifndef SQLITE_OMIT_AUTOVACUUM
   56823     if( idx==BTREE_INCR_VACUUM ){
   56824       assert( pBt->autoVacuum || iMeta==0 );
   56825       assert( iMeta==0 || iMeta==1 );
   56826       pBt->incrVacuum = (u8)iMeta;
   56827     }
   56828 #endif
   56829   }
   56830   sqlite3BtreeLeave(p);
   56831   return rc;
   56832 }
   56833 
   56834 #ifndef SQLITE_OMIT_BTREECOUNT
   56835 /*
   56836 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   56837 ** number of entries in the b-tree and write the result to *pnEntry.
   56838 **
   56839 ** SQLITE_OK is returned if the operation is successfully executed.
   56840 ** Otherwise, if an error is encountered (i.e. an IO error or database
   56841 ** corruption) an SQLite error code is returned.
   56842 */
   56843 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   56844   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   56845   int rc;                              /* Return code */
   56846 
   56847   if( pCur->pgnoRoot==0 ){
   56848     *pnEntry = 0;
   56849     return SQLITE_OK;
   56850   }
   56851   rc = moveToRoot(pCur);
   56852 
   56853   /* Unless an error occurs, the following loop runs one iteration for each
   56854   ** page in the B-Tree structure (not including overflow pages).
   56855   */
   56856   while( rc==SQLITE_OK ){
   56857     int iIdx;                          /* Index of child node in parent */
   56858     MemPage *pPage;                    /* Current page of the b-tree */
   56859 
   56860     /* If this is a leaf page or the tree is not an int-key tree, then
   56861     ** this page contains countable entries. Increment the entry counter
   56862     ** accordingly.
   56863     */
   56864     pPage = pCur->apPage[pCur->iPage];
   56865     if( pPage->leaf || !pPage->intKey ){
   56866       nEntry += pPage->nCell;
   56867     }
   56868 
   56869     /* pPage is a leaf node. This loop navigates the cursor so that it
   56870     ** points to the first interior cell that it points to the parent of
   56871     ** the next page in the tree that has not yet been visited. The
   56872     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   56873     ** of the page, or to the number of cells in the page if the next page
   56874     ** to visit is the right-child of its parent.
   56875     **
   56876     ** If all pages in the tree have been visited, return SQLITE_OK to the
   56877     ** caller.
   56878     */
   56879     if( pPage->leaf ){
   56880       do {
   56881         if( pCur->iPage==0 ){
   56882           /* All pages of the b-tree have been visited. Return successfully. */
   56883           *pnEntry = nEntry;
   56884           return SQLITE_OK;
   56885         }
   56886         moveToParent(pCur);
   56887       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   56888 
   56889       pCur->aiIdx[pCur->iPage]++;
   56890       pPage = pCur->apPage[pCur->iPage];
   56891     }
   56892 
   56893     /* Descend to the child node of the cell that the cursor currently
   56894     ** points at. This is the right-child if (iIdx==pPage->nCell).
   56895     */
   56896     iIdx = pCur->aiIdx[pCur->iPage];
   56897     if( iIdx==pPage->nCell ){
   56898       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   56899     }else{
   56900       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   56901     }
   56902   }
   56903 
   56904   /* An error has occurred. Return an error code. */
   56905   return rc;
   56906 }
   56907 #endif
   56908 
   56909 /*
   56910 ** Return the pager associated with a BTree.  This routine is used for
   56911 ** testing and debugging only.
   56912 */
   56913 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   56914   return p->pBt->pPager;
   56915 }
   56916 
   56917 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   56918 /*
   56919 ** Append a message to the error message string.
   56920 */
   56921 static void checkAppendMsg(
   56922   IntegrityCk *pCheck,
   56923   char *zMsg1,
   56924   const char *zFormat,
   56925   ...
   56926 ){
   56927   va_list ap;
   56928   if( !pCheck->mxErr ) return;
   56929   pCheck->mxErr--;
   56930   pCheck->nErr++;
   56931   va_start(ap, zFormat);
   56932   if( pCheck->errMsg.nChar ){
   56933     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   56934   }
   56935   if( zMsg1 ){
   56936     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
   56937   }
   56938   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   56939   va_end(ap);
   56940   if( pCheck->errMsg.mallocFailed ){
   56941     pCheck->mallocFailed = 1;
   56942   }
   56943 }
   56944 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   56945 
   56946 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   56947 /*
   56948 ** Add 1 to the reference count for page iPage.  If this is the second
   56949 ** reference to the page, add an error message to pCheck->zErrMsg.
   56950 ** Return 1 if there are 2 ore more references to the page and 0 if
   56951 ** if this is the first reference to the page.
   56952 **
   56953 ** Also check that the page number is in bounds.
   56954 */
   56955 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   56956   if( iPage==0 ) return 1;
   56957   if( iPage>pCheck->nPage ){
   56958     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   56959     return 1;
   56960   }
   56961   if( pCheck->anRef[iPage]==1 ){
   56962     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   56963     return 1;
   56964   }
   56965   return  (pCheck->anRef[iPage]++)>1;
   56966 }
   56967 
   56968 #ifndef SQLITE_OMIT_AUTOVACUUM
   56969 /*
   56970 ** Check that the entry in the pointer-map for page iChild maps to
   56971 ** page iParent, pointer type ptrType. If not, append an error message
   56972 ** to pCheck.
   56973 */
   56974 static void checkPtrmap(
   56975   IntegrityCk *pCheck,   /* Integrity check context */
   56976   Pgno iChild,           /* Child page number */
   56977   u8 eType,              /* Expected pointer map type */
   56978   Pgno iParent,          /* Expected pointer map parent page number */
   56979   char *zContext         /* Context description (used for error msg) */
   56980 ){
   56981   int rc;
   56982   u8 ePtrmapType;
   56983   Pgno iPtrmapParent;
   56984 
   56985   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   56986   if( rc!=SQLITE_OK ){
   56987     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   56988     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   56989     return;
   56990   }
   56991 
   56992   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   56993     checkAppendMsg(pCheck, zContext,
   56994       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   56995       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   56996   }
   56997 }
   56998 #endif
   56999 
   57000 /*
   57001 ** Check the integrity of the freelist or of an overflow page list.
   57002 ** Verify that the number of pages on the list is N.
   57003 */
   57004 static void checkList(
   57005   IntegrityCk *pCheck,  /* Integrity checking context */
   57006   int isFreeList,       /* True for a freelist.  False for overflow page list */
   57007   int iPage,            /* Page number for first page in the list */
   57008   int N,                /* Expected number of pages in the list */
   57009   char *zContext        /* Context for error messages */
   57010 ){
   57011   int i;
   57012   int expected = N;
   57013   int iFirst = iPage;
   57014   while( N-- > 0 && pCheck->mxErr ){
   57015     DbPage *pOvflPage;
   57016     unsigned char *pOvflData;
   57017     if( iPage<1 ){
   57018       checkAppendMsg(pCheck, zContext,
   57019          "%d of %d pages missing from overflow list starting at %d",
   57020           N+1, expected, iFirst);
   57021       break;
   57022     }
   57023     if( checkRef(pCheck, iPage, zContext) ) break;
   57024     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   57025       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   57026       break;
   57027     }
   57028     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   57029     if( isFreeList ){
   57030       int n = get4byte(&pOvflData[4]);
   57031 #ifndef SQLITE_OMIT_AUTOVACUUM
   57032       if( pCheck->pBt->autoVacuum ){
   57033         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   57034       }
   57035 #endif
   57036       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   57037         checkAppendMsg(pCheck, zContext,
   57038            "freelist leaf count too big on page %d", iPage);
   57039         N--;
   57040       }else{
   57041         for(i=0; i<n; i++){
   57042           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   57043 #ifndef SQLITE_OMIT_AUTOVACUUM
   57044           if( pCheck->pBt->autoVacuum ){
   57045             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   57046           }
   57047 #endif
   57048           checkRef(pCheck, iFreePage, zContext);
   57049         }
   57050         N -= n;
   57051       }
   57052     }
   57053 #ifndef SQLITE_OMIT_AUTOVACUUM
   57054     else{
   57055       /* If this database supports auto-vacuum and iPage is not the last
   57056       ** page in this overflow list, check that the pointer-map entry for
   57057       ** the following page matches iPage.
   57058       */
   57059       if( pCheck->pBt->autoVacuum && N>0 ){
   57060         i = get4byte(pOvflData);
   57061         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   57062       }
   57063     }
   57064 #endif
   57065     iPage = get4byte(pOvflData);
   57066     sqlite3PagerUnref(pOvflPage);
   57067   }
   57068 }
   57069 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57070 
   57071 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   57072 /*
   57073 ** Do various sanity checks on a single page of a tree.  Return
   57074 ** the tree depth.  Root pages return 0.  Parents of root pages
   57075 ** return 1, and so forth.
   57076 **
   57077 ** These checks are done:
   57078 **
   57079 **      1.  Make sure that cells and freeblocks do not overlap
   57080 **          but combine to completely cover the page.
   57081 **  NO  2.  Make sure cell keys are in order.
   57082 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   57083 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   57084 **      5.  Check the integrity of overflow pages.
   57085 **      6.  Recursively call checkTreePage on all children.
   57086 **      7.  Verify that the depth of all children is the same.
   57087 **      8.  Make sure this page is at least 33% full or else it is
   57088 **          the root of the tree.
   57089 */
   57090 static int checkTreePage(
   57091   IntegrityCk *pCheck,  /* Context for the sanity check */
   57092   int iPage,            /* Page number of the page to check */
   57093   char *zParentContext, /* Parent context */
   57094   i64 *pnParentMinKey,
   57095   i64 *pnParentMaxKey
   57096 ){
   57097   MemPage *pPage;
   57098   int i, rc, depth, d2, pgno, cnt;
   57099   int hdr, cellStart;
   57100   int nCell;
   57101   u8 *data;
   57102   BtShared *pBt;
   57103   int usableSize;
   57104   char zContext[100];
   57105   char *hit = 0;
   57106   i64 nMinKey = 0;
   57107   i64 nMaxKey = 0;
   57108 
   57109   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   57110 
   57111   /* Check that the page exists
   57112   */
   57113   pBt = pCheck->pBt;
   57114   usableSize = pBt->usableSize;
   57115   if( iPage==0 ) return 0;
   57116   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   57117   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   57118     checkAppendMsg(pCheck, zContext,
   57119        "unable to get the page. error code=%d", rc);
   57120     return 0;
   57121   }
   57122 
   57123   /* Clear MemPage.isInit to make sure the corruption detection code in
   57124   ** btreeInitPage() is executed.  */
   57125   pPage->isInit = 0;
   57126   if( (rc = btreeInitPage(pPage))!=0 ){
   57127     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   57128     checkAppendMsg(pCheck, zContext,
   57129                    "btreeInitPage() returns error code %d", rc);
   57130     releasePage(pPage);
   57131     return 0;
   57132   }
   57133 
   57134   /* Check out all the cells.
   57135   */
   57136   depth = 0;
   57137   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   57138     u8 *pCell;
   57139     u32 sz;
   57140     CellInfo info;
   57141 
   57142     /* Check payload overflow pages
   57143     */
   57144     sqlite3_snprintf(sizeof(zContext), zContext,
   57145              "On tree page %d cell %d: ", iPage, i);
   57146     pCell = findCell(pPage,i);
   57147     btreeParseCellPtr(pPage, pCell, &info);
   57148     sz = info.nData;
   57149     if( !pPage->intKey ) sz += (int)info.nKey;
   57150     /* For intKey pages, check that the keys are in order.
   57151     */
   57152     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   57153     else{
   57154       if( info.nKey <= nMaxKey ){
   57155         checkAppendMsg(pCheck, zContext,
   57156             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   57157       }
   57158       nMaxKey = info.nKey;
   57159     }
   57160     assert( sz==info.nPayload );
   57161     if( (sz>info.nLocal)
   57162      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   57163     ){
   57164       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   57165       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   57166 #ifndef SQLITE_OMIT_AUTOVACUUM
   57167       if( pBt->autoVacuum ){
   57168         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   57169       }
   57170 #endif
   57171       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   57172     }
   57173 
   57174     /* Check sanity of left child page.
   57175     */
   57176     if( !pPage->leaf ){
   57177       pgno = get4byte(pCell);
   57178 #ifndef SQLITE_OMIT_AUTOVACUUM
   57179       if( pBt->autoVacuum ){
   57180         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   57181       }
   57182 #endif
   57183       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   57184       if( i>0 && d2!=depth ){
   57185         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   57186       }
   57187       depth = d2;
   57188     }
   57189   }
   57190 
   57191   if( !pPage->leaf ){
   57192     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   57193     sqlite3_snprintf(sizeof(zContext), zContext,
   57194                      "On page %d at right child: ", iPage);
   57195 #ifndef SQLITE_OMIT_AUTOVACUUM
   57196     if( pBt->autoVacuum ){
   57197       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   57198     }
   57199 #endif
   57200     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   57201   }
   57202 
   57203   /* For intKey leaf pages, check that the min/max keys are in order
   57204   ** with any left/parent/right pages.
   57205   */
   57206   if( pPage->leaf && pPage->intKey ){
   57207     /* if we are a left child page */
   57208     if( pnParentMinKey ){
   57209       /* if we are the left most child page */
   57210       if( !pnParentMaxKey ){
   57211         if( nMaxKey > *pnParentMinKey ){
   57212           checkAppendMsg(pCheck, zContext,
   57213               "Rowid %lld out of order (max larger than parent min of %lld)",
   57214               nMaxKey, *pnParentMinKey);
   57215         }
   57216       }else{
   57217         if( nMinKey <= *pnParentMinKey ){
   57218           checkAppendMsg(pCheck, zContext,
   57219               "Rowid %lld out of order (min less than parent min of %lld)",
   57220               nMinKey, *pnParentMinKey);
   57221         }
   57222         if( nMaxKey > *pnParentMaxKey ){
   57223           checkAppendMsg(pCheck, zContext,
   57224               "Rowid %lld out of order (max larger than parent max of %lld)",
   57225               nMaxKey, *pnParentMaxKey);
   57226         }
   57227         *pnParentMinKey = nMaxKey;
   57228       }
   57229     /* else if we're a right child page */
   57230     } else if( pnParentMaxKey ){
   57231       if( nMinKey <= *pnParentMaxKey ){
   57232         checkAppendMsg(pCheck, zContext,
   57233             "Rowid %lld out of order (min less than parent max of %lld)",
   57234             nMinKey, *pnParentMaxKey);
   57235       }
   57236     }
   57237   }
   57238 
   57239   /* Check for complete coverage of the page
   57240   */
   57241   data = pPage->aData;
   57242   hdr = pPage->hdrOffset;
   57243   hit = sqlite3PageMalloc( pBt->pageSize );
   57244   if( hit==0 ){
   57245     pCheck->mallocFailed = 1;
   57246   }else{
   57247     int contentOffset = get2byteNotZero(&data[hdr+5]);
   57248     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   57249     memset(hit+contentOffset, 0, usableSize-contentOffset);
   57250     memset(hit, 1, contentOffset);
   57251     nCell = get2byte(&data[hdr+3]);
   57252     cellStart = hdr + 12 - 4*pPage->leaf;
   57253     for(i=0; i<nCell; i++){
   57254       int pc = get2byte(&data[cellStart+i*2]);
   57255       u32 size = 65536;
   57256       int j;
   57257       if( pc<=usableSize-4 ){
   57258         size = cellSizePtr(pPage, &data[pc]);
   57259       }
   57260       if( (int)(pc+size-1)>=usableSize ){
   57261         checkAppendMsg(pCheck, 0,
   57262             "Corruption detected in cell %d on page %d",i,iPage);
   57263       }else{
   57264         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   57265       }
   57266     }
   57267     i = get2byte(&data[hdr+1]);
   57268     while( i>0 ){
   57269       int size, j;
   57270       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   57271       size = get2byte(&data[i+2]);
   57272       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   57273       for(j=i+size-1; j>=i; j--) hit[j]++;
   57274       j = get2byte(&data[i]);
   57275       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   57276       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   57277       i = j;
   57278     }
   57279     for(i=cnt=0; i<usableSize; i++){
   57280       if( hit[i]==0 ){
   57281         cnt++;
   57282       }else if( hit[i]>1 ){
   57283         checkAppendMsg(pCheck, 0,
   57284           "Multiple uses for byte %d of page %d", i, iPage);
   57285         break;
   57286       }
   57287     }
   57288     if( cnt!=data[hdr+7] ){
   57289       checkAppendMsg(pCheck, 0,
   57290           "Fragmentation of %d bytes reported as %d on page %d",
   57291           cnt, data[hdr+7], iPage);
   57292     }
   57293   }
   57294   sqlite3PageFree(hit);
   57295   releasePage(pPage);
   57296   return depth+1;
   57297 }
   57298 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57299 
   57300 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   57301 /*
   57302 ** This routine does a complete check of the given BTree file.  aRoot[] is
   57303 ** an array of pages numbers were each page number is the root page of
   57304 ** a table.  nRoot is the number of entries in aRoot.
   57305 **
   57306 ** A read-only or read-write transaction must be opened before calling
   57307 ** this function.
   57308 **
   57309 ** Write the number of error seen in *pnErr.  Except for some memory
   57310 ** allocation errors,  an error message held in memory obtained from
   57311 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   57312 ** returned.  If a memory allocation error occurs, NULL is returned.
   57313 */
   57314 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   57315   Btree *p,     /* The btree to be checked */
   57316   int *aRoot,   /* An array of root pages numbers for individual trees */
   57317   int nRoot,    /* Number of entries in aRoot[] */
   57318   int mxErr,    /* Stop reporting errors after this many */
   57319   int *pnErr    /* Write number of errors seen to this variable */
   57320 ){
   57321   Pgno i;
   57322   int nRef;
   57323   IntegrityCk sCheck;
   57324   BtShared *pBt = p->pBt;
   57325   char zErr[100];
   57326 
   57327   sqlite3BtreeEnter(p);
   57328   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   57329   nRef = sqlite3PagerRefcount(pBt->pPager);
   57330   sCheck.pBt = pBt;
   57331   sCheck.pPager = pBt->pPager;
   57332   sCheck.nPage = btreePagecount(sCheck.pBt);
   57333   sCheck.mxErr = mxErr;
   57334   sCheck.nErr = 0;
   57335   sCheck.mallocFailed = 0;
   57336   *pnErr = 0;
   57337   if( sCheck.nPage==0 ){
   57338     sqlite3BtreeLeave(p);
   57339     return 0;
   57340   }
   57341   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
   57342   if( !sCheck.anRef ){
   57343     *pnErr = 1;
   57344     sqlite3BtreeLeave(p);
   57345     return 0;
   57346   }
   57347   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
   57348   i = PENDING_BYTE_PAGE(pBt);
   57349   if( i<=sCheck.nPage ){
   57350     sCheck.anRef[i] = 1;
   57351   }
   57352   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
   57353   sCheck.errMsg.useMalloc = 2;
   57354 
   57355   /* Check the integrity of the freelist
   57356   */
   57357   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   57358             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   57359 
   57360   /* Check all the tables.
   57361   */
   57362   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   57363     if( aRoot[i]==0 ) continue;
   57364 #ifndef SQLITE_OMIT_AUTOVACUUM
   57365     if( pBt->autoVacuum && aRoot[i]>1 ){
   57366       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   57367     }
   57368 #endif
   57369     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   57370   }
   57371 
   57372   /* Make sure every page in the file is referenced
   57373   */
   57374   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   57375 #ifdef SQLITE_OMIT_AUTOVACUUM
   57376     if( sCheck.anRef[i]==0 ){
   57377       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   57378     }
   57379 #else
   57380     /* If the database supports auto-vacuum, make sure no tables contain
   57381     ** references to pointer-map pages.
   57382     */
   57383     if( sCheck.anRef[i]==0 &&
   57384        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   57385       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   57386     }
   57387     if( sCheck.anRef[i]!=0 &&
   57388        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   57389       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   57390     }
   57391 #endif
   57392   }
   57393 
   57394   /* Make sure this analysis did not leave any unref() pages.
   57395   ** This is an internal consistency check; an integrity check
   57396   ** of the integrity check.
   57397   */
   57398   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   57399     checkAppendMsg(&sCheck, 0,
   57400       "Outstanding page count goes from %d to %d during this analysis",
   57401       nRef, sqlite3PagerRefcount(pBt->pPager)
   57402     );
   57403   }
   57404 
   57405   /* Clean  up and report errors.
   57406   */
   57407   sqlite3BtreeLeave(p);
   57408   sqlite3_free(sCheck.anRef);
   57409   if( sCheck.mallocFailed ){
   57410     sqlite3StrAccumReset(&sCheck.errMsg);
   57411     *pnErr = sCheck.nErr+1;
   57412     return 0;
   57413   }
   57414   *pnErr = sCheck.nErr;
   57415   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   57416   return sqlite3StrAccumFinish(&sCheck.errMsg);
   57417 }
   57418 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57419 
   57420 /*
   57421 ** Return the full pathname of the underlying database file.
   57422 **
   57423 ** The pager filename is invariant as long as the pager is
   57424 ** open so it is safe to access without the BtShared mutex.
   57425 */
   57426 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   57427   assert( p->pBt->pPager!=0 );
   57428   return sqlite3PagerFilename(p->pBt->pPager);
   57429 }
   57430 
   57431 /*
   57432 ** Return the pathname of the journal file for this database. The return
   57433 ** value of this routine is the same regardless of whether the journal file
   57434 ** has been created or not.
   57435 **
   57436 ** The pager journal filename is invariant as long as the pager is
   57437 ** open so it is safe to access without the BtShared mutex.
   57438 */
   57439 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   57440   assert( p->pBt->pPager!=0 );
   57441   return sqlite3PagerJournalname(p->pBt->pPager);
   57442 }
   57443 
   57444 /*
   57445 ** Return non-zero if a transaction is active.
   57446 */
   57447 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   57448   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   57449   return (p && (p->inTrans==TRANS_WRITE));
   57450 }
   57451 
   57452 #ifndef SQLITE_OMIT_WAL
   57453 /*
   57454 ** Run a checkpoint on the Btree passed as the first argument.
   57455 **
   57456 ** Return SQLITE_LOCKED if this or any other connection has an open
   57457 ** transaction on the shared-cache the argument Btree is connected to.
   57458 **
   57459 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   57460 */
   57461 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
   57462   int rc = SQLITE_OK;
   57463   if( p ){
   57464     BtShared *pBt = p->pBt;
   57465     sqlite3BtreeEnter(p);
   57466     if( pBt->inTransaction!=TRANS_NONE ){
   57467       rc = SQLITE_LOCKED;
   57468     }else{
   57469       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
   57470     }
   57471     sqlite3BtreeLeave(p);
   57472   }
   57473   return rc;
   57474 }
   57475 #endif
   57476 
   57477 /*
   57478 ** Return non-zero if a read (or write) transaction is active.
   57479 */
   57480 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   57481   assert( p );
   57482   assert( sqlite3_mutex_held(p->db->mutex) );
   57483   return p->inTrans!=TRANS_NONE;
   57484 }
   57485 
   57486 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   57487   assert( p );
   57488   assert( sqlite3_mutex_held(p->db->mutex) );
   57489   return p->nBackup!=0;
   57490 }
   57491 
   57492 /*
   57493 ** This function returns a pointer to a blob of memory associated with
   57494 ** a single shared-btree. The memory is used by client code for its own
   57495 ** purposes (for example, to store a high-level schema associated with
   57496 ** the shared-btree). The btree layer manages reference counting issues.
   57497 **
   57498 ** The first time this is called on a shared-btree, nBytes bytes of memory
   57499 ** are allocated, zeroed, and returned to the caller. For each subsequent
   57500 ** call the nBytes parameter is ignored and a pointer to the same blob
   57501 ** of memory returned.
   57502 **
   57503 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   57504 ** allocated, a null pointer is returned. If the blob has already been
   57505 ** allocated, it is returned as normal.
   57506 **
   57507 ** Just before the shared-btree is closed, the function passed as the
   57508 ** xFree argument when the memory allocation was made is invoked on the
   57509 ** blob of allocated memory. The xFree function should not call sqlite3_free()
   57510 ** on the memory, the btree layer does that.
   57511 */
   57512 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   57513   BtShared *pBt = p->pBt;
   57514   sqlite3BtreeEnter(p);
   57515   if( !pBt->pSchema && nBytes ){
   57516     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   57517     pBt->xFreeSchema = xFree;
   57518   }
   57519   sqlite3BtreeLeave(p);
   57520   return pBt->pSchema;
   57521 }
   57522 
   57523 /*
   57524 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   57525 ** btree as the argument handle holds an exclusive lock on the
   57526 ** sqlite_master table. Otherwise SQLITE_OK.
   57527 */
   57528 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   57529   int rc;
   57530   assert( sqlite3_mutex_held(p->db->mutex) );
   57531   sqlite3BtreeEnter(p);
   57532   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   57533   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   57534   sqlite3BtreeLeave(p);
   57535   return rc;
   57536 }
   57537 
   57538 
   57539 #ifndef SQLITE_OMIT_SHARED_CACHE
   57540 /*
   57541 ** Obtain a lock on the table whose root page is iTab.  The
   57542 ** lock is a write lock if isWritelock is true or a read lock
   57543 ** if it is false.
   57544 */
   57545 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   57546   int rc = SQLITE_OK;
   57547   assert( p->inTrans!=TRANS_NONE );
   57548   if( p->sharable ){
   57549     u8 lockType = READ_LOCK + isWriteLock;
   57550     assert( READ_LOCK+1==WRITE_LOCK );
   57551     assert( isWriteLock==0 || isWriteLock==1 );
   57552 
   57553     sqlite3BtreeEnter(p);
   57554     rc = querySharedCacheTableLock(p, iTab, lockType);
   57555     if( rc==SQLITE_OK ){
   57556       rc = setSharedCacheTableLock(p, iTab, lockType);
   57557     }
   57558     sqlite3BtreeLeave(p);
   57559   }
   57560   return rc;
   57561 }
   57562 #endif
   57563 
   57564 #ifndef SQLITE_OMIT_INCRBLOB
   57565 /*
   57566 ** Argument pCsr must be a cursor opened for writing on an
   57567 ** INTKEY table currently pointing at a valid table entry.
   57568 ** This function modifies the data stored as part of that entry.
   57569 **
   57570 ** Only the data content may only be modified, it is not possible to
   57571 ** change the length of the data stored. If this function is called with
   57572 ** parameters that attempt to write past the end of the existing data,
   57573 ** no modifications are made and SQLITE_CORRUPT is returned.
   57574 */
   57575 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   57576   int rc;
   57577   assert( cursorHoldsMutex(pCsr) );
   57578   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   57579   assert( pCsr->isIncrblobHandle );
   57580 
   57581   rc = restoreCursorPosition(pCsr);
   57582   if( rc!=SQLITE_OK ){
   57583     return rc;
   57584   }
   57585   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   57586   if( pCsr->eState!=CURSOR_VALID ){
   57587     return SQLITE_ABORT;
   57588   }
   57589 
   57590   /* Check some assumptions:
   57591   **   (a) the cursor is open for writing,
   57592   **   (b) there is a read/write transaction open,
   57593   **   (c) the connection holds a write-lock on the table (if required),
   57594   **   (d) there are no conflicting read-locks, and
   57595   **   (e) the cursor points at a valid row of an intKey table.
   57596   */
   57597   if( !pCsr->wrFlag ){
   57598     return SQLITE_READONLY;
   57599   }
   57600   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
   57601               && pCsr->pBt->inTransaction==TRANS_WRITE );
   57602   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   57603   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   57604   assert( pCsr->apPage[pCsr->iPage]->intKey );
   57605 
   57606   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   57607 }
   57608 
   57609 /*
   57610 ** Set a flag on this cursor to cache the locations of pages from the
   57611 ** overflow list for the current row. This is used by cursors opened
   57612 ** for incremental blob IO only.
   57613 **
   57614 ** This function sets a flag only. The actual page location cache
   57615 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
   57616 ** accessPayload() (the worker function for sqlite3BtreeData() and
   57617 ** sqlite3BtreePutData()).
   57618 */
   57619 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
   57620   assert( cursorHoldsMutex(pCur) );
   57621   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   57622   invalidateOverflowCache(pCur);
   57623   pCur->isIncrblobHandle = 1;
   57624 }
   57625 #endif
   57626 
   57627 /*
   57628 ** Set both the "read version" (single byte at byte offset 18) and
   57629 ** "write version" (single byte at byte offset 19) fields in the database
   57630 ** header to iVersion.
   57631 */
   57632 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   57633   BtShared *pBt = pBtree->pBt;
   57634   int rc;                         /* Return code */
   57635 
   57636   assert( iVersion==1 || iVersion==2 );
   57637 
   57638   /* If setting the version fields to 1, do not automatically open the
   57639   ** WAL connection, even if the version fields are currently set to 2.
   57640   */
   57641   pBt->btsFlags &= ~BTS_NO_WAL;
   57642   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
   57643 
   57644   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   57645   if( rc==SQLITE_OK ){
   57646     u8 *aData = pBt->pPage1->aData;
   57647     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   57648       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   57649       if( rc==SQLITE_OK ){
   57650         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   57651         if( rc==SQLITE_OK ){
   57652           aData[18] = (u8)iVersion;
   57653           aData[19] = (u8)iVersion;
   57654         }
   57655       }
   57656     }
   57657   }
   57658 
   57659   pBt->btsFlags &= ~BTS_NO_WAL;
   57660   return rc;
   57661 }
   57662 
   57663 /************** End of btree.c ***********************************************/
   57664 /************** Begin file backup.c ******************************************/
   57665 /*
   57666 ** 2009 January 28
   57667 **
   57668 ** The author disclaims copyright to this source code.  In place of
   57669 ** a legal notice, here is a blessing:
   57670 **
   57671 **    May you do good and not evil.
   57672 **    May you find forgiveness for yourself and forgive others.
   57673 **    May you share freely, never taking more than you give.
   57674 **
   57675 *************************************************************************
   57676 ** This file contains the implementation of the sqlite3_backup_XXX()
   57677 ** API functions and the related features.
   57678 */
   57679 
   57680 /* Macro to find the minimum of two numeric values.
   57681 */
   57682 #ifndef MIN
   57683 # define MIN(x,y) ((x)<(y)?(x):(y))
   57684 #endif
   57685 
   57686 /*
   57687 ** Structure allocated for each backup operation.
   57688 */
   57689 struct sqlite3_backup {
   57690   sqlite3* pDestDb;        /* Destination database handle */
   57691   Btree *pDest;            /* Destination b-tree file */
   57692   u32 iDestSchema;         /* Original schema cookie in destination */
   57693   int bDestLocked;         /* True once a write-transaction is open on pDest */
   57694 
   57695   Pgno iNext;              /* Page number of the next source page to copy */
   57696   sqlite3* pSrcDb;         /* Source database handle */
   57697   Btree *pSrc;             /* Source b-tree file */
   57698 
   57699   int rc;                  /* Backup process error code */
   57700 
   57701   /* These two variables are set by every call to backup_step(). They are
   57702   ** read by calls to backup_remaining() and backup_pagecount().
   57703   */
   57704   Pgno nRemaining;         /* Number of pages left to copy */
   57705   Pgno nPagecount;         /* Total number of pages to copy */
   57706 
   57707   int isAttached;          /* True once backup has been registered with pager */
   57708   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   57709 };
   57710 
   57711 /*
   57712 ** THREAD SAFETY NOTES:
   57713 **
   57714 **   Once it has been created using backup_init(), a single sqlite3_backup
   57715 **   structure may be accessed via two groups of thread-safe entry points:
   57716 **
   57717 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   57718 **       backup_finish(). Both these functions obtain the source database
   57719 **       handle mutex and the mutex associated with the source BtShared
   57720 **       structure, in that order.
   57721 **
   57722 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   57723 **       invoked by the pager layer to report various state changes in
   57724 **       the page cache associated with the source database. The mutex
   57725 **       associated with the source database BtShared structure will always
   57726 **       be held when either of these functions are invoked.
   57727 **
   57728 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   57729 **   backup_pagecount() are not thread-safe functions. If they are called
   57730 **   while some other thread is calling backup_step() or backup_finish(),
   57731 **   the values returned may be invalid. There is no way for a call to
   57732 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   57733 **   or backup_pagecount().
   57734 **
   57735 **   Depending on the SQLite configuration, the database handles and/or
   57736 **   the Btree objects may have their own mutexes that require locking.
   57737 **   Non-sharable Btrees (in-memory databases for example), do not have
   57738 **   associated mutexes.
   57739 */
   57740 
   57741 /*
   57742 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   57743 ** in connection handle pDb. If such a database cannot be found, return
   57744 ** a NULL pointer and write an error message to pErrorDb.
   57745 **
   57746 ** If the "temp" database is requested, it may need to be opened by this
   57747 ** function. If an error occurs while doing so, return 0 and write an
   57748 ** error message to pErrorDb.
   57749 */
   57750 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   57751   int i = sqlite3FindDbName(pDb, zDb);
   57752 
   57753   if( i==1 ){
   57754     Parse *pParse;
   57755     int rc = 0;
   57756     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   57757     if( pParse==0 ){
   57758       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   57759       rc = SQLITE_NOMEM;
   57760     }else{
   57761       pParse->db = pDb;
   57762       if( sqlite3OpenTempDatabase(pParse) ){
   57763         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   57764         rc = SQLITE_ERROR;
   57765       }
   57766       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   57767       sqlite3StackFree(pErrorDb, pParse);
   57768     }
   57769     if( rc ){
   57770       return 0;
   57771     }
   57772   }
   57773 
   57774   if( i<0 ){
   57775     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   57776     return 0;
   57777   }
   57778 
   57779   return pDb->aDb[i].pBt;
   57780 }
   57781 
   57782 /*
   57783 ** Attempt to set the page size of the destination to match the page size
   57784 ** of the source.
   57785 */
   57786 static int setDestPgsz(sqlite3_backup *p){
   57787   int rc;
   57788   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
   57789   return rc;
   57790 }
   57791 
   57792 /*
   57793 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   57794 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   57795 ** a pointer to the new sqlite3_backup object.
   57796 **
   57797 ** If an error occurs, NULL is returned and an error code and error message
   57798 ** stored in database handle pDestDb.
   57799 */
   57800 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   57801   sqlite3* pDestDb,                     /* Database to write to */
   57802   const char *zDestDb,                  /* Name of database within pDestDb */
   57803   sqlite3* pSrcDb,                      /* Database connection to read from */
   57804   const char *zSrcDb                    /* Name of database within pSrcDb */
   57805 ){
   57806   sqlite3_backup *p;                    /* Value to return */
   57807 
   57808   /* Lock the source database handle. The destination database
   57809   ** handle is not locked in this routine, but it is locked in
   57810   ** sqlite3_backup_step(). The user is required to ensure that no
   57811   ** other thread accesses the destination handle for the duration
   57812   ** of the backup operation.  Any attempt to use the destination
   57813   ** database connection while a backup is in progress may cause
   57814   ** a malfunction or a deadlock.
   57815   */
   57816   sqlite3_mutex_enter(pSrcDb->mutex);
   57817   sqlite3_mutex_enter(pDestDb->mutex);
   57818 
   57819   if( pSrcDb==pDestDb ){
   57820     sqlite3Error(
   57821         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   57822     );
   57823     p = 0;
   57824   }else {
   57825     /* Allocate space for a new sqlite3_backup object...
   57826     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   57827     ** call to sqlite3_backup_init() and is destroyed by a call to
   57828     ** sqlite3_backup_finish(). */
   57829     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
   57830     if( !p ){
   57831       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   57832     }
   57833   }
   57834 
   57835   /* If the allocation succeeded, populate the new object. */
   57836   if( p ){
   57837     memset(p, 0, sizeof(sqlite3_backup));
   57838     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   57839     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   57840     p->pDestDb = pDestDb;
   57841     p->pSrcDb = pSrcDb;
   57842     p->iNext = 1;
   57843     p->isAttached = 0;
   57844 
   57845     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
   57846       /* One (or both) of the named databases did not exist or an OOM
   57847       ** error was hit.  The error has already been written into the
   57848       ** pDestDb handle.  All that is left to do here is free the
   57849       ** sqlite3_backup structure.
   57850       */
   57851       sqlite3_free(p);
   57852       p = 0;
   57853     }
   57854   }
   57855   if( p ){
   57856     p->pSrc->nBackup++;
   57857   }
   57858 
   57859   sqlite3_mutex_leave(pDestDb->mutex);
   57860   sqlite3_mutex_leave(pSrcDb->mutex);
   57861   return p;
   57862 }
   57863 
   57864 /*
   57865 ** Argument rc is an SQLite error code. Return true if this error is
   57866 ** considered fatal if encountered during a backup operation. All errors
   57867 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   57868 */
   57869 static int isFatalError(int rc){
   57870   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   57871 }
   57872 
   57873 /*
   57874 ** Parameter zSrcData points to a buffer containing the data for
   57875 ** page iSrcPg from the source database. Copy this data into the
   57876 ** destination database.
   57877 */
   57878 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
   57879   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   57880   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   57881   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   57882   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   57883   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   57884 #ifdef SQLITE_HAS_CODEC
   57885   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
   57886   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
   57887 #endif
   57888 
   57889   int rc = SQLITE_OK;
   57890   i64 iOff;
   57891 
   57892   assert( p->bDestLocked );
   57893   assert( !isFatalError(p->rc) );
   57894   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   57895   assert( zSrcData );
   57896 
   57897   /* Catch the case where the destination is an in-memory database and the
   57898   ** page sizes of the source and destination differ.
   57899   */
   57900   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   57901     rc = SQLITE_READONLY;
   57902   }
   57903 
   57904 #ifdef SQLITE_HAS_CODEC
   57905   /* Backup is not possible if the page size of the destination is changing
   57906   ** and a codec is in use.
   57907   */
   57908   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   57909     rc = SQLITE_READONLY;
   57910   }
   57911 
   57912   /* Backup is not possible if the number of bytes of reserve space differ
   57913   ** between source and destination.  If there is a difference, try to
   57914   ** fix the destination to agree with the source.  If that is not possible,
   57915   ** then the backup cannot proceed.
   57916   */
   57917   if( nSrcReserve!=nDestReserve ){
   57918     u32 newPgsz = nSrcPgsz;
   57919     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
   57920     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
   57921   }
   57922 #endif
   57923 
   57924   /* This loop runs once for each destination page spanned by the source
   57925   ** page. For each iteration, variable iOff is set to the byte offset
   57926   ** of the destination page.
   57927   */
   57928   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   57929     DbPage *pDestPg = 0;
   57930     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   57931     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   57932     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   57933      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   57934     ){
   57935       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   57936       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   57937       u8 *zOut = &zDestData[iOff%nDestPgsz];
   57938 
   57939       /* Copy the data from the source page into the destination page.
   57940       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   57941       ** and the pager code use this trick (clearing the first byte
   57942       ** of the page 'extra' space to invalidate the Btree layers
   57943       ** cached parse of the page). MemPage.isInit is marked
   57944       ** "MUST BE FIRST" for this purpose.
   57945       */
   57946       memcpy(zOut, zIn, nCopy);
   57947       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   57948     }
   57949     sqlite3PagerUnref(pDestPg);
   57950   }
   57951 
   57952   return rc;
   57953 }
   57954 
   57955 /*
   57956 ** If pFile is currently larger than iSize bytes, then truncate it to
   57957 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   57958 ** this function is a no-op.
   57959 **
   57960 ** Return SQLITE_OK if everything is successful, or an SQLite error
   57961 ** code if an error occurs.
   57962 */
   57963 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   57964   i64 iCurrent;
   57965   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   57966   if( rc==SQLITE_OK && iCurrent>iSize ){
   57967     rc = sqlite3OsTruncate(pFile, iSize);
   57968   }
   57969   return rc;
   57970 }
   57971 
   57972 /*
   57973 ** Register this backup object with the associated source pager for
   57974 ** callbacks when pages are changed or the cache invalidated.
   57975 */
   57976 static void attachBackupObject(sqlite3_backup *p){
   57977   sqlite3_backup **pp;
   57978   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   57979   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   57980   p->pNext = *pp;
   57981   *pp = p;
   57982   p->isAttached = 1;
   57983 }
   57984 
   57985 /*
   57986 ** Copy nPage pages from the source b-tree to the destination.
   57987 */
   57988 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   57989   int rc;
   57990   int destMode;       /* Destination journal mode */
   57991   int pgszSrc = 0;    /* Source page size */
   57992   int pgszDest = 0;   /* Destination page size */
   57993 
   57994   sqlite3_mutex_enter(p->pSrcDb->mutex);
   57995   sqlite3BtreeEnter(p->pSrc);
   57996   if( p->pDestDb ){
   57997     sqlite3_mutex_enter(p->pDestDb->mutex);
   57998   }
   57999 
   58000   rc = p->rc;
   58001   if( !isFatalError(rc) ){
   58002     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   58003     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   58004     int ii;                            /* Iterator variable */
   58005     int nSrcPage = -1;                 /* Size of source db in pages */
   58006     int bCloseTrans = 0;               /* True if src db requires unlocking */
   58007 
   58008     /* If the source pager is currently in a write-transaction, return
   58009     ** SQLITE_BUSY immediately.
   58010     */
   58011     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   58012       rc = SQLITE_BUSY;
   58013     }else{
   58014       rc = SQLITE_OK;
   58015     }
   58016 
   58017     /* Lock the destination database, if it is not locked already. */
   58018     if( SQLITE_OK==rc && p->bDestLocked==0
   58019      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   58020     ){
   58021       p->bDestLocked = 1;
   58022       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   58023     }
   58024 
   58025     /* If there is no open read-transaction on the source database, open
   58026     ** one now. If a transaction is opened here, then it will be closed
   58027     ** before this function exits.
   58028     */
   58029     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   58030       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   58031       bCloseTrans = 1;
   58032     }
   58033 
   58034     /* Do not allow backup if the destination database is in WAL mode
   58035     ** and the page sizes are different between source and destination */
   58036     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   58037     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   58038     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   58039     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   58040       rc = SQLITE_READONLY;
   58041     }
   58042 
   58043     /* Now that there is a read-lock on the source database, query the
   58044     ** source pager for the number of pages in the database.
   58045     */
   58046     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   58047     assert( nSrcPage>=0 );
   58048     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   58049       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   58050       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   58051         DbPage *pSrcPg;                             /* Source page object */
   58052         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   58053         if( rc==SQLITE_OK ){
   58054           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
   58055           sqlite3PagerUnref(pSrcPg);
   58056         }
   58057       }
   58058       p->iNext++;
   58059     }
   58060     if( rc==SQLITE_OK ){
   58061       p->nPagecount = nSrcPage;
   58062       p->nRemaining = nSrcPage+1-p->iNext;
   58063       if( p->iNext>(Pgno)nSrcPage ){
   58064         rc = SQLITE_DONE;
   58065       }else if( !p->isAttached ){
   58066         attachBackupObject(p);
   58067       }
   58068     }
   58069 
   58070     /* Update the schema version field in the destination database. This
   58071     ** is to make sure that the schema-version really does change in
   58072     ** the case where the source and destination databases have the
   58073     ** same schema version.
   58074     */
   58075     if( rc==SQLITE_DONE ){
   58076       rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
   58077       if( rc==SQLITE_OK ){
   58078         if( p->pDestDb ){
   58079           sqlite3ResetInternalSchema(p->pDestDb, -1);
   58080         }
   58081         if( destMode==PAGER_JOURNALMODE_WAL ){
   58082           rc = sqlite3BtreeSetVersion(p->pDest, 2);
   58083         }
   58084       }
   58085       if( rc==SQLITE_OK ){
   58086         int nDestTruncate;
   58087         /* Set nDestTruncate to the final number of pages in the destination
   58088         ** database. The complication here is that the destination page
   58089         ** size may be different to the source page size.
   58090         **
   58091         ** If the source page size is smaller than the destination page size,
   58092         ** round up. In this case the call to sqlite3OsTruncate() below will
   58093         ** fix the size of the file. However it is important to call
   58094         ** sqlite3PagerTruncateImage() here so that any pages in the
   58095         ** destination file that lie beyond the nDestTruncate page mark are
   58096         ** journalled by PagerCommitPhaseOne() before they are destroyed
   58097         ** by the file truncation.
   58098         */
   58099         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   58100         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   58101         if( pgszSrc<pgszDest ){
   58102           int ratio = pgszDest/pgszSrc;
   58103           nDestTruncate = (nSrcPage+ratio-1)/ratio;
   58104           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   58105             nDestTruncate--;
   58106           }
   58107         }else{
   58108           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   58109         }
   58110         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   58111 
   58112         if( pgszSrc<pgszDest ){
   58113           /* If the source page-size is smaller than the destination page-size,
   58114           ** two extra things may need to happen:
   58115           **
   58116           **   * The destination may need to be truncated, and
   58117           **
   58118           **   * Data stored on the pages immediately following the
   58119           **     pending-byte page in the source database may need to be
   58120           **     copied into the destination database.
   58121           */
   58122           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   58123           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   58124           i64 iOff;
   58125           i64 iEnd;
   58126 
   58127           assert( pFile );
   58128           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   58129                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   58130              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   58131           ));
   58132 
   58133           /* This call ensures that all data required to recreate the original
   58134           ** database has been stored in the journal for pDestPager and the
   58135           ** journal synced to disk. So at this point we may safely modify
   58136           ** the database file in any way, knowing that if a power failure
   58137           ** occurs, the original database will be reconstructed from the
   58138           ** journal file.  */
   58139           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
   58140 
   58141           /* Write the extra pages and truncate the database file as required */
   58142           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   58143           for(
   58144             iOff=PENDING_BYTE+pgszSrc;
   58145             rc==SQLITE_OK && iOff<iEnd;
   58146             iOff+=pgszSrc
   58147           ){
   58148             PgHdr *pSrcPg = 0;
   58149             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   58150             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   58151             if( rc==SQLITE_OK ){
   58152               u8 *zData = sqlite3PagerGetData(pSrcPg);
   58153               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   58154             }
   58155             sqlite3PagerUnref(pSrcPg);
   58156           }
   58157           if( rc==SQLITE_OK ){
   58158             rc = backupTruncateFile(pFile, iSize);
   58159           }
   58160 
   58161           /* Sync the database file to disk. */
   58162           if( rc==SQLITE_OK ){
   58163             rc = sqlite3PagerSync(pDestPager);
   58164           }
   58165         }else{
   58166           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   58167         }
   58168 
   58169         /* Finish committing the transaction to the destination database. */
   58170         if( SQLITE_OK==rc
   58171          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
   58172         ){
   58173           rc = SQLITE_DONE;
   58174         }
   58175       }
   58176     }
   58177 
   58178     /* If bCloseTrans is true, then this function opened a read transaction
   58179     ** on the source database. Close the read transaction here. There is
   58180     ** no need to check the return values of the btree methods here, as
   58181     ** "committing" a read-only transaction cannot fail.
   58182     */
   58183     if( bCloseTrans ){
   58184       TESTONLY( int rc2 );
   58185       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   58186       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
   58187       assert( rc2==SQLITE_OK );
   58188     }
   58189 
   58190     if( rc==SQLITE_IOERR_NOMEM ){
   58191       rc = SQLITE_NOMEM;
   58192     }
   58193     p->rc = rc;
   58194   }
   58195   if( p->pDestDb ){
   58196     sqlite3_mutex_leave(p->pDestDb->mutex);
   58197   }
   58198   sqlite3BtreeLeave(p->pSrc);
   58199   sqlite3_mutex_leave(p->pSrcDb->mutex);
   58200   return rc;
   58201 }
   58202 
   58203 /*
   58204 ** Release all resources associated with an sqlite3_backup* handle.
   58205 */
   58206 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   58207   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   58208   MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
   58209   int rc;                              /* Value to return */
   58210 
   58211   /* Enter the mutexes */
   58212   if( p==0 ) return SQLITE_OK;
   58213   sqlite3_mutex_enter(p->pSrcDb->mutex);
   58214   sqlite3BtreeEnter(p->pSrc);
   58215   MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
   58216   if( p->pDestDb ){
   58217     sqlite3_mutex_enter(p->pDestDb->mutex);
   58218   }
   58219 
   58220   /* Detach this backup from the source pager. */
   58221   if( p->pDestDb ){
   58222     p->pSrc->nBackup--;
   58223   }
   58224   if( p->isAttached ){
   58225     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   58226     while( *pp!=p ){
   58227       pp = &(*pp)->pNext;
   58228     }
   58229     *pp = p->pNext;
   58230   }
   58231 
   58232   /* If a transaction is still open on the Btree, roll it back. */
   58233   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
   58234 
   58235   /* Set the error code of the destination database handle. */
   58236   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   58237   sqlite3Error(p->pDestDb, rc, 0);
   58238 
   58239   /* Exit the mutexes and free the backup context structure. */
   58240   if( p->pDestDb ){
   58241     sqlite3_mutex_leave(p->pDestDb->mutex);
   58242   }
   58243   sqlite3BtreeLeave(p->pSrc);
   58244   if( p->pDestDb ){
   58245     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   58246     ** call to sqlite3_backup_init() and is destroyed by a call to
   58247     ** sqlite3_backup_finish(). */
   58248     sqlite3_free(p);
   58249   }
   58250   sqlite3_mutex_leave(mutex);
   58251   return rc;
   58252 }
   58253 
   58254 /*
   58255 ** Return the number of pages still to be backed up as of the most recent
   58256 ** call to sqlite3_backup_step().
   58257 */
   58258 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   58259   return p->nRemaining;
   58260 }
   58261 
   58262 /*
   58263 ** Return the total number of pages in the source database as of the most
   58264 ** recent call to sqlite3_backup_step().
   58265 */
   58266 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   58267   return p->nPagecount;
   58268 }
   58269 
   58270 /*
   58271 ** This function is called after the contents of page iPage of the
   58272 ** source database have been modified. If page iPage has already been
   58273 ** copied into the destination database, then the data written to the
   58274 ** destination is now invalidated. The destination copy of iPage needs
   58275 ** to be updated with the new data before the backup operation is
   58276 ** complete.
   58277 **
   58278 ** It is assumed that the mutex associated with the BtShared object
   58279 ** corresponding to the source database is held when this function is
   58280 ** called.
   58281 */
   58282 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   58283   sqlite3_backup *p;                   /* Iterator variable */
   58284   for(p=pBackup; p; p=p->pNext){
   58285     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   58286     if( !isFatalError(p->rc) && iPage<p->iNext ){
   58287       /* The backup process p has already copied page iPage. But now it
   58288       ** has been modified by a transaction on the source pager. Copy
   58289       ** the new data into the backup.
   58290       */
   58291       int rc;
   58292       assert( p->pDestDb );
   58293       sqlite3_mutex_enter(p->pDestDb->mutex);
   58294       rc = backupOnePage(p, iPage, aData);
   58295       sqlite3_mutex_leave(p->pDestDb->mutex);
   58296       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   58297       if( rc!=SQLITE_OK ){
   58298         p->rc = rc;
   58299       }
   58300     }
   58301   }
   58302 }
   58303 
   58304 /*
   58305 ** Restart the backup process. This is called when the pager layer
   58306 ** detects that the database has been modified by an external database
   58307 ** connection. In this case there is no way of knowing which of the
   58308 ** pages that have been copied into the destination database are still
   58309 ** valid and which are not, so the entire process needs to be restarted.
   58310 **
   58311 ** It is assumed that the mutex associated with the BtShared object
   58312 ** corresponding to the source database is held when this function is
   58313 ** called.
   58314 */
   58315 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   58316   sqlite3_backup *p;                   /* Iterator variable */
   58317   for(p=pBackup; p; p=p->pNext){
   58318     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   58319     p->iNext = 1;
   58320   }
   58321 }
   58322 
   58323 #ifndef SQLITE_OMIT_VACUUM
   58324 /*
   58325 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   58326 ** must be active for both files.
   58327 **
   58328 ** The size of file pTo may be reduced by this operation. If anything
   58329 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   58330 ** transaction is committed before returning.
   58331 */
   58332 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   58333   int rc;
   58334   sqlite3_file *pFd;              /* File descriptor for database pTo */
   58335   sqlite3_backup b;
   58336   sqlite3BtreeEnter(pTo);
   58337   sqlite3BtreeEnter(pFrom);
   58338 
   58339   assert( sqlite3BtreeIsInTrans(pTo) );
   58340   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   58341   if( pFd->pMethods ){
   58342     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
   58343     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
   58344     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   58345     if( rc ) goto copy_finished;
   58346   }
   58347 
   58348   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   58349   ** to 0. This is used by the implementations of sqlite3_backup_step()
   58350   ** and sqlite3_backup_finish() to detect that they are being called
   58351   ** from this function, not directly by the user.
   58352   */
   58353   memset(&b, 0, sizeof(b));
   58354   b.pSrcDb = pFrom->db;
   58355   b.pSrc = pFrom;
   58356   b.pDest = pTo;
   58357   b.iNext = 1;
   58358 
   58359   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   58360   ** file. By passing this as the number of pages to copy to
   58361   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   58362   ** within a single call (unless an error occurs). The assert() statement
   58363   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   58364   ** or an error code.
   58365   */
   58366   sqlite3_backup_step(&b, 0x7FFFFFFF);
   58367   assert( b.rc!=SQLITE_OK );
   58368   rc = sqlite3_backup_finish(&b);
   58369   if( rc==SQLITE_OK ){
   58370     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
   58371   }else{
   58372     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   58373   }
   58374 
   58375   assert( sqlite3BtreeIsInTrans(pTo)==0 );
   58376 copy_finished:
   58377   sqlite3BtreeLeave(pFrom);
   58378   sqlite3BtreeLeave(pTo);
   58379   return rc;
   58380 }
   58381 #endif /* SQLITE_OMIT_VACUUM */
   58382 
   58383 /************** End of backup.c **********************************************/
   58384 /************** Begin file vdbemem.c *****************************************/
   58385 /*
   58386 ** 2004 May 26
   58387 **
   58388 ** The author disclaims copyright to this source code.  In place of
   58389 ** a legal notice, here is a blessing:
   58390 **
   58391 **    May you do good and not evil.
   58392 **    May you find forgiveness for yourself and forgive others.
   58393 **    May you share freely, never taking more than you give.
   58394 **
   58395 *************************************************************************
   58396 **
   58397 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   58398 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   58399 ** only within the VDBE.  Interface routines refer to a Mem using the
   58400 ** name sqlite_value
   58401 */
   58402 
   58403 /*
   58404 ** If pMem is an object with a valid string representation, this routine
   58405 ** ensures the internal encoding for the string representation is
   58406 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   58407 **
   58408 ** If pMem is not a string object, or the encoding of the string
   58409 ** representation is already stored using the requested encoding, then this
   58410 ** routine is a no-op.
   58411 **
   58412 ** SQLITE_OK is returned if the conversion is successful (or not required).
   58413 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   58414 ** between formats.
   58415 */
   58416 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   58417   int rc;
   58418   assert( (pMem->flags&MEM_RowSet)==0 );
   58419   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   58420            || desiredEnc==SQLITE_UTF16BE );
   58421   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   58422     return SQLITE_OK;
   58423   }
   58424   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58425 #ifdef SQLITE_OMIT_UTF16
   58426   return SQLITE_ERROR;
   58427 #else
   58428 
   58429   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   58430   ** then the encoding of the value may not have changed.
   58431   */
   58432   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   58433   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   58434   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   58435   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   58436   return rc;
   58437 #endif
   58438 }
   58439 
   58440 /*
   58441 ** Make sure pMem->z points to a writable allocation of at least
   58442 ** n bytes.
   58443 **
   58444 ** If the memory cell currently contains string or blob data
   58445 ** and the third argument passed to this function is true, the
   58446 ** current content of the cell is preserved. Otherwise, it may
   58447 ** be discarded.
   58448 **
   58449 ** This function sets the MEM_Dyn flag and clears any xDel callback.
   58450 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
   58451 ** not set, Mem.n is zeroed.
   58452 */
   58453 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
   58454   assert( 1 >=
   58455     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
   58456     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
   58457     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
   58458     ((pMem->flags&MEM_Static) ? 1 : 0)
   58459   );
   58460   assert( (pMem->flags&MEM_RowSet)==0 );
   58461 
   58462   if( n<32 ) n = 32;
   58463   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   58464     if( preserve && pMem->z==pMem->zMalloc ){
   58465       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   58466       preserve = 0;
   58467     }else{
   58468       sqlite3DbFree(pMem->db, pMem->zMalloc);
   58469       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   58470     }
   58471   }
   58472 
   58473   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
   58474     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   58475   }
   58476   if( pMem->flags&MEM_Dyn && pMem->xDel ){
   58477     assert( pMem->xDel!=SQLITE_DYNAMIC );
   58478     pMem->xDel((void *)(pMem->z));
   58479   }
   58480 
   58481   pMem->z = pMem->zMalloc;
   58482   if( pMem->z==0 ){
   58483     pMem->flags = MEM_Null;
   58484   }else{
   58485     pMem->flags &= ~(MEM_Ephem|MEM_Static);
   58486   }
   58487   pMem->xDel = 0;
   58488   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
   58489 }
   58490 
   58491 /*
   58492 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   58493 ** that any TEXT or BLOB content is stored in memory obtained from
   58494 ** malloc().  In this way, we know that the memory is safe to be
   58495 ** overwritten or altered.
   58496 **
   58497 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   58498 */
   58499 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   58500   int f;
   58501   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58502   assert( (pMem->flags&MEM_RowSet)==0 );
   58503   ExpandBlob(pMem);
   58504   f = pMem->flags;
   58505   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   58506     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   58507       return SQLITE_NOMEM;
   58508     }
   58509     pMem->z[pMem->n] = 0;
   58510     pMem->z[pMem->n+1] = 0;
   58511     pMem->flags |= MEM_Term;
   58512 #ifdef SQLITE_DEBUG
   58513     pMem->pScopyFrom = 0;
   58514 #endif
   58515   }
   58516 
   58517   return SQLITE_OK;
   58518 }
   58519 
   58520 /*
   58521 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   58522 ** blob stored in dynamically allocated space.
   58523 */
   58524 #ifndef SQLITE_OMIT_INCRBLOB
   58525 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   58526   if( pMem->flags & MEM_Zero ){
   58527     int nByte;
   58528     assert( pMem->flags&MEM_Blob );
   58529     assert( (pMem->flags&MEM_RowSet)==0 );
   58530     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58531 
   58532     /* Set nByte to the number of bytes required to store the expanded blob. */
   58533     nByte = pMem->n + pMem->u.nZero;
   58534     if( nByte<=0 ){
   58535       nByte = 1;
   58536     }
   58537     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   58538       return SQLITE_NOMEM;
   58539     }
   58540 
   58541     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   58542     pMem->n += pMem->u.nZero;
   58543     pMem->flags &= ~(MEM_Zero|MEM_Term);
   58544   }
   58545   return SQLITE_OK;
   58546 }
   58547 #endif
   58548 
   58549 
   58550 /*
   58551 ** Make sure the given Mem is \u0000 terminated.
   58552 */
   58553 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   58554   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58555   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   58556     return SQLITE_OK;   /* Nothing to do */
   58557   }
   58558   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   58559     return SQLITE_NOMEM;
   58560   }
   58561   pMem->z[pMem->n] = 0;
   58562   pMem->z[pMem->n+1] = 0;
   58563   pMem->flags |= MEM_Term;
   58564   return SQLITE_OK;
   58565 }
   58566 
   58567 /*
   58568 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   58569 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   58570 ** is a no-op.
   58571 **
   58572 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   58573 **
   58574 ** A MEM_Null value will never be passed to this function. This function is
   58575 ** used for converting values to text for returning to the user (i.e. via
   58576 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   58577 ** keys are strings. In the former case a NULL pointer is returned the
   58578 ** user and the later is an internal programming error.
   58579 */
   58580 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   58581   int rc = SQLITE_OK;
   58582   int fg = pMem->flags;
   58583   const int nByte = 32;
   58584 
   58585   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58586   assert( !(fg&MEM_Zero) );
   58587   assert( !(fg&(MEM_Str|MEM_Blob)) );
   58588   assert( fg&(MEM_Int|MEM_Real) );
   58589   assert( (pMem->flags&MEM_RowSet)==0 );
   58590   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58591 
   58592 
   58593   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   58594     return SQLITE_NOMEM;
   58595   }
   58596 
   58597   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   58598   ** string representation of the value. Then, if the required encoding
   58599   ** is UTF-16le or UTF-16be do a translation.
   58600   **
   58601   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   58602   */
   58603   if( fg & MEM_Int ){
   58604     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   58605   }else{
   58606     assert( fg & MEM_Real );
   58607     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   58608   }
   58609   pMem->n = sqlite3Strlen30(pMem->z);
   58610   pMem->enc = SQLITE_UTF8;
   58611   pMem->flags |= MEM_Str|MEM_Term;
   58612   sqlite3VdbeChangeEncoding(pMem, enc);
   58613   return rc;
   58614 }
   58615 
   58616 /*
   58617 ** Memory cell pMem contains the context of an aggregate function.
   58618 ** This routine calls the finalize method for that function.  The
   58619 ** result of the aggregate is stored back into pMem.
   58620 **
   58621 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   58622 ** otherwise.
   58623 */
   58624 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   58625   int rc = SQLITE_OK;
   58626   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   58627     sqlite3_context ctx;
   58628     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   58629     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58630     memset(&ctx, 0, sizeof(ctx));
   58631     ctx.s.flags = MEM_Null;
   58632     ctx.s.db = pMem->db;
   58633     ctx.pMem = pMem;
   58634     ctx.pFunc = pFunc;
   58635     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   58636     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   58637     sqlite3DbFree(pMem->db, pMem->zMalloc);
   58638     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   58639     rc = ctx.isError;
   58640   }
   58641   return rc;
   58642 }
   58643 
   58644 /*
   58645 ** If the memory cell contains a string value that must be freed by
   58646 ** invoking an external callback, free it now. Calling this function
   58647 ** does not free any Mem.zMalloc buffer.
   58648 */
   58649 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   58650   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   58651   if( p->flags&MEM_Agg ){
   58652     sqlite3VdbeMemFinalize(p, p->u.pDef);
   58653     assert( (p->flags & MEM_Agg)==0 );
   58654     sqlite3VdbeMemRelease(p);
   58655   }else if( p->flags&MEM_Dyn && p->xDel ){
   58656     assert( (p->flags&MEM_RowSet)==0 );
   58657     assert( p->xDel!=SQLITE_DYNAMIC );
   58658     p->xDel((void *)p->z);
   58659     p->xDel = 0;
   58660   }else if( p->flags&MEM_RowSet ){
   58661     sqlite3RowSetClear(p->u.pRowSet);
   58662   }else if( p->flags&MEM_Frame ){
   58663     sqlite3VdbeMemSetNull(p);
   58664   }
   58665 }
   58666 
   58667 /*
   58668 ** Release any memory held by the Mem. This may leave the Mem in an
   58669 ** inconsistent state, for example with (Mem.z==0) and
   58670 ** (Mem.type==SQLITE_TEXT).
   58671 */
   58672 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   58673   VdbeMemRelease(p);
   58674   sqlite3DbFree(p->db, p->zMalloc);
   58675   p->z = 0;
   58676   p->zMalloc = 0;
   58677   p->xDel = 0;
   58678 }
   58679 
   58680 /*
   58681 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   58682 ** If the double is too large, return 0x8000000000000000.
   58683 **
   58684 ** Most systems appear to do this simply by assigning
   58685 ** variables and without the extra range tests.  But
   58686 ** there are reports that windows throws an expection
   58687 ** if the floating point value is out of range. (See ticket #2880.)
   58688 ** Because we do not completely understand the problem, we will
   58689 ** take the conservative approach and always do range tests
   58690 ** before attempting the conversion.
   58691 */
   58692 static i64 doubleToInt64(double r){
   58693 #ifdef SQLITE_OMIT_FLOATING_POINT
   58694   /* When floating-point is omitted, double and int64 are the same thing */
   58695   return r;
   58696 #else
   58697   /*
   58698   ** Many compilers we encounter do not define constants for the
   58699   ** minimum and maximum 64-bit integers, or they define them
   58700   ** inconsistently.  And many do not understand the "LL" notation.
   58701   ** So we define our own static constants here using nothing
   58702   ** larger than a 32-bit integer constant.
   58703   */
   58704   static const i64 maxInt = LARGEST_INT64;
   58705   static const i64 minInt = SMALLEST_INT64;
   58706 
   58707   if( r<(double)minInt ){
   58708     return minInt;
   58709   }else if( r>(double)maxInt ){
   58710     /* minInt is correct here - not maxInt.  It turns out that assigning
   58711     ** a very large positive number to an integer results in a very large
   58712     ** negative integer.  This makes no sense, but it is what x86 hardware
   58713     ** does so for compatibility we will do the same in software. */
   58714     return minInt;
   58715   }else{
   58716     return (i64)r;
   58717   }
   58718 #endif
   58719 }
   58720 
   58721 /*
   58722 ** Return some kind of integer value which is the best we can do
   58723 ** at representing the value that *pMem describes as an integer.
   58724 ** If pMem is an integer, then the value is exact.  If pMem is
   58725 ** a floating-point then the value returned is the integer part.
   58726 ** If pMem is a string or blob, then we make an attempt to convert
   58727 ** it into a integer and return that.  If pMem represents an
   58728 ** an SQL-NULL value, return 0.
   58729 **
   58730 ** If pMem represents a string value, its encoding might be changed.
   58731 */
   58732 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   58733   int flags;
   58734   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58735   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58736   flags = pMem->flags;
   58737   if( flags & MEM_Int ){
   58738     return pMem->u.i;
   58739   }else if( flags & MEM_Real ){
   58740     return doubleToInt64(pMem->r);
   58741   }else if( flags & (MEM_Str|MEM_Blob) ){
   58742     i64 value = 0;
   58743     assert( pMem->z || pMem->n==0 );
   58744     testcase( pMem->z==0 );
   58745     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   58746     return value;
   58747   }else{
   58748     return 0;
   58749   }
   58750 }
   58751 
   58752 /*
   58753 ** Return the best representation of pMem that we can get into a
   58754 ** double.  If pMem is already a double or an integer, return its
   58755 ** value.  If it is a string or blob, try to convert it to a double.
   58756 ** If it is a NULL, return 0.0.
   58757 */
   58758 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   58759   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58760   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58761   if( pMem->flags & MEM_Real ){
   58762     return pMem->r;
   58763   }else if( pMem->flags & MEM_Int ){
   58764     return (double)pMem->u.i;
   58765   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   58766     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   58767     double val = (double)0;
   58768     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   58769     return val;
   58770   }else{
   58771     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   58772     return (double)0;
   58773   }
   58774 }
   58775 
   58776 /*
   58777 ** The MEM structure is already a MEM_Real.  Try to also make it a
   58778 ** MEM_Int if we can.
   58779 */
   58780 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   58781   assert( pMem->flags & MEM_Real );
   58782   assert( (pMem->flags & MEM_RowSet)==0 );
   58783   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58784   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58785 
   58786   pMem->u.i = doubleToInt64(pMem->r);
   58787 
   58788   /* Only mark the value as an integer if
   58789   **
   58790   **    (1) the round-trip conversion real->int->real is a no-op, and
   58791   **    (2) The integer is neither the largest nor the smallest
   58792   **        possible integer (ticket #3922)
   58793   **
   58794   ** The second and third terms in the following conditional enforces
   58795   ** the second condition under the assumption that addition overflow causes
   58796   ** values to wrap around.  On x86 hardware, the third term is always
   58797   ** true and could be omitted.  But we leave it in because other
   58798   ** architectures might behave differently.
   58799   */
   58800   if( pMem->r==(double)pMem->u.i
   58801    && pMem->u.i>SMALLEST_INT64
   58802 #if defined(__i486__) || defined(__x86_64__)
   58803    && ALWAYS(pMem->u.i<LARGEST_INT64)
   58804 #else
   58805    && pMem->u.i<LARGEST_INT64
   58806 #endif
   58807   ){
   58808     pMem->flags |= MEM_Int;
   58809   }
   58810 }
   58811 
   58812 /*
   58813 ** Convert pMem to type integer.  Invalidate any prior representations.
   58814 */
   58815 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   58816   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58817   assert( (pMem->flags & MEM_RowSet)==0 );
   58818   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58819 
   58820   pMem->u.i = sqlite3VdbeIntValue(pMem);
   58821   MemSetTypeFlag(pMem, MEM_Int);
   58822   return SQLITE_OK;
   58823 }
   58824 
   58825 /*
   58826 ** Convert pMem so that it is of type MEM_Real.
   58827 ** Invalidate any prior representations.
   58828 */
   58829 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   58830   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58831   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58832 
   58833   pMem->r = sqlite3VdbeRealValue(pMem);
   58834   MemSetTypeFlag(pMem, MEM_Real);
   58835   return SQLITE_OK;
   58836 }
   58837 
   58838 /*
   58839 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   58840 ** Invalidate any prior representations.
   58841 **
   58842 ** Every effort is made to force the conversion, even if the input
   58843 ** is a string that does not look completely like a number.  Convert
   58844 ** as much of the string as we can and ignore the rest.
   58845 */
   58846 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   58847   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   58848     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   58849     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58850     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
   58851       MemSetTypeFlag(pMem, MEM_Int);
   58852     }else{
   58853       pMem->r = sqlite3VdbeRealValue(pMem);
   58854       MemSetTypeFlag(pMem, MEM_Real);
   58855       sqlite3VdbeIntegerAffinity(pMem);
   58856     }
   58857   }
   58858   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   58859   pMem->flags &= ~(MEM_Str|MEM_Blob);
   58860   return SQLITE_OK;
   58861 }
   58862 
   58863 /*
   58864 ** Delete any previous value and set the value stored in *pMem to NULL.
   58865 */
   58866 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   58867   if( pMem->flags & MEM_Frame ){
   58868     VdbeFrame *pFrame = pMem->u.pFrame;
   58869     pFrame->pParent = pFrame->v->pDelFrame;
   58870     pFrame->v->pDelFrame = pFrame;
   58871   }
   58872   if( pMem->flags & MEM_RowSet ){
   58873     sqlite3RowSetClear(pMem->u.pRowSet);
   58874   }
   58875   MemSetTypeFlag(pMem, MEM_Null);
   58876   pMem->type = SQLITE_NULL;
   58877 }
   58878 
   58879 /*
   58880 ** Delete any previous value and set the value to be a BLOB of length
   58881 ** n containing all zeros.
   58882 */
   58883 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   58884   sqlite3VdbeMemRelease(pMem);
   58885   pMem->flags = MEM_Blob|MEM_Zero;
   58886   pMem->type = SQLITE_BLOB;
   58887   pMem->n = 0;
   58888   if( n<0 ) n = 0;
   58889   pMem->u.nZero = n;
   58890   pMem->enc = SQLITE_UTF8;
   58891 
   58892 #ifdef SQLITE_OMIT_INCRBLOB
   58893   sqlite3VdbeMemGrow(pMem, n, 0);
   58894   if( pMem->z ){
   58895     pMem->n = n;
   58896     memset(pMem->z, 0, n);
   58897   }
   58898 #endif
   58899 }
   58900 
   58901 /*
   58902 ** Delete any previous value and set the value stored in *pMem to val,
   58903 ** manifest type INTEGER.
   58904 */
   58905 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   58906   sqlite3VdbeMemRelease(pMem);
   58907   pMem->u.i = val;
   58908   pMem->flags = MEM_Int;
   58909   pMem->type = SQLITE_INTEGER;
   58910 }
   58911 
   58912 #ifndef SQLITE_OMIT_FLOATING_POINT
   58913 /*
   58914 ** Delete any previous value and set the value stored in *pMem to val,
   58915 ** manifest type REAL.
   58916 */
   58917 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   58918   if( sqlite3IsNaN(val) ){
   58919     sqlite3VdbeMemSetNull(pMem);
   58920   }else{
   58921     sqlite3VdbeMemRelease(pMem);
   58922     pMem->r = val;
   58923     pMem->flags = MEM_Real;
   58924     pMem->type = SQLITE_FLOAT;
   58925   }
   58926 }
   58927 #endif
   58928 
   58929 /*
   58930 ** Delete any previous value and set the value of pMem to be an
   58931 ** empty boolean index.
   58932 */
   58933 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   58934   sqlite3 *db = pMem->db;
   58935   assert( db!=0 );
   58936   assert( (pMem->flags & MEM_RowSet)==0 );
   58937   sqlite3VdbeMemRelease(pMem);
   58938   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   58939   if( db->mallocFailed ){
   58940     pMem->flags = MEM_Null;
   58941   }else{
   58942     assert( pMem->zMalloc );
   58943     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   58944                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   58945     assert( pMem->u.pRowSet!=0 );
   58946     pMem->flags = MEM_RowSet;
   58947   }
   58948 }
   58949 
   58950 /*
   58951 ** Return true if the Mem object contains a TEXT or BLOB that is
   58952 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   58953 */
   58954 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   58955   assert( p->db!=0 );
   58956   if( p->flags & (MEM_Str|MEM_Blob) ){
   58957     int n = p->n;
   58958     if( p->flags & MEM_Zero ){
   58959       n += p->u.nZero;
   58960     }
   58961     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   58962   }
   58963   return 0;
   58964 }
   58965 
   58966 #ifdef SQLITE_DEBUG
   58967 /*
   58968 ** This routine prepares a memory cell for modication by breaking
   58969 ** its link to a shallow copy and by marking any current shallow
   58970 ** copies of this cell as invalid.
   58971 **
   58972 ** This is used for testing and debugging only - to make sure shallow
   58973 ** copies are not misused.
   58974 */
   58975 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   58976   int i;
   58977   Mem *pX;
   58978   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
   58979     if( pX->pScopyFrom==pMem ){
   58980       pX->flags |= MEM_Invalid;
   58981       pX->pScopyFrom = 0;
   58982     }
   58983   }
   58984   pMem->pScopyFrom = 0;
   58985 }
   58986 #endif /* SQLITE_DEBUG */
   58987 
   58988 /*
   58989 ** Size of struct Mem not including the Mem.zMalloc member.
   58990 */
   58991 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
   58992 
   58993 /*
   58994 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   58995 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   58996 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   58997 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   58998 */
   58999 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   59000   assert( (pFrom->flags & MEM_RowSet)==0 );
   59001   VdbeMemRelease(pTo);
   59002   memcpy(pTo, pFrom, MEMCELLSIZE);
   59003   pTo->xDel = 0;
   59004   if( (pFrom->flags&MEM_Static)==0 ){
   59005     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   59006     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   59007     pTo->flags |= srcType;
   59008   }
   59009 }
   59010 
   59011 /*
   59012 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   59013 ** freed before the copy is made.
   59014 */
   59015 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   59016   int rc = SQLITE_OK;
   59017 
   59018   assert( (pFrom->flags & MEM_RowSet)==0 );
   59019   VdbeMemRelease(pTo);
   59020   memcpy(pTo, pFrom, MEMCELLSIZE);
   59021   pTo->flags &= ~MEM_Dyn;
   59022 
   59023   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   59024     if( 0==(pFrom->flags&MEM_Static) ){
   59025       pTo->flags |= MEM_Ephem;
   59026       rc = sqlite3VdbeMemMakeWriteable(pTo);
   59027     }
   59028   }
   59029 
   59030   return rc;
   59031 }
   59032 
   59033 /*
   59034 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   59035 ** freed. If pFrom contains ephemeral data, a copy is made.
   59036 **
   59037 ** pFrom contains an SQL NULL when this routine returns.
   59038 */
   59039 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   59040   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   59041   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   59042   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   59043 
   59044   sqlite3VdbeMemRelease(pTo);
   59045   memcpy(pTo, pFrom, sizeof(Mem));
   59046   pFrom->flags = MEM_Null;
   59047   pFrom->xDel = 0;
   59048   pFrom->zMalloc = 0;
   59049 }
   59050 
   59051 /*
   59052 ** Change the value of a Mem to be a string or a BLOB.
   59053 **
   59054 ** The memory management strategy depends on the value of the xDel
   59055 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   59056 ** string is copied into a (possibly existing) buffer managed by the
   59057 ** Mem structure. Otherwise, any existing buffer is freed and the
   59058 ** pointer copied.
   59059 **
   59060 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   59061 ** size limit) then no memory allocation occurs.  If the string can be
   59062 ** stored without allocating memory, then it is.  If a memory allocation
   59063 ** is required to store the string, then value of pMem is unchanged.  In
   59064 ** either case, SQLITE_TOOBIG is returned.
   59065 */
   59066 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   59067   Mem *pMem,          /* Memory cell to set to string value */
   59068   const char *z,      /* String pointer */
   59069   int n,              /* Bytes in string, or negative */
   59070   u8 enc,             /* Encoding of z.  0 for BLOBs */
   59071   void (*xDel)(void*) /* Destructor function */
   59072 ){
   59073   int nByte = n;      /* New value for pMem->n */
   59074   int iLimit;         /* Maximum allowed string or blob size */
   59075   u16 flags = 0;      /* New value for pMem->flags */
   59076 
   59077   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   59078   assert( (pMem->flags & MEM_RowSet)==0 );
   59079 
   59080   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   59081   if( !z ){
   59082     sqlite3VdbeMemSetNull(pMem);
   59083     return SQLITE_OK;
   59084   }
   59085 
   59086   if( pMem->db ){
   59087     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   59088   }else{
   59089     iLimit = SQLITE_MAX_LENGTH;
   59090   }
   59091   flags = (enc==0?MEM_Blob:MEM_Str);
   59092   if( nByte<0 ){
   59093     assert( enc!=0 );
   59094     if( enc==SQLITE_UTF8 ){
   59095       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   59096     }else{
   59097       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   59098     }
   59099     flags |= MEM_Term;
   59100   }
   59101 
   59102   /* The following block sets the new values of Mem.z and Mem.xDel. It
   59103   ** also sets a flag in local variable "flags" to indicate the memory
   59104   ** management (one of MEM_Dyn or MEM_Static).
   59105   */
   59106   if( xDel==SQLITE_TRANSIENT ){
   59107     int nAlloc = nByte;
   59108     if( flags&MEM_Term ){
   59109       nAlloc += (enc==SQLITE_UTF8?1:2);
   59110     }
   59111     if( nByte>iLimit ){
   59112       return SQLITE_TOOBIG;
   59113     }
   59114     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   59115       return SQLITE_NOMEM;
   59116     }
   59117     memcpy(pMem->z, z, nAlloc);
   59118   }else if( xDel==SQLITE_DYNAMIC ){
   59119     sqlite3VdbeMemRelease(pMem);
   59120     pMem->zMalloc = pMem->z = (char *)z;
   59121     pMem->xDel = 0;
   59122   }else{
   59123     sqlite3VdbeMemRelease(pMem);
   59124     pMem->z = (char *)z;
   59125     pMem->xDel = xDel;
   59126     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   59127   }
   59128 
   59129   pMem->n = nByte;
   59130   pMem->flags = flags;
   59131   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   59132   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
   59133 
   59134 #ifndef SQLITE_OMIT_UTF16
   59135   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   59136     return SQLITE_NOMEM;
   59137   }
   59138 #endif
   59139 
   59140   if( nByte>iLimit ){
   59141     return SQLITE_TOOBIG;
   59142   }
   59143 
   59144   return SQLITE_OK;
   59145 }
   59146 
   59147 /*
   59148 ** Compare the values contained by the two memory cells, returning
   59149 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   59150 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   59151 ** and reals) sorted numerically, followed by text ordered by the collating
   59152 ** sequence pColl and finally blob's ordered by memcmp().
   59153 **
   59154 ** Two NULL values are considered equal by this function.
   59155 */
   59156 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   59157   int rc;
   59158   int f1, f2;
   59159   int combined_flags;
   59160 
   59161   f1 = pMem1->flags;
   59162   f2 = pMem2->flags;
   59163   combined_flags = f1|f2;
   59164   assert( (combined_flags & MEM_RowSet)==0 );
   59165 
   59166   /* If one value is NULL, it is less than the other. If both values
   59167   ** are NULL, return 0.
   59168   */
   59169   if( combined_flags&MEM_Null ){
   59170     return (f2&MEM_Null) - (f1&MEM_Null);
   59171   }
   59172 
   59173   /* If one value is a number and the other is not, the number is less.
   59174   ** If both are numbers, compare as reals if one is a real, or as integers
   59175   ** if both values are integers.
   59176   */
   59177   if( combined_flags&(MEM_Int|MEM_Real) ){
   59178     if( !(f1&(MEM_Int|MEM_Real)) ){
   59179       return 1;
   59180     }
   59181     if( !(f2&(MEM_Int|MEM_Real)) ){
   59182       return -1;
   59183     }
   59184     if( (f1 & f2 & MEM_Int)==0 ){
   59185       double r1, r2;
   59186       if( (f1&MEM_Real)==0 ){
   59187         r1 = (double)pMem1->u.i;
   59188       }else{
   59189         r1 = pMem1->r;
   59190       }
   59191       if( (f2&MEM_Real)==0 ){
   59192         r2 = (double)pMem2->u.i;
   59193       }else{
   59194         r2 = pMem2->r;
   59195       }
   59196       if( r1<r2 ) return -1;
   59197       if( r1>r2 ) return 1;
   59198       return 0;
   59199     }else{
   59200       assert( f1&MEM_Int );
   59201       assert( f2&MEM_Int );
   59202       if( pMem1->u.i < pMem2->u.i ) return -1;
   59203       if( pMem1->u.i > pMem2->u.i ) return 1;
   59204       return 0;
   59205     }
   59206   }
   59207 
   59208   /* If one value is a string and the other is a blob, the string is less.
   59209   ** If both are strings, compare using the collating functions.
   59210   */
   59211   if( combined_flags&MEM_Str ){
   59212     if( (f1 & MEM_Str)==0 ){
   59213       return 1;
   59214     }
   59215     if( (f2 & MEM_Str)==0 ){
   59216       return -1;
   59217     }
   59218 
   59219     assert( pMem1->enc==pMem2->enc );
   59220     assert( pMem1->enc==SQLITE_UTF8 ||
   59221             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   59222 
   59223     /* The collation sequence must be defined at this point, even if
   59224     ** the user deletes the collation sequence after the vdbe program is
   59225     ** compiled (this was not always the case).
   59226     */
   59227     assert( !pColl || pColl->xCmp );
   59228 
   59229     if( pColl ){
   59230       if( pMem1->enc==pColl->enc ){
   59231         /* The strings are already in the correct encoding.  Call the
   59232         ** comparison function directly */
   59233         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   59234       }else{
   59235         const void *v1, *v2;
   59236         int n1, n2;
   59237         Mem c1;
   59238         Mem c2;
   59239         memset(&c1, 0, sizeof(c1));
   59240         memset(&c2, 0, sizeof(c2));
   59241         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   59242         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   59243         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   59244         n1 = v1==0 ? 0 : c1.n;
   59245         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   59246         n2 = v2==0 ? 0 : c2.n;
   59247         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   59248         sqlite3VdbeMemRelease(&c1);
   59249         sqlite3VdbeMemRelease(&c2);
   59250         return rc;
   59251       }
   59252     }
   59253     /* If a NULL pointer was passed as the collate function, fall through
   59254     ** to the blob case and use memcmp().  */
   59255   }
   59256 
   59257   /* Both values must be blobs.  Compare using memcmp().  */
   59258   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   59259   if( rc==0 ){
   59260     rc = pMem1->n - pMem2->n;
   59261   }
   59262   return rc;
   59263 }
   59264 
   59265 /*
   59266 ** Move data out of a btree key or data field and into a Mem structure.
   59267 ** The data or key is taken from the entry that pCur is currently pointing
   59268 ** to.  offset and amt determine what portion of the data or key to retrieve.
   59269 ** key is true to get the key or false to get data.  The result is written
   59270 ** into the pMem element.
   59271 **
   59272 ** The pMem structure is assumed to be uninitialized.  Any prior content
   59273 ** is overwritten without being freed.
   59274 **
   59275 ** If this routine fails for any reason (malloc returns NULL or unable
   59276 ** to read from the disk) then the pMem is left in an inconsistent state.
   59277 */
   59278 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   59279   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   59280   int offset,       /* Offset from the start of data to return bytes from. */
   59281   int amt,          /* Number of bytes to return. */
   59282   int key,          /* If true, retrieve from the btree key, not data. */
   59283   Mem *pMem         /* OUT: Return data in this Mem structure. */
   59284 ){
   59285   char *zData;        /* Data from the btree layer */
   59286   int available = 0;  /* Number of bytes available on the local btree page */
   59287   int rc = SQLITE_OK; /* Return code */
   59288 
   59289   assert( sqlite3BtreeCursorIsValid(pCur) );
   59290 
   59291   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   59292   ** that both the BtShared and database handle mutexes are held. */
   59293   assert( (pMem->flags & MEM_RowSet)==0 );
   59294   if( key ){
   59295     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   59296   }else{
   59297     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   59298   }
   59299   assert( zData!=0 );
   59300 
   59301   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
   59302     sqlite3VdbeMemRelease(pMem);
   59303     pMem->z = &zData[offset];
   59304     pMem->flags = MEM_Blob|MEM_Ephem;
   59305   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   59306     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
   59307     pMem->enc = 0;
   59308     pMem->type = SQLITE_BLOB;
   59309     if( key ){
   59310       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   59311     }else{
   59312       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   59313     }
   59314     pMem->z[amt] = 0;
   59315     pMem->z[amt+1] = 0;
   59316     if( rc!=SQLITE_OK ){
   59317       sqlite3VdbeMemRelease(pMem);
   59318     }
   59319   }
   59320   pMem->n = amt;
   59321 
   59322   return rc;
   59323 }
   59324 
   59325 /* This function is only available internally, it is not part of the
   59326 ** external API. It works in a similar way to sqlite3_value_text(),
   59327 ** except the data returned is in the encoding specified by the second
   59328 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   59329 ** SQLITE_UTF8.
   59330 **
   59331 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   59332 ** If that is the case, then the result must be aligned on an even byte
   59333 ** boundary.
   59334 */
   59335 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   59336   if( !pVal ) return 0;
   59337 
   59338   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   59339   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   59340   assert( (pVal->flags & MEM_RowSet)==0 );
   59341 
   59342   if( pVal->flags&MEM_Null ){
   59343     return 0;
   59344   }
   59345   assert( (MEM_Blob>>3) == MEM_Str );
   59346   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   59347   ExpandBlob(pVal);
   59348   if( pVal->flags&MEM_Str ){
   59349     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   59350     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   59351       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   59352       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   59353         return 0;
   59354       }
   59355     }
   59356     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
   59357   }else{
   59358     assert( (pVal->flags&MEM_Blob)==0 );
   59359     sqlite3VdbeMemStringify(pVal, enc);
   59360     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   59361   }
   59362   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   59363               || pVal->db->mallocFailed );
   59364   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   59365     return pVal->z;
   59366   }else{
   59367     return 0;
   59368   }
   59369 }
   59370 
   59371 /*
   59372 ** Create a new sqlite3_value object.
   59373 */
   59374 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   59375   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   59376   if( p ){
   59377     p->flags = MEM_Null;
   59378     p->type = SQLITE_NULL;
   59379     p->db = db;
   59380   }
   59381   return p;
   59382 }
   59383 
   59384 /*
   59385 ** Create a new sqlite3_value object, containing the value of pExpr.
   59386 **
   59387 ** This only works for very simple expressions that consist of one constant
   59388 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   59389 ** be converted directly into a value, then the value is allocated and
   59390 ** a pointer written to *ppVal. The caller is responsible for deallocating
   59391 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   59392 ** cannot be converted to a value, then *ppVal is set to NULL.
   59393 */
   59394 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   59395   sqlite3 *db,              /* The database connection */
   59396   Expr *pExpr,              /* The expression to evaluate */
   59397   u8 enc,                   /* Encoding to use */
   59398   u8 affinity,              /* Affinity to use */
   59399   sqlite3_value **ppVal     /* Write the new value here */
   59400 ){
   59401   int op;
   59402   char *zVal = 0;
   59403   sqlite3_value *pVal = 0;
   59404   int negInt = 1;
   59405   const char *zNeg = "";
   59406 
   59407   if( !pExpr ){
   59408     *ppVal = 0;
   59409     return SQLITE_OK;
   59410   }
   59411   op = pExpr->op;
   59412 
   59413   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
   59414   ** The ifdef here is to enable us to achieve 100% branch test coverage even
   59415   ** when SQLITE_ENABLE_STAT3 is omitted.
   59416   */
   59417 #ifdef SQLITE_ENABLE_STAT3
   59418   if( op==TK_REGISTER ) op = pExpr->op2;
   59419 #else
   59420   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   59421 #endif
   59422 
   59423   /* Handle negative integers in a single step.  This is needed in the
   59424   ** case when the value is -9223372036854775808.
   59425   */
   59426   if( op==TK_UMINUS
   59427    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   59428     pExpr = pExpr->pLeft;
   59429     op = pExpr->op;
   59430     negInt = -1;
   59431     zNeg = "-";
   59432   }
   59433 
   59434   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   59435     pVal = sqlite3ValueNew(db);
   59436     if( pVal==0 ) goto no_mem;
   59437     if( ExprHasProperty(pExpr, EP_IntValue) ){
   59438       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   59439     }else{
   59440       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   59441       if( zVal==0 ) goto no_mem;
   59442       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   59443       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
   59444     }
   59445     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   59446       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   59447     }else{
   59448       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   59449     }
   59450     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   59451     if( enc!=SQLITE_UTF8 ){
   59452       sqlite3VdbeChangeEncoding(pVal, enc);
   59453     }
   59454   }else if( op==TK_UMINUS ) {
   59455     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   59456     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
   59457       sqlite3VdbeMemNumerify(pVal);
   59458       if( pVal->u.i==SMALLEST_INT64 ){
   59459         pVal->flags &= MEM_Int;
   59460         pVal->flags |= MEM_Real;
   59461         pVal->r = (double)LARGEST_INT64;
   59462       }else{
   59463         pVal->u.i = -pVal->u.i;
   59464       }
   59465       pVal->r = -pVal->r;
   59466       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   59467     }
   59468   }else if( op==TK_NULL ){
   59469     pVal = sqlite3ValueNew(db);
   59470     if( pVal==0 ) goto no_mem;
   59471   }
   59472 #ifndef SQLITE_OMIT_BLOB_LITERAL
   59473   else if( op==TK_BLOB ){
   59474     int nVal;
   59475     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   59476     assert( pExpr->u.zToken[1]=='\'' );
   59477     pVal = sqlite3ValueNew(db);
   59478     if( !pVal ) goto no_mem;
   59479     zVal = &pExpr->u.zToken[2];
   59480     nVal = sqlite3Strlen30(zVal)-1;
   59481     assert( zVal[nVal]=='\'' );
   59482     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   59483                          0, SQLITE_DYNAMIC);
   59484   }
   59485 #endif
   59486 
   59487   if( pVal ){
   59488     sqlite3VdbeMemStoreType(pVal);
   59489   }
   59490   *ppVal = pVal;
   59491   return SQLITE_OK;
   59492 
   59493 no_mem:
   59494   db->mallocFailed = 1;
   59495   sqlite3DbFree(db, zVal);
   59496   sqlite3ValueFree(pVal);
   59497   *ppVal = 0;
   59498   return SQLITE_NOMEM;
   59499 }
   59500 
   59501 /*
   59502 ** Change the string value of an sqlite3_value object
   59503 */
   59504 SQLITE_PRIVATE void sqlite3ValueSetStr(
   59505   sqlite3_value *v,     /* Value to be set */
   59506   int n,                /* Length of string z */
   59507   const void *z,        /* Text of the new string */
   59508   u8 enc,               /* Encoding to use */
   59509   void (*xDel)(void*)   /* Destructor for the string */
   59510 ){
   59511   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   59512 }
   59513 
   59514 /*
   59515 ** Free an sqlite3_value object
   59516 */
   59517 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   59518   if( !v ) return;
   59519   sqlite3VdbeMemRelease((Mem *)v);
   59520   sqlite3DbFree(((Mem*)v)->db, v);
   59521 }
   59522 
   59523 /*
   59524 ** Return the number of bytes in the sqlite3_value object assuming
   59525 ** that it uses the encoding "enc"
   59526 */
   59527 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   59528   Mem *p = (Mem*)pVal;
   59529   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   59530     if( p->flags & MEM_Zero ){
   59531       return p->n + p->u.nZero;
   59532     }else{
   59533       return p->n;
   59534     }
   59535   }
   59536   return 0;
   59537 }
   59538 
   59539 /************** End of vdbemem.c *********************************************/
   59540 /************** Begin file vdbeaux.c *****************************************/
   59541 /*
   59542 ** 2003 September 6
   59543 **
   59544 ** The author disclaims copyright to this source code.  In place of
   59545 ** a legal notice, here is a blessing:
   59546 **
   59547 **    May you do good and not evil.
   59548 **    May you find forgiveness for yourself and forgive others.
   59549 **    May you share freely, never taking more than you give.
   59550 **
   59551 *************************************************************************
   59552 ** This file contains code used for creating, destroying, and populating
   59553 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   59554 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   59555 ** But that file was getting too big so this subroutines were split out.
   59556 */
   59557 
   59558 
   59559 
   59560 /*
   59561 ** When debugging the code generator in a symbolic debugger, one can
   59562 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
   59563 ** as they are added to the instruction stream.
   59564 */
   59565 #ifdef SQLITE_DEBUG
   59566 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
   59567 #endif
   59568 
   59569 
   59570 /*
   59571 ** Create a new virtual database engine.
   59572 */
   59573 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
   59574   Vdbe *p;
   59575   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   59576   if( p==0 ) return 0;
   59577   p->db = db;
   59578   if( db->pVdbe ){
   59579     db->pVdbe->pPrev = p;
   59580   }
   59581   p->pNext = db->pVdbe;
   59582   p->pPrev = 0;
   59583   db->pVdbe = p;
   59584   p->magic = VDBE_MAGIC_INIT;
   59585   return p;
   59586 }
   59587 
   59588 /*
   59589 ** Remember the SQL string for a prepared statement.
   59590 */
   59591 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   59592   assert( isPrepareV2==1 || isPrepareV2==0 );
   59593   if( p==0 ) return;
   59594 #ifdef SQLITE_OMIT_TRACE
   59595   if( !isPrepareV2 ) return;
   59596 #endif
   59597   assert( p->zSql==0 );
   59598   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   59599   p->isPrepareV2 = (u8)isPrepareV2;
   59600 }
   59601 
   59602 /*
   59603 ** Return the SQL associated with a prepared statement
   59604 */
   59605 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   59606   Vdbe *p = (Vdbe *)pStmt;
   59607   return (p && p->isPrepareV2) ? p->zSql : 0;
   59608 }
   59609 
   59610 /*
   59611 ** Swap all content between two VDBE structures.
   59612 */
   59613 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   59614   Vdbe tmp, *pTmp;
   59615   char *zTmp;
   59616   tmp = *pA;
   59617   *pA = *pB;
   59618   *pB = tmp;
   59619   pTmp = pA->pNext;
   59620   pA->pNext = pB->pNext;
   59621   pB->pNext = pTmp;
   59622   pTmp = pA->pPrev;
   59623   pA->pPrev = pB->pPrev;
   59624   pB->pPrev = pTmp;
   59625   zTmp = pA->zSql;
   59626   pA->zSql = pB->zSql;
   59627   pB->zSql = zTmp;
   59628   pB->isPrepareV2 = pA->isPrepareV2;
   59629 }
   59630 
   59631 #ifdef SQLITE_DEBUG
   59632 /*
   59633 ** Turn tracing on or off
   59634 */
   59635 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
   59636   p->trace = trace;
   59637 }
   59638 #endif
   59639 
   59640 /*
   59641 ** Resize the Vdbe.aOp array so that it is at least one op larger than
   59642 ** it was.
   59643 **
   59644 ** If an out-of-memory error occurs while resizing the array, return
   59645 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
   59646 ** unchanged (this is so that any opcodes already allocated can be
   59647 ** correctly deallocated along with the rest of the Vdbe).
   59648 */
   59649 static int growOpArray(Vdbe *p){
   59650   VdbeOp *pNew;
   59651   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   59652   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   59653   if( pNew ){
   59654     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   59655     p->aOp = pNew;
   59656   }
   59657   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   59658 }
   59659 
   59660 /*
   59661 ** Add a new instruction to the list of instructions current in the
   59662 ** VDBE.  Return the address of the new instruction.
   59663 **
   59664 ** Parameters:
   59665 **
   59666 **    p               Pointer to the VDBE
   59667 **
   59668 **    op              The opcode for this instruction
   59669 **
   59670 **    p1, p2, p3      Operands
   59671 **
   59672 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   59673 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   59674 ** operand.
   59675 */
   59676 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   59677   int i;
   59678   VdbeOp *pOp;
   59679 
   59680   i = p->nOp;
   59681   assert( p->magic==VDBE_MAGIC_INIT );
   59682   assert( op>0 && op<0xff );
   59683   if( p->nOpAlloc<=i ){
   59684     if( growOpArray(p) ){
   59685       return 1;
   59686     }
   59687   }
   59688   p->nOp++;
   59689   pOp = &p->aOp[i];
   59690   pOp->opcode = (u8)op;
   59691   pOp->p5 = 0;
   59692   pOp->p1 = p1;
   59693   pOp->p2 = p2;
   59694   pOp->p3 = p3;
   59695   pOp->p4.p = 0;
   59696   pOp->p4type = P4_NOTUSED;
   59697 #ifdef SQLITE_DEBUG
   59698   pOp->zComment = 0;
   59699   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   59700 #endif
   59701 #ifdef VDBE_PROFILE
   59702   pOp->cycles = 0;
   59703   pOp->cnt = 0;
   59704 #endif
   59705   return i;
   59706 }
   59707 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   59708   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   59709 }
   59710 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   59711   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   59712 }
   59713 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   59714   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   59715 }
   59716 
   59717 
   59718 /*
   59719 ** Add an opcode that includes the p4 value as a pointer.
   59720 */
   59721 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   59722   Vdbe *p,            /* Add the opcode to this VM */
   59723   int op,             /* The new opcode */
   59724   int p1,             /* The P1 operand */
   59725   int p2,             /* The P2 operand */
   59726   int p3,             /* The P3 operand */
   59727   const char *zP4,    /* The P4 operand */
   59728   int p4type          /* P4 operand type */
   59729 ){
   59730   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   59731   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   59732   return addr;
   59733 }
   59734 
   59735 /*
   59736 ** Add an OP_ParseSchema opcode.  This routine is broken out from
   59737 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
   59738 ** as having been used.
   59739 **
   59740 ** The zWhere string must have been obtained from sqlite3_malloc().
   59741 ** This routine will take ownership of the allocated memory.
   59742 */
   59743 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   59744   int j;
   59745   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
   59746   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
   59747   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   59748 }
   59749 
   59750 /*
   59751 ** Add an opcode that includes the p4 value as an integer.
   59752 */
   59753 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   59754   Vdbe *p,            /* Add the opcode to this VM */
   59755   int op,             /* The new opcode */
   59756   int p1,             /* The P1 operand */
   59757   int p2,             /* The P2 operand */
   59758   int p3,             /* The P3 operand */
   59759   int p4              /* The P4 operand as an integer */
   59760 ){
   59761   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   59762   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   59763   return addr;
   59764 }
   59765 
   59766 /*
   59767 ** Create a new symbolic label for an instruction that has yet to be
   59768 ** coded.  The symbolic label is really just a negative number.  The
   59769 ** label can be used as the P2 value of an operation.  Later, when
   59770 ** the label is resolved to a specific address, the VDBE will scan
   59771 ** through its operation list and change all values of P2 which match
   59772 ** the label into the resolved address.
   59773 **
   59774 ** The VDBE knows that a P2 value is a label because labels are
   59775 ** always negative and P2 values are suppose to be non-negative.
   59776 ** Hence, a negative P2 value is a label that has yet to be resolved.
   59777 **
   59778 ** Zero is returned if a malloc() fails.
   59779 */
   59780 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
   59781   int i = p->nLabel++;
   59782   assert( p->magic==VDBE_MAGIC_INIT );
   59783   if( (i & (i-1))==0 ){
   59784     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   59785                                        (i*2+1)*sizeof(p->aLabel[0]));
   59786   }
   59787   if( p->aLabel ){
   59788     p->aLabel[i] = -1;
   59789   }
   59790   return -1-i;
   59791 }
   59792 
   59793 /*
   59794 ** Resolve label "x" to be the address of the next instruction to
   59795 ** be inserted.  The parameter "x" must have been obtained from
   59796 ** a prior call to sqlite3VdbeMakeLabel().
   59797 */
   59798 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   59799   int j = -1-x;
   59800   assert( p->magic==VDBE_MAGIC_INIT );
   59801   assert( j>=0 && j<p->nLabel );
   59802   if( p->aLabel ){
   59803     p->aLabel[j] = p->nOp;
   59804   }
   59805 }
   59806 
   59807 /*
   59808 ** Mark the VDBE as one that can only be run one time.
   59809 */
   59810 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   59811   p->runOnlyOnce = 1;
   59812 }
   59813 
   59814 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   59815 
   59816 /*
   59817 ** The following type and function are used to iterate through all opcodes
   59818 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   59819 ** invoke directly or indirectly. It should be used as follows:
   59820 **
   59821 **   Op *pOp;
   59822 **   VdbeOpIter sIter;
   59823 **
   59824 **   memset(&sIter, 0, sizeof(sIter));
   59825 **   sIter.v = v;                            // v is of type Vdbe*
   59826 **   while( (pOp = opIterNext(&sIter)) ){
   59827 **     // Do something with pOp
   59828 **   }
   59829 **   sqlite3DbFree(v->db, sIter.apSub);
   59830 **
   59831 */
   59832 typedef struct VdbeOpIter VdbeOpIter;
   59833 struct VdbeOpIter {
   59834   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   59835   SubProgram **apSub;        /* Array of subprograms */
   59836   int nSub;                  /* Number of entries in apSub */
   59837   int iAddr;                 /* Address of next instruction to return */
   59838   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   59839 };
   59840 static Op *opIterNext(VdbeOpIter *p){
   59841   Vdbe *v = p->v;
   59842   Op *pRet = 0;
   59843   Op *aOp;
   59844   int nOp;
   59845 
   59846   if( p->iSub<=p->nSub ){
   59847 
   59848     if( p->iSub==0 ){
   59849       aOp = v->aOp;
   59850       nOp = v->nOp;
   59851     }else{
   59852       aOp = p->apSub[p->iSub-1]->aOp;
   59853       nOp = p->apSub[p->iSub-1]->nOp;
   59854     }
   59855     assert( p->iAddr<nOp );
   59856 
   59857     pRet = &aOp[p->iAddr];
   59858     p->iAddr++;
   59859     if( p->iAddr==nOp ){
   59860       p->iSub++;
   59861       p->iAddr = 0;
   59862     }
   59863 
   59864     if( pRet->p4type==P4_SUBPROGRAM ){
   59865       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   59866       int j;
   59867       for(j=0; j<p->nSub; j++){
   59868         if( p->apSub[j]==pRet->p4.pProgram ) break;
   59869       }
   59870       if( j==p->nSub ){
   59871         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   59872         if( !p->apSub ){
   59873           pRet = 0;
   59874         }else{
   59875           p->apSub[p->nSub++] = pRet->p4.pProgram;
   59876         }
   59877       }
   59878     }
   59879   }
   59880 
   59881   return pRet;
   59882 }
   59883 
   59884 /*
   59885 ** Check if the program stored in the VM associated with pParse may
   59886 ** throw an ABORT exception (causing the statement, but not entire transaction
   59887 ** to be rolled back). This condition is true if the main program or any
   59888 ** sub-programs contains any of the following:
   59889 **
   59890 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   59891 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   59892 **   *  OP_Destroy
   59893 **   *  OP_VUpdate
   59894 **   *  OP_VRename
   59895 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   59896 **
   59897 ** Then check that the value of Parse.mayAbort is true if an
   59898 ** ABORT may be thrown, or false otherwise. Return true if it does
   59899 ** match, or false otherwise. This function is intended to be used as
   59900 ** part of an assert statement in the compiler. Similar to:
   59901 **
   59902 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   59903 */
   59904 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   59905   int hasAbort = 0;
   59906   Op *pOp;
   59907   VdbeOpIter sIter;
   59908   memset(&sIter, 0, sizeof(sIter));
   59909   sIter.v = v;
   59910 
   59911   while( (pOp = opIterNext(&sIter))!=0 ){
   59912     int opcode = pOp->opcode;
   59913     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   59914 #ifndef SQLITE_OMIT_FOREIGN_KEY
   59915      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   59916 #endif
   59917      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   59918       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   59919     ){
   59920       hasAbort = 1;
   59921       break;
   59922     }
   59923   }
   59924   sqlite3DbFree(v->db, sIter.apSub);
   59925 
   59926   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
   59927   ** If malloc failed, then the while() loop above may not have iterated
   59928   ** through all opcodes and hasAbort may be set incorrectly. Return
   59929   ** true for this case to prevent the assert() in the callers frame
   59930   ** from failing.  */
   59931   return ( v->db->mallocFailed || hasAbort==mayAbort );
   59932 }
   59933 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   59934 
   59935 /*
   59936 ** Loop through the program looking for P2 values that are negative
   59937 ** on jump instructions.  Each such value is a label.  Resolve the
   59938 ** label by setting the P2 value to its correct non-zero value.
   59939 **
   59940 ** This routine is called once after all opcodes have been inserted.
   59941 **
   59942 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   59943 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   59944 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   59945 **
   59946 ** The Op.opflags field is set on all opcodes.
   59947 */
   59948 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   59949   int i;
   59950   int nMaxArgs = *pMaxFuncArgs;
   59951   Op *pOp;
   59952   int *aLabel = p->aLabel;
   59953   p->readOnly = 1;
   59954   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   59955     u8 opcode = pOp->opcode;
   59956 
   59957     pOp->opflags = sqlite3OpcodeProperty[opcode];
   59958     if( opcode==OP_Function || opcode==OP_AggStep ){
   59959       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   59960     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
   59961       p->readOnly = 0;
   59962 #ifndef SQLITE_OMIT_VIRTUALTABLE
   59963     }else if( opcode==OP_VUpdate ){
   59964       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   59965     }else if( opcode==OP_VFilter ){
   59966       int n;
   59967       assert( p->nOp - i >= 3 );
   59968       assert( pOp[-1].opcode==OP_Integer );
   59969       n = pOp[-1].p1;
   59970       if( n>nMaxArgs ) nMaxArgs = n;
   59971 #endif
   59972     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
   59973       pOp->p4.xAdvance = sqlite3BtreeNext;
   59974       pOp->p4type = P4_ADVANCE;
   59975     }else if( opcode==OP_Prev ){
   59976       pOp->p4.xAdvance = sqlite3BtreePrevious;
   59977       pOp->p4type = P4_ADVANCE;
   59978     }
   59979 
   59980     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   59981       assert( -1-pOp->p2<p->nLabel );
   59982       pOp->p2 = aLabel[-1-pOp->p2];
   59983     }
   59984   }
   59985   sqlite3DbFree(p->db, p->aLabel);
   59986   p->aLabel = 0;
   59987 
   59988   *pMaxFuncArgs = nMaxArgs;
   59989 }
   59990 
   59991 /*
   59992 ** Return the address of the next instruction to be inserted.
   59993 */
   59994 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   59995   assert( p->magic==VDBE_MAGIC_INIT );
   59996   return p->nOp;
   59997 }
   59998 
   59999 /*
   60000 ** This function returns a pointer to the array of opcodes associated with
   60001 ** the Vdbe passed as the first argument. It is the callers responsibility
   60002 ** to arrange for the returned array to be eventually freed using the
   60003 ** vdbeFreeOpArray() function.
   60004 **
   60005 ** Before returning, *pnOp is set to the number of entries in the returned
   60006 ** array. Also, *pnMaxArg is set to the larger of its current value and
   60007 ** the number of entries in the Vdbe.apArg[] array required to execute the
   60008 ** returned program.
   60009 */
   60010 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   60011   VdbeOp *aOp = p->aOp;
   60012   assert( aOp && !p->db->mallocFailed );
   60013 
   60014   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   60015   assert( p->btreeMask==0 );
   60016 
   60017   resolveP2Values(p, pnMaxArg);
   60018   *pnOp = p->nOp;
   60019   p->aOp = 0;
   60020   return aOp;
   60021 }
   60022 
   60023 /*
   60024 ** Add a whole list of operations to the operation stack.  Return the
   60025 ** address of the first operation added.
   60026 */
   60027 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   60028   int addr;
   60029   assert( p->magic==VDBE_MAGIC_INIT );
   60030   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
   60031     return 0;
   60032   }
   60033   addr = p->nOp;
   60034   if( ALWAYS(nOp>0) ){
   60035     int i;
   60036     VdbeOpList const *pIn = aOp;
   60037     for(i=0; i<nOp; i++, pIn++){
   60038       int p2 = pIn->p2;
   60039       VdbeOp *pOut = &p->aOp[i+addr];
   60040       pOut->opcode = pIn->opcode;
   60041       pOut->p1 = pIn->p1;
   60042       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
   60043         pOut->p2 = addr + ADDR(p2);
   60044       }else{
   60045         pOut->p2 = p2;
   60046       }
   60047       pOut->p3 = pIn->p3;
   60048       pOut->p4type = P4_NOTUSED;
   60049       pOut->p4.p = 0;
   60050       pOut->p5 = 0;
   60051 #ifdef SQLITE_DEBUG
   60052       pOut->zComment = 0;
   60053       if( sqlite3VdbeAddopTrace ){
   60054         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   60055       }
   60056 #endif
   60057     }
   60058     p->nOp += nOp;
   60059   }
   60060   return addr;
   60061 }
   60062 
   60063 /*
   60064 ** Change the value of the P1 operand for a specific instruction.
   60065 ** This routine is useful when a large program is loaded from a
   60066 ** static array using sqlite3VdbeAddOpList but we want to make a
   60067 ** few minor changes to the program.
   60068 */
   60069 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
   60070   assert( p!=0 );
   60071   if( ((u32)p->nOp)>addr ){
   60072     p->aOp[addr].p1 = val;
   60073   }
   60074 }
   60075 
   60076 /*
   60077 ** Change the value of the P2 operand for a specific instruction.
   60078 ** This routine is useful for setting a jump destination.
   60079 */
   60080 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
   60081   assert( p!=0 );
   60082   if( ((u32)p->nOp)>addr ){
   60083     p->aOp[addr].p2 = val;
   60084   }
   60085 }
   60086 
   60087 /*
   60088 ** Change the value of the P3 operand for a specific instruction.
   60089 */
   60090 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
   60091   assert( p!=0 );
   60092   if( ((u32)p->nOp)>addr ){
   60093     p->aOp[addr].p3 = val;
   60094   }
   60095 }
   60096 
   60097 /*
   60098 ** Change the value of the P5 operand for the most recently
   60099 ** added operation.
   60100 */
   60101 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   60102   assert( p!=0 );
   60103   if( p->aOp ){
   60104     assert( p->nOp>0 );
   60105     p->aOp[p->nOp-1].p5 = val;
   60106   }
   60107 }
   60108 
   60109 /*
   60110 ** Change the P2 operand of instruction addr so that it points to
   60111 ** the address of the next instruction to be coded.
   60112 */
   60113 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   60114   assert( addr>=0 || p->db->mallocFailed );
   60115   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
   60116 }
   60117 
   60118 
   60119 /*
   60120 ** If the input FuncDef structure is ephemeral, then free it.  If
   60121 ** the FuncDef is not ephermal, then do nothing.
   60122 */
   60123 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   60124   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
   60125     sqlite3DbFree(db, pDef);
   60126   }
   60127 }
   60128 
   60129 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   60130 
   60131 /*
   60132 ** Delete a P4 value if necessary.
   60133 */
   60134 static void freeP4(sqlite3 *db, int p4type, void *p4){
   60135   if( p4 ){
   60136     assert( db );
   60137     switch( p4type ){
   60138       case P4_REAL:
   60139       case P4_INT64:
   60140       case P4_DYNAMIC:
   60141       case P4_KEYINFO:
   60142       case P4_INTARRAY:
   60143       case P4_KEYINFO_HANDOFF: {
   60144         sqlite3DbFree(db, p4);
   60145         break;
   60146       }
   60147       case P4_MPRINTF: {
   60148         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
   60149         break;
   60150       }
   60151       case P4_VDBEFUNC: {
   60152         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
   60153         freeEphemeralFunction(db, pVdbeFunc->pFunc);
   60154         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
   60155         sqlite3DbFree(db, pVdbeFunc);
   60156         break;
   60157       }
   60158       case P4_FUNCDEF: {
   60159         freeEphemeralFunction(db, (FuncDef*)p4);
   60160         break;
   60161       }
   60162       case P4_MEM: {
   60163         if( db->pnBytesFreed==0 ){
   60164           sqlite3ValueFree((sqlite3_value*)p4);
   60165         }else{
   60166           Mem *p = (Mem*)p4;
   60167           sqlite3DbFree(db, p->zMalloc);
   60168           sqlite3DbFree(db, p);
   60169         }
   60170         break;
   60171       }
   60172       case P4_VTAB : {
   60173         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   60174         break;
   60175       }
   60176     }
   60177   }
   60178 }
   60179 
   60180 /*
   60181 ** Free the space allocated for aOp and any p4 values allocated for the
   60182 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   60183 ** nOp entries.
   60184 */
   60185 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   60186   if( aOp ){
   60187     Op *pOp;
   60188     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   60189       freeP4(db, pOp->p4type, pOp->p4.p);
   60190 #ifdef SQLITE_DEBUG
   60191       sqlite3DbFree(db, pOp->zComment);
   60192 #endif
   60193     }
   60194   }
   60195   sqlite3DbFree(db, aOp);
   60196 }
   60197 
   60198 /*
   60199 ** Link the SubProgram object passed as the second argument into the linked
   60200 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   60201 ** objects when the VM is no longer required.
   60202 */
   60203 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   60204   p->pNext = pVdbe->pProgram;
   60205   pVdbe->pProgram = p;
   60206 }
   60207 
   60208 /*
   60209 ** Change the opcode at addr into OP_Noop
   60210 */
   60211 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   60212   if( p->aOp ){
   60213     VdbeOp *pOp = &p->aOp[addr];
   60214     sqlite3 *db = p->db;
   60215     freeP4(db, pOp->p4type, pOp->p4.p);
   60216     memset(pOp, 0, sizeof(pOp[0]));
   60217     pOp->opcode = OP_Noop;
   60218   }
   60219 }
   60220 
   60221 /*
   60222 ** Change the value of the P4 operand for a specific instruction.
   60223 ** This routine is useful when a large program is loaded from a
   60224 ** static array using sqlite3VdbeAddOpList but we want to make a
   60225 ** few minor changes to the program.
   60226 **
   60227 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   60228 ** the string is made into memory obtained from sqlite3_malloc().
   60229 ** A value of n==0 means copy bytes of zP4 up to and including the
   60230 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   60231 **
   60232 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
   60233 ** A copy is made of the KeyInfo structure into memory obtained from
   60234 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
   60235 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
   60236 ** stored in memory that the caller has obtained from sqlite3_malloc. The
   60237 ** caller should not free the allocation, it will be freed when the Vdbe is
   60238 ** finalized.
   60239 **
   60240 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   60241 ** to a string or structure that is guaranteed to exist for the lifetime of
   60242 ** the Vdbe. In these cases we can just copy the pointer.
   60243 **
   60244 ** If addr<0 then change P4 on the most recently inserted instruction.
   60245 */
   60246 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   60247   Op *pOp;
   60248   sqlite3 *db;
   60249   assert( p!=0 );
   60250   db = p->db;
   60251   assert( p->magic==VDBE_MAGIC_INIT );
   60252   if( p->aOp==0 || db->mallocFailed ){
   60253     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
   60254       freeP4(db, n, (void*)*(char**)&zP4);
   60255     }
   60256     return;
   60257   }
   60258   assert( p->nOp>0 );
   60259   assert( addr<p->nOp );
   60260   if( addr<0 ){
   60261     addr = p->nOp - 1;
   60262   }
   60263   pOp = &p->aOp[addr];
   60264   freeP4(db, pOp->p4type, pOp->p4.p);
   60265   pOp->p4.p = 0;
   60266   if( n==P4_INT32 ){
   60267     /* Note: this cast is safe, because the origin data point was an int
   60268     ** that was cast to a (const char *). */
   60269     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   60270     pOp->p4type = P4_INT32;
   60271   }else if( zP4==0 ){
   60272     pOp->p4.p = 0;
   60273     pOp->p4type = P4_NOTUSED;
   60274   }else if( n==P4_KEYINFO ){
   60275     KeyInfo *pKeyInfo;
   60276     int nField, nByte;
   60277 
   60278     nField = ((KeyInfo*)zP4)->nField;
   60279     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   60280     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
   60281     pOp->p4.pKeyInfo = pKeyInfo;
   60282     if( pKeyInfo ){
   60283       u8 *aSortOrder;
   60284       memcpy((char*)pKeyInfo, zP4, nByte - nField);
   60285       aSortOrder = pKeyInfo->aSortOrder;
   60286       if( aSortOrder ){
   60287         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   60288         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
   60289       }
   60290       pOp->p4type = P4_KEYINFO;
   60291     }else{
   60292       p->db->mallocFailed = 1;
   60293       pOp->p4type = P4_NOTUSED;
   60294     }
   60295   }else if( n==P4_KEYINFO_HANDOFF ){
   60296     pOp->p4.p = (void*)zP4;
   60297     pOp->p4type = P4_KEYINFO;
   60298   }else if( n==P4_VTAB ){
   60299     pOp->p4.p = (void*)zP4;
   60300     pOp->p4type = P4_VTAB;
   60301     sqlite3VtabLock((VTable *)zP4);
   60302     assert( ((VTable *)zP4)->db==p->db );
   60303   }else if( n<0 ){
   60304     pOp->p4.p = (void*)zP4;
   60305     pOp->p4type = (signed char)n;
   60306   }else{
   60307     if( n==0 ) n = sqlite3Strlen30(zP4);
   60308     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   60309     pOp->p4type = P4_DYNAMIC;
   60310   }
   60311 }
   60312 
   60313 #ifndef NDEBUG
   60314 /*
   60315 ** Change the comment on the the most recently coded instruction.  Or
   60316 ** insert a No-op and add the comment to that new instruction.  This
   60317 ** makes the code easier to read during debugging.  None of this happens
   60318 ** in a production build.
   60319 */
   60320 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   60321   assert( p->nOp>0 || p->aOp==0 );
   60322   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   60323   if( p->nOp ){
   60324     assert( p->aOp );
   60325     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
   60326     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
   60327   }
   60328 }
   60329 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   60330   va_list ap;
   60331   if( p ){
   60332     va_start(ap, zFormat);
   60333     vdbeVComment(p, zFormat, ap);
   60334     va_end(ap);
   60335   }
   60336 }
   60337 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   60338   va_list ap;
   60339   if( p ){
   60340     sqlite3VdbeAddOp0(p, OP_Noop);
   60341     va_start(ap, zFormat);
   60342     vdbeVComment(p, zFormat, ap);
   60343     va_end(ap);
   60344   }
   60345 }
   60346 #endif  /* NDEBUG */
   60347 
   60348 /*
   60349 ** Return the opcode for a given address.  If the address is -1, then
   60350 ** return the most recently inserted opcode.
   60351 **
   60352 ** If a memory allocation error has occurred prior to the calling of this
   60353 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   60354 ** is readable but not writable, though it is cast to a writable value.
   60355 ** The return of a dummy opcode allows the call to continue functioning
   60356 ** after a OOM fault without having to check to see if the return from
   60357 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   60358 ** dummy will never be written to.  This is verified by code inspection and
   60359 ** by running with Valgrind.
   60360 **
   60361 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
   60362 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
   60363 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
   60364 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
   60365 ** having to double-check to make sure that the result is non-negative. But
   60366 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
   60367 ** check the value of p->nOp-1 before continuing.
   60368 */
   60369 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   60370   /* C89 specifies that the constant "dummy" will be initialized to all
   60371   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   60372   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   60373   assert( p->magic==VDBE_MAGIC_INIT );
   60374   if( addr<0 ){
   60375 #ifdef SQLITE_OMIT_TRACE
   60376     if( p->nOp==0 ) return (VdbeOp*)&dummy;
   60377 #endif
   60378     addr = p->nOp - 1;
   60379   }
   60380   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   60381   if( p->db->mallocFailed ){
   60382     return (VdbeOp*)&dummy;
   60383   }else{
   60384     return &p->aOp[addr];
   60385   }
   60386 }
   60387 
   60388 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   60389      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   60390 /*
   60391 ** Compute a string that describes the P4 parameter for an opcode.
   60392 ** Use zTemp for any required temporary buffer space.
   60393 */
   60394 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   60395   char *zP4 = zTemp;
   60396   assert( nTemp>=20 );
   60397   switch( pOp->p4type ){
   60398     case P4_KEYINFO_STATIC:
   60399     case P4_KEYINFO: {
   60400       int i, j;
   60401       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   60402       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
   60403       i = sqlite3Strlen30(zTemp);
   60404       for(j=0; j<pKeyInfo->nField; j++){
   60405         CollSeq *pColl = pKeyInfo->aColl[j];
   60406         if( pColl ){
   60407           int n = sqlite3Strlen30(pColl->zName);
   60408           if( i+n>nTemp-6 ){
   60409             memcpy(&zTemp[i],",...",4);
   60410             break;
   60411           }
   60412           zTemp[i++] = ',';
   60413           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
   60414             zTemp[i++] = '-';
   60415           }
   60416           memcpy(&zTemp[i], pColl->zName,n+1);
   60417           i += n;
   60418         }else if( i+4<nTemp-6 ){
   60419           memcpy(&zTemp[i],",nil",4);
   60420           i += 4;
   60421         }
   60422       }
   60423       zTemp[i++] = ')';
   60424       zTemp[i] = 0;
   60425       assert( i<nTemp );
   60426       break;
   60427     }
   60428     case P4_COLLSEQ: {
   60429       CollSeq *pColl = pOp->p4.pColl;
   60430       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
   60431       break;
   60432     }
   60433     case P4_FUNCDEF: {
   60434       FuncDef *pDef = pOp->p4.pFunc;
   60435       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   60436       break;
   60437     }
   60438     case P4_INT64: {
   60439       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   60440       break;
   60441     }
   60442     case P4_INT32: {
   60443       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   60444       break;
   60445     }
   60446     case P4_REAL: {
   60447       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   60448       break;
   60449     }
   60450     case P4_MEM: {
   60451       Mem *pMem = pOp->p4.pMem;
   60452       if( pMem->flags & MEM_Str ){
   60453         zP4 = pMem->z;
   60454       }else if( pMem->flags & MEM_Int ){
   60455         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   60456       }else if( pMem->flags & MEM_Real ){
   60457         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   60458       }else if( pMem->flags & MEM_Null ){
   60459         sqlite3_snprintf(nTemp, zTemp, "NULL");
   60460       }else{
   60461         assert( pMem->flags & MEM_Blob );
   60462         zP4 = "(blob)";
   60463       }
   60464       break;
   60465     }
   60466 #ifndef SQLITE_OMIT_VIRTUALTABLE
   60467     case P4_VTAB: {
   60468       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   60469       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   60470       break;
   60471     }
   60472 #endif
   60473     case P4_INTARRAY: {
   60474       sqlite3_snprintf(nTemp, zTemp, "intarray");
   60475       break;
   60476     }
   60477     case P4_SUBPROGRAM: {
   60478       sqlite3_snprintf(nTemp, zTemp, "program");
   60479       break;
   60480     }
   60481     case P4_ADVANCE: {
   60482       zTemp[0] = 0;
   60483       break;
   60484     }
   60485     default: {
   60486       zP4 = pOp->p4.z;
   60487       if( zP4==0 ){
   60488         zP4 = zTemp;
   60489         zTemp[0] = 0;
   60490       }
   60491     }
   60492   }
   60493   assert( zP4!=0 );
   60494   return zP4;
   60495 }
   60496 #endif
   60497 
   60498 /*
   60499 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   60500 **
   60501 ** The prepared statements need to know in advance the complete set of
   60502 ** attached databases that will be use.  A mask of these databases
   60503 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
   60504 ** p->btreeMask of databases that will require a lock.
   60505 */
   60506 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   60507   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
   60508   assert( i<(int)sizeof(p->btreeMask)*8 );
   60509   p->btreeMask |= ((yDbMask)1)<<i;
   60510   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
   60511     p->lockMask |= ((yDbMask)1)<<i;
   60512   }
   60513 }
   60514 
   60515 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   60516 /*
   60517 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   60518 ** this routine obtains the mutex associated with each BtShared structure
   60519 ** that may be accessed by the VM passed as an argument. In doing so it also
   60520 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   60521 ** that the correct busy-handler callback is invoked if required.
   60522 **
   60523 ** If SQLite is not threadsafe but does support shared-cache mode, then
   60524 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
   60525 ** of all of BtShared structures accessible via the database handle
   60526 ** associated with the VM.
   60527 **
   60528 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   60529 ** function is a no-op.
   60530 **
   60531 ** The p->btreeMask field is a bitmask of all btrees that the prepared
   60532 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
   60533 ** corresponding to btrees that use shared cache.  Then the runtime of
   60534 ** this routine is N*N.  But as N is rarely more than 1, this should not
   60535 ** be a problem.
   60536 */
   60537 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
   60538   int i;
   60539   yDbMask mask;
   60540   sqlite3 *db;
   60541   Db *aDb;
   60542   int nDb;
   60543   if( p->lockMask==0 ) return;  /* The common case */
   60544   db = p->db;
   60545   aDb = db->aDb;
   60546   nDb = db->nDb;
   60547   for(i=0, mask=1; i<nDb; i++, mask += mask){
   60548     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
   60549       sqlite3BtreeEnter(aDb[i].pBt);
   60550     }
   60551   }
   60552 }
   60553 #endif
   60554 
   60555 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   60556 /*
   60557 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
   60558 */
   60559 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
   60560   int i;
   60561   yDbMask mask;
   60562   sqlite3 *db;
   60563   Db *aDb;
   60564   int nDb;
   60565   if( p->lockMask==0 ) return;  /* The common case */
   60566   db = p->db;
   60567   aDb = db->aDb;
   60568   nDb = db->nDb;
   60569   for(i=0, mask=1; i<nDb; i++, mask += mask){
   60570     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
   60571       sqlite3BtreeLeave(aDb[i].pBt);
   60572     }
   60573   }
   60574 }
   60575 #endif
   60576 
   60577 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   60578 /*
   60579 ** Print a single opcode.  This routine is used for debugging only.
   60580 */
   60581 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   60582   char *zP4;
   60583   char zPtr[50];
   60584   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
   60585   if( pOut==0 ) pOut = stdout;
   60586   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   60587   fprintf(pOut, zFormat1, pc,
   60588       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   60589 #ifdef SQLITE_DEBUG
   60590       pOp->zComment ? pOp->zComment : ""
   60591 #else
   60592       ""
   60593 #endif
   60594   );
   60595   fflush(pOut);
   60596 }
   60597 #endif
   60598 
   60599 /*
   60600 ** Release an array of N Mem elements
   60601 */
   60602 static void releaseMemArray(Mem *p, int N){
   60603   if( p && N ){
   60604     Mem *pEnd;
   60605     sqlite3 *db = p->db;
   60606     u8 malloc_failed = db->mallocFailed;
   60607     if( db->pnBytesFreed ){
   60608       for(pEnd=&p[N]; p<pEnd; p++){
   60609         sqlite3DbFree(db, p->zMalloc);
   60610       }
   60611       return;
   60612     }
   60613     for(pEnd=&p[N]; p<pEnd; p++){
   60614       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   60615 
   60616       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   60617       ** that takes advantage of the fact that the memory cell value is
   60618       ** being set to NULL after releasing any dynamic resources.
   60619       **
   60620       ** The justification for duplicating code is that according to
   60621       ** callgrind, this causes a certain test case to hit the CPU 4.7
   60622       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   60623       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   60624       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   60625       ** with no indexes using a single prepared INSERT statement, bind()
   60626       ** and reset(). Inserts are grouped into a transaction.
   60627       */
   60628       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   60629         sqlite3VdbeMemRelease(p);
   60630       }else if( p->zMalloc ){
   60631         sqlite3DbFree(db, p->zMalloc);
   60632         p->zMalloc = 0;
   60633       }
   60634 
   60635       p->flags = MEM_Invalid;
   60636     }
   60637     db->mallocFailed = malloc_failed;
   60638   }
   60639 }
   60640 
   60641 /*
   60642 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   60643 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   60644 */
   60645 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   60646   int i;
   60647   Mem *aMem = VdbeFrameMem(p);
   60648   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   60649   for(i=0; i<p->nChildCsr; i++){
   60650     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   60651   }
   60652   releaseMemArray(aMem, p->nChildMem);
   60653   sqlite3DbFree(p->v->db, p);
   60654 }
   60655 
   60656 #ifndef SQLITE_OMIT_EXPLAIN
   60657 /*
   60658 ** Give a listing of the program in the virtual machine.
   60659 **
   60660 ** The interface is the same as sqlite3VdbeExec().  But instead of
   60661 ** running the code, it invokes the callback once for each instruction.
   60662 ** This feature is used to implement "EXPLAIN".
   60663 **
   60664 ** When p->explain==1, each instruction is listed.  When
   60665 ** p->explain==2, only OP_Explain instructions are listed and these
   60666 ** are shown in a different format.  p->explain==2 is used to implement
   60667 ** EXPLAIN QUERY PLAN.
   60668 **
   60669 ** When p->explain==1, first the main program is listed, then each of
   60670 ** the trigger subprograms are listed one by one.
   60671 */
   60672 SQLITE_PRIVATE int sqlite3VdbeList(
   60673   Vdbe *p                   /* The VDBE */
   60674 ){
   60675   int nRow;                            /* Stop when row count reaches this */
   60676   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   60677   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   60678   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   60679   sqlite3 *db = p->db;                 /* The database connection */
   60680   int i;                               /* Loop counter */
   60681   int rc = SQLITE_OK;                  /* Return code */
   60682   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
   60683 
   60684   assert( p->explain );
   60685   assert( p->magic==VDBE_MAGIC_RUN );
   60686   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   60687 
   60688   /* Even though this opcode does not use dynamic strings for
   60689   ** the result, result columns may become dynamic if the user calls
   60690   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   60691   */
   60692   releaseMemArray(pMem, 8);
   60693   p->pResultSet = 0;
   60694 
   60695   if( p->rc==SQLITE_NOMEM ){
   60696     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   60697     ** sqlite3_column_text16() failed.  */
   60698     db->mallocFailed = 1;
   60699     return SQLITE_ERROR;
   60700   }
   60701 
   60702   /* When the number of output rows reaches nRow, that means the
   60703   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   60704   ** nRow is the sum of the number of rows in the main program, plus
   60705   ** the sum of the number of rows in all trigger subprograms encountered
   60706   ** so far.  The nRow value will increase as new trigger subprograms are
   60707   ** encountered, but p->pc will eventually catch up to nRow.
   60708   */
   60709   nRow = p->nOp;
   60710   if( p->explain==1 ){
   60711     /* The first 8 memory cells are used for the result set.  So we will
   60712     ** commandeer the 9th cell to use as storage for an array of pointers
   60713     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   60714     ** cells.  */
   60715     assert( p->nMem>9 );
   60716     pSub = &p->aMem[9];
   60717     if( pSub->flags&MEM_Blob ){
   60718       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   60719       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   60720       nSub = pSub->n/sizeof(Vdbe*);
   60721       apSub = (SubProgram **)pSub->z;
   60722     }
   60723     for(i=0; i<nSub; i++){
   60724       nRow += apSub[i]->nOp;
   60725     }
   60726   }
   60727 
   60728   do{
   60729     i = p->pc++;
   60730   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   60731   if( i>=nRow ){
   60732     p->rc = SQLITE_OK;
   60733     rc = SQLITE_DONE;
   60734   }else if( db->u1.isInterrupted ){
   60735     p->rc = SQLITE_INTERRUPT;
   60736     rc = SQLITE_ERROR;
   60737     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   60738   }else{
   60739     char *z;
   60740     Op *pOp;
   60741     if( i<p->nOp ){
   60742       /* The output line number is small enough that we are still in the
   60743       ** main program. */
   60744       pOp = &p->aOp[i];
   60745     }else{
   60746       /* We are currently listing subprograms.  Figure out which one and
   60747       ** pick up the appropriate opcode. */
   60748       int j;
   60749       i -= p->nOp;
   60750       for(j=0; i>=apSub[j]->nOp; j++){
   60751         i -= apSub[j]->nOp;
   60752       }
   60753       pOp = &apSub[j]->aOp[i];
   60754     }
   60755     if( p->explain==1 ){
   60756       pMem->flags = MEM_Int;
   60757       pMem->type = SQLITE_INTEGER;
   60758       pMem->u.i = i;                                /* Program counter */
   60759       pMem++;
   60760 
   60761       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   60762       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   60763       assert( pMem->z!=0 );
   60764       pMem->n = sqlite3Strlen30(pMem->z);
   60765       pMem->type = SQLITE_TEXT;
   60766       pMem->enc = SQLITE_UTF8;
   60767       pMem++;
   60768 
   60769       /* When an OP_Program opcode is encounter (the only opcode that has
   60770       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   60771       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   60772       ** has not already been seen.
   60773       */
   60774       if( pOp->p4type==P4_SUBPROGRAM ){
   60775         int nByte = (nSub+1)*sizeof(SubProgram*);
   60776         int j;
   60777         for(j=0; j<nSub; j++){
   60778           if( apSub[j]==pOp->p4.pProgram ) break;
   60779         }
   60780         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
   60781           apSub = (SubProgram **)pSub->z;
   60782           apSub[nSub++] = pOp->p4.pProgram;
   60783           pSub->flags |= MEM_Blob;
   60784           pSub->n = nSub*sizeof(SubProgram*);
   60785         }
   60786       }
   60787     }
   60788 
   60789     pMem->flags = MEM_Int;
   60790     pMem->u.i = pOp->p1;                          /* P1 */
   60791     pMem->type = SQLITE_INTEGER;
   60792     pMem++;
   60793 
   60794     pMem->flags = MEM_Int;
   60795     pMem->u.i = pOp->p2;                          /* P2 */
   60796     pMem->type = SQLITE_INTEGER;
   60797     pMem++;
   60798 
   60799     pMem->flags = MEM_Int;
   60800     pMem->u.i = pOp->p3;                          /* P3 */
   60801     pMem->type = SQLITE_INTEGER;
   60802     pMem++;
   60803 
   60804     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   60805       assert( p->db->mallocFailed );
   60806       return SQLITE_ERROR;
   60807     }
   60808     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   60809     z = displayP4(pOp, pMem->z, 32);
   60810     if( z!=pMem->z ){
   60811       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
   60812     }else{
   60813       assert( pMem->z!=0 );
   60814       pMem->n = sqlite3Strlen30(pMem->z);
   60815       pMem->enc = SQLITE_UTF8;
   60816     }
   60817     pMem->type = SQLITE_TEXT;
   60818     pMem++;
   60819 
   60820     if( p->explain==1 ){
   60821       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   60822         assert( p->db->mallocFailed );
   60823         return SQLITE_ERROR;
   60824       }
   60825       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   60826       pMem->n = 2;
   60827       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   60828       pMem->type = SQLITE_TEXT;
   60829       pMem->enc = SQLITE_UTF8;
   60830       pMem++;
   60831 
   60832 #ifdef SQLITE_DEBUG
   60833       if( pOp->zComment ){
   60834         pMem->flags = MEM_Str|MEM_Term;
   60835         pMem->z = pOp->zComment;
   60836         pMem->n = sqlite3Strlen30(pMem->z);
   60837         pMem->enc = SQLITE_UTF8;
   60838         pMem->type = SQLITE_TEXT;
   60839       }else
   60840 #endif
   60841       {
   60842         pMem->flags = MEM_Null;                       /* Comment */
   60843         pMem->type = SQLITE_NULL;
   60844       }
   60845     }
   60846 
   60847     p->nResColumn = 8 - 4*(p->explain-1);
   60848     p->pResultSet = &p->aMem[1];
   60849     p->rc = SQLITE_OK;
   60850     rc = SQLITE_ROW;
   60851   }
   60852   return rc;
   60853 }
   60854 #endif /* SQLITE_OMIT_EXPLAIN */
   60855 
   60856 #ifdef SQLITE_DEBUG
   60857 /*
   60858 ** Print the SQL that was used to generate a VDBE program.
   60859 */
   60860 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   60861   int nOp = p->nOp;
   60862   VdbeOp *pOp;
   60863   if( nOp<1 ) return;
   60864   pOp = &p->aOp[0];
   60865   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   60866     const char *z = pOp->p4.z;
   60867     while( sqlite3Isspace(*z) ) z++;
   60868     printf("SQL: [%s]\n", z);
   60869   }
   60870 }
   60871 #endif
   60872 
   60873 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   60874 /*
   60875 ** Print an IOTRACE message showing SQL content.
   60876 */
   60877 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   60878   int nOp = p->nOp;
   60879   VdbeOp *pOp;
   60880   if( sqlite3IoTrace==0 ) return;
   60881   if( nOp<1 ) return;
   60882   pOp = &p->aOp[0];
   60883   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   60884     int i, j;
   60885     char z[1000];
   60886     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   60887     for(i=0; sqlite3Isspace(z[i]); i++){}
   60888     for(j=0; z[i]; i++){
   60889       if( sqlite3Isspace(z[i]) ){
   60890         if( z[i-1]!=' ' ){
   60891           z[j++] = ' ';
   60892         }
   60893       }else{
   60894         z[j++] = z[i];
   60895       }
   60896     }
   60897     z[j] = 0;
   60898     sqlite3IoTrace("SQL %s\n", z);
   60899   }
   60900 }
   60901 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   60902 
   60903 /*
   60904 ** Allocate space from a fixed size buffer and return a pointer to
   60905 ** that space.  If insufficient space is available, return NULL.
   60906 **
   60907 ** The pBuf parameter is the initial value of a pointer which will
   60908 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   60909 ** NULL, it means that memory space has already been allocated and that
   60910 ** this routine should not allocate any new memory.  When pBuf is not
   60911 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   60912 ** is NULL.
   60913 **
   60914 ** nByte is the number of bytes of space needed.
   60915 **
   60916 ** *ppFrom points to available space and pEnd points to the end of the
   60917 ** available space.  When space is allocated, *ppFrom is advanced past
   60918 ** the end of the allocated space.
   60919 **
   60920 ** *pnByte is a counter of the number of bytes of space that have failed
   60921 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   60922 ** request, then increment *pnByte by the amount of the request.
   60923 */
   60924 static void *allocSpace(
   60925   void *pBuf,          /* Where return pointer will be stored */
   60926   int nByte,           /* Number of bytes to allocate */
   60927   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   60928   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   60929   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   60930 ){
   60931   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   60932   if( pBuf ) return pBuf;
   60933   nByte = ROUND8(nByte);
   60934   if( &(*ppFrom)[nByte] <= pEnd ){
   60935     pBuf = (void*)*ppFrom;
   60936     *ppFrom += nByte;
   60937   }else{
   60938     *pnByte += nByte;
   60939   }
   60940   return pBuf;
   60941 }
   60942 
   60943 /*
   60944 ** Rewind the VDBE back to the beginning in preparation for
   60945 ** running it.
   60946 */
   60947 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
   60948 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   60949   int i;
   60950 #endif
   60951   assert( p!=0 );
   60952   assert( p->magic==VDBE_MAGIC_INIT );
   60953 
   60954   /* There should be at least one opcode.
   60955   */
   60956   assert( p->nOp>0 );
   60957 
   60958   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   60959   p->magic = VDBE_MAGIC_RUN;
   60960 
   60961 #ifdef SQLITE_DEBUG
   60962   for(i=1; i<p->nMem; i++){
   60963     assert( p->aMem[i].db==p->db );
   60964   }
   60965 #endif
   60966   p->pc = -1;
   60967   p->rc = SQLITE_OK;
   60968   p->errorAction = OE_Abort;
   60969   p->magic = VDBE_MAGIC_RUN;
   60970   p->nChange = 0;
   60971   p->cacheCtr = 1;
   60972   p->minWriteFileFormat = 255;
   60973   p->iStatement = 0;
   60974   p->nFkConstraint = 0;
   60975 #ifdef VDBE_PROFILE
   60976   for(i=0; i<p->nOp; i++){
   60977     p->aOp[i].cnt = 0;
   60978     p->aOp[i].cycles = 0;
   60979   }
   60980 #endif
   60981 }
   60982 
   60983 /*
   60984 ** Prepare a virtual machine for execution for the first time after
   60985 ** creating the virtual machine.  This involves things such
   60986 ** as allocating stack space and initializing the program counter.
   60987 ** After the VDBE has be prepped, it can be executed by one or more
   60988 ** calls to sqlite3VdbeExec().
   60989 **
   60990 ** This function may be called exact once on a each virtual machine.
   60991 ** After this routine is called the VM has been "packaged" and is ready
   60992 ** to run.  After this routine is called, futher calls to
   60993 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
   60994 ** the Vdbe from the Parse object that helped generate it so that the
   60995 ** the Vdbe becomes an independent entity and the Parse object can be
   60996 ** destroyed.
   60997 **
   60998 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
   60999 ** to its initial state after it has been run.
   61000 */
   61001 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   61002   Vdbe *p,                       /* The VDBE */
   61003   Parse *pParse                  /* Parsing context */
   61004 ){
   61005   sqlite3 *db;                   /* The database connection */
   61006   int nVar;                      /* Number of parameters */
   61007   int nMem;                      /* Number of VM memory registers */
   61008   int nCursor;                   /* Number of cursors required */
   61009   int nArg;                      /* Number of arguments in subprograms */
   61010   int nOnce;                     /* Number of OP_Once instructions */
   61011   int n;                         /* Loop counter */
   61012   u8 *zCsr;                      /* Memory available for allocation */
   61013   u8 *zEnd;                      /* First byte past allocated memory */
   61014   int nByte;                     /* How much extra memory is needed */
   61015 
   61016   assert( p!=0 );
   61017   assert( p->nOp>0 );
   61018   assert( pParse!=0 );
   61019   assert( p->magic==VDBE_MAGIC_INIT );
   61020   db = p->db;
   61021   assert( db->mallocFailed==0 );
   61022   nVar = pParse->nVar;
   61023   nMem = pParse->nMem;
   61024   nCursor = pParse->nTab;
   61025   nArg = pParse->nMaxArg;
   61026   nOnce = pParse->nOnce;
   61027   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
   61028 
   61029   /* For each cursor required, also allocate a memory cell. Memory
   61030   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   61031   ** the vdbe program. Instead they are used to allocate space for
   61032   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   61033   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   61034   ** stores the blob of memory associated with cursor 1, etc.
   61035   **
   61036   ** See also: allocateCursor().
   61037   */
   61038   nMem += nCursor;
   61039 
   61040   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   61041   ** an array to marshal SQL function arguments in.
   61042   */
   61043   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
   61044   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
   61045 
   61046   resolveP2Values(p, &nArg);
   61047   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
   61048   if( pParse->explain && nMem<10 ){
   61049     nMem = 10;
   61050   }
   61051   memset(zCsr, 0, zEnd-zCsr);
   61052   zCsr += (zCsr - (u8*)0)&7;
   61053   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   61054   p->expired = 0;
   61055 
   61056   /* Memory for registers, parameters, cursor, etc, is allocated in two
   61057   ** passes.  On the first pass, we try to reuse unused space at the
   61058   ** end of the opcode array.  If we are unable to satisfy all memory
   61059   ** requirements by reusing the opcode array tail, then the second
   61060   ** pass will fill in the rest using a fresh allocation.
   61061   **
   61062   ** This two-pass approach that reuses as much memory as possible from
   61063   ** the leftover space at the end of the opcode array can significantly
   61064   ** reduce the amount of memory held by a prepared statement.
   61065   */
   61066   do {
   61067     nByte = 0;
   61068     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   61069     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   61070     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   61071     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   61072     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   61073                           &zCsr, zEnd, &nByte);
   61074     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
   61075     if( nByte ){
   61076       p->pFree = sqlite3DbMallocZero(db, nByte);
   61077     }
   61078     zCsr = p->pFree;
   61079     zEnd = &zCsr[nByte];
   61080   }while( nByte && !db->mallocFailed );
   61081 
   61082   p->nCursor = (u16)nCursor;
   61083   p->nOnceFlag = nOnce;
   61084   if( p->aVar ){
   61085     p->nVar = (ynVar)nVar;
   61086     for(n=0; n<nVar; n++){
   61087       p->aVar[n].flags = MEM_Null;
   61088       p->aVar[n].db = db;
   61089     }
   61090   }
   61091   if( p->azVar ){
   61092     p->nzVar = pParse->nzVar;
   61093     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
   61094     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
   61095   }
   61096   if( p->aMem ){
   61097     p->aMem--;                      /* aMem[] goes from 1..nMem */
   61098     p->nMem = nMem;                 /*       not from 0..nMem-1 */
   61099     for(n=1; n<=nMem; n++){
   61100       p->aMem[n].flags = MEM_Invalid;
   61101       p->aMem[n].db = db;
   61102     }
   61103   }
   61104   p->explain = pParse->explain;
   61105   sqlite3VdbeRewind(p);
   61106 }
   61107 
   61108 /*
   61109 ** Close a VDBE cursor and release all the resources that cursor
   61110 ** happens to hold.
   61111 */
   61112 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   61113   if( pCx==0 ){
   61114     return;
   61115   }
   61116   sqlite3VdbeSorterClose(p->db, pCx);
   61117   if( pCx->pBt ){
   61118     sqlite3BtreeClose(pCx->pBt);
   61119     /* The pCx->pCursor will be close automatically, if it exists, by
   61120     ** the call above. */
   61121   }else if( pCx->pCursor ){
   61122     sqlite3BtreeCloseCursor(pCx->pCursor);
   61123   }
   61124 #ifndef SQLITE_OMIT_VIRTUALTABLE
   61125   if( pCx->pVtabCursor ){
   61126     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   61127     const sqlite3_module *pModule = pCx->pModule;
   61128     p->inVtabMethod = 1;
   61129     pModule->xClose(pVtabCursor);
   61130     p->inVtabMethod = 0;
   61131   }
   61132 #endif
   61133 }
   61134 
   61135 /*
   61136 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   61137 ** is used, for example, when a trigger sub-program is halted to restore
   61138 ** control to the main program.
   61139 */
   61140 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   61141   Vdbe *v = pFrame->v;
   61142   v->aOnceFlag = pFrame->aOnceFlag;
   61143   v->nOnceFlag = pFrame->nOnceFlag;
   61144   v->aOp = pFrame->aOp;
   61145   v->nOp = pFrame->nOp;
   61146   v->aMem = pFrame->aMem;
   61147   v->nMem = pFrame->nMem;
   61148   v->apCsr = pFrame->apCsr;
   61149   v->nCursor = pFrame->nCursor;
   61150   v->db->lastRowid = pFrame->lastRowid;
   61151   v->nChange = pFrame->nChange;
   61152   return pFrame->pc;
   61153 }
   61154 
   61155 /*
   61156 ** Close all cursors.
   61157 **
   61158 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   61159 ** cell array. This is necessary as the memory cell array may contain
   61160 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   61161 ** open cursors.
   61162 */
   61163 static void closeAllCursors(Vdbe *p){
   61164   if( p->pFrame ){
   61165     VdbeFrame *pFrame;
   61166     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   61167     sqlite3VdbeFrameRestore(pFrame);
   61168   }
   61169   p->pFrame = 0;
   61170   p->nFrame = 0;
   61171 
   61172   if( p->apCsr ){
   61173     int i;
   61174     for(i=0; i<p->nCursor; i++){
   61175       VdbeCursor *pC = p->apCsr[i];
   61176       if( pC ){
   61177         sqlite3VdbeFreeCursor(p, pC);
   61178         p->apCsr[i] = 0;
   61179       }
   61180     }
   61181   }
   61182   if( p->aMem ){
   61183     releaseMemArray(&p->aMem[1], p->nMem);
   61184   }
   61185   while( p->pDelFrame ){
   61186     VdbeFrame *pDel = p->pDelFrame;
   61187     p->pDelFrame = pDel->pParent;
   61188     sqlite3VdbeFrameDelete(pDel);
   61189   }
   61190 }
   61191 
   61192 /*
   61193 ** Clean up the VM after execution.
   61194 **
   61195 ** This routine will automatically close any cursors, lists, and/or
   61196 ** sorters that were left open.  It also deletes the values of
   61197 ** variables in the aVar[] array.
   61198 */
   61199 static void Cleanup(Vdbe *p){
   61200   sqlite3 *db = p->db;
   61201 
   61202 #ifdef SQLITE_DEBUG
   61203   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   61204   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   61205   int i;
   61206   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   61207   if( p->aMem ){
   61208     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
   61209   }
   61210 #endif
   61211 
   61212   sqlite3DbFree(db, p->zErrMsg);
   61213   p->zErrMsg = 0;
   61214   p->pResultSet = 0;
   61215 }
   61216 
   61217 /*
   61218 ** Set the number of result columns that will be returned by this SQL
   61219 ** statement. This is now set at compile time, rather than during
   61220 ** execution of the vdbe program so that sqlite3_column_count() can
   61221 ** be called on an SQL statement before sqlite3_step().
   61222 */
   61223 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   61224   Mem *pColName;
   61225   int n;
   61226   sqlite3 *db = p->db;
   61227 
   61228   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   61229   sqlite3DbFree(db, p->aColName);
   61230   n = nResColumn*COLNAME_N;
   61231   p->nResColumn = (u16)nResColumn;
   61232   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   61233   if( p->aColName==0 ) return;
   61234   while( n-- > 0 ){
   61235     pColName->flags = MEM_Null;
   61236     pColName->db = p->db;
   61237     pColName++;
   61238   }
   61239 }
   61240 
   61241 /*
   61242 ** Set the name of the idx'th column to be returned by the SQL statement.
   61243 ** zName must be a pointer to a nul terminated string.
   61244 **
   61245 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   61246 **
   61247 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   61248 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   61249 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   61250 */
   61251 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   61252   Vdbe *p,                         /* Vdbe being configured */
   61253   int idx,                         /* Index of column zName applies to */
   61254   int var,                         /* One of the COLNAME_* constants */
   61255   const char *zName,               /* Pointer to buffer containing name */
   61256   void (*xDel)(void*)              /* Memory management strategy for zName */
   61257 ){
   61258   int rc;
   61259   Mem *pColName;
   61260   assert( idx<p->nResColumn );
   61261   assert( var<COLNAME_N );
   61262   if( p->db->mallocFailed ){
   61263     assert( !zName || xDel!=SQLITE_DYNAMIC );
   61264     return SQLITE_NOMEM;
   61265   }
   61266   assert( p->aColName!=0 );
   61267   pColName = &(p->aColName[idx+var*p->nResColumn]);
   61268   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   61269   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   61270   return rc;
   61271 }
   61272 
   61273 /*
   61274 ** A read or write transaction may or may not be active on database handle
   61275 ** db. If a transaction is active, commit it. If there is a
   61276 ** write-transaction spanning more than one database file, this routine
   61277 ** takes care of the master journal trickery.
   61278 */
   61279 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   61280   int i;
   61281   int nTrans = 0;  /* Number of databases with an active write-transaction */
   61282   int rc = SQLITE_OK;
   61283   int needXcommit = 0;
   61284 
   61285 #ifdef SQLITE_OMIT_VIRTUALTABLE
   61286   /* With this option, sqlite3VtabSync() is defined to be simply
   61287   ** SQLITE_OK so p is not used.
   61288   */
   61289   UNUSED_PARAMETER(p);
   61290 #endif
   61291 
   61292   /* Before doing anything else, call the xSync() callback for any
   61293   ** virtual module tables written in this transaction. This has to
   61294   ** be done before determining whether a master journal file is
   61295   ** required, as an xSync() callback may add an attached database
   61296   ** to the transaction.
   61297   */
   61298   rc = sqlite3VtabSync(db, &p->zErrMsg);
   61299 
   61300   /* This loop determines (a) if the commit hook should be invoked and
   61301   ** (b) how many database files have open write transactions, not
   61302   ** including the temp database. (b) is important because if more than
   61303   ** one database file has an open write transaction, a master journal
   61304   ** file is required for an atomic commit.
   61305   */
   61306   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61307     Btree *pBt = db->aDb[i].pBt;
   61308     if( sqlite3BtreeIsInTrans(pBt) ){
   61309       needXcommit = 1;
   61310       if( i!=1 ) nTrans++;
   61311       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
   61312     }
   61313   }
   61314   if( rc!=SQLITE_OK ){
   61315     return rc;
   61316   }
   61317 
   61318   /* If there are any write-transactions at all, invoke the commit hook */
   61319   if( needXcommit && db->xCommitCallback ){
   61320     rc = db->xCommitCallback(db->pCommitArg);
   61321     if( rc ){
   61322       return SQLITE_CONSTRAINT;
   61323     }
   61324   }
   61325 
   61326   /* The simple case - no more than one database file (not counting the
   61327   ** TEMP database) has a transaction active.   There is no need for the
   61328   ** master-journal.
   61329   **
   61330   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   61331   ** string, it means the main database is :memory: or a temp file.  In
   61332   ** that case we do not support atomic multi-file commits, so use the
   61333   ** simple case then too.
   61334   */
   61335   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   61336    || nTrans<=1
   61337   ){
   61338     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61339       Btree *pBt = db->aDb[i].pBt;
   61340       if( pBt ){
   61341         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   61342       }
   61343     }
   61344 
   61345     /* Do the commit only if all databases successfully complete phase 1.
   61346     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   61347     ** IO error while deleting or truncating a journal file. It is unlikely,
   61348     ** but could happen. In this case abandon processing and return the error.
   61349     */
   61350     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61351       Btree *pBt = db->aDb[i].pBt;
   61352       if( pBt ){
   61353         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
   61354       }
   61355     }
   61356     if( rc==SQLITE_OK ){
   61357       sqlite3VtabCommit(db);
   61358     }
   61359   }
   61360 
   61361   /* The complex case - There is a multi-file write-transaction active.
   61362   ** This requires a master journal file to ensure the transaction is
   61363   ** committed atomicly.
   61364   */
   61365 #ifndef SQLITE_OMIT_DISKIO
   61366   else{
   61367     sqlite3_vfs *pVfs = db->pVfs;
   61368     int needSync = 0;
   61369     char *zMaster = 0;   /* File-name for the master journal */
   61370     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   61371     sqlite3_file *pMaster = 0;
   61372     i64 offset = 0;
   61373     int res;
   61374     int retryCount = 0;
   61375     int nMainFile;
   61376 
   61377     /* Select a master journal file name */
   61378     nMainFile = sqlite3Strlen30(zMainFile);
   61379     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
   61380     if( zMaster==0 ) return SQLITE_NOMEM;
   61381     do {
   61382       u32 iRandom;
   61383       if( retryCount ){
   61384         if( retryCount>100 ){
   61385           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
   61386           sqlite3OsDelete(pVfs, zMaster, 0);
   61387           break;
   61388         }else if( retryCount==1 ){
   61389           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
   61390         }
   61391       }
   61392       retryCount++;
   61393       sqlite3_randomness(sizeof(iRandom), &iRandom);
   61394       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
   61395                                (iRandom>>8)&0xffffff, iRandom&0xff);
   61396       /* The antipenultimate character of the master journal name must
   61397       ** be "9" to avoid name collisions when using 8+3 filenames. */
   61398       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
   61399       sqlite3FileSuffix3(zMainFile, zMaster);
   61400       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   61401     }while( rc==SQLITE_OK && res );
   61402     if( rc==SQLITE_OK ){
   61403       /* Open the master journal. */
   61404       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   61405           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   61406           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   61407       );
   61408     }
   61409     if( rc!=SQLITE_OK ){
   61410       sqlite3DbFree(db, zMaster);
   61411       return rc;
   61412     }
   61413 
   61414     /* Write the name of each database file in the transaction into the new
   61415     ** master journal file. If an error occurs at this point close
   61416     ** and delete the master journal file. All the individual journal files
   61417     ** still have 'null' as the master journal pointer, so they will roll
   61418     ** back independently if a failure occurs.
   61419     */
   61420     for(i=0; i<db->nDb; i++){
   61421       Btree *pBt = db->aDb[i].pBt;
   61422       if( sqlite3BtreeIsInTrans(pBt) ){
   61423         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   61424         if( zFile==0 ){
   61425           continue;  /* Ignore TEMP and :memory: databases */
   61426         }
   61427         assert( zFile[0]!=0 );
   61428         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   61429           needSync = 1;
   61430         }
   61431         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   61432         offset += sqlite3Strlen30(zFile)+1;
   61433         if( rc!=SQLITE_OK ){
   61434           sqlite3OsCloseFree(pMaster);
   61435           sqlite3OsDelete(pVfs, zMaster, 0);
   61436           sqlite3DbFree(db, zMaster);
   61437           return rc;
   61438         }
   61439       }
   61440     }
   61441 
   61442     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   61443     ** flag is set this is not required.
   61444     */
   61445     if( needSync
   61446      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   61447      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   61448     ){
   61449       sqlite3OsCloseFree(pMaster);
   61450       sqlite3OsDelete(pVfs, zMaster, 0);
   61451       sqlite3DbFree(db, zMaster);
   61452       return rc;
   61453     }
   61454 
   61455     /* Sync all the db files involved in the transaction. The same call
   61456     ** sets the master journal pointer in each individual journal. If
   61457     ** an error occurs here, do not delete the master journal file.
   61458     **
   61459     ** If the error occurs during the first call to
   61460     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   61461     ** master journal file will be orphaned. But we cannot delete it,
   61462     ** in case the master journal file name was written into the journal
   61463     ** file before the failure occurred.
   61464     */
   61465     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61466       Btree *pBt = db->aDb[i].pBt;
   61467       if( pBt ){
   61468         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   61469       }
   61470     }
   61471     sqlite3OsCloseFree(pMaster);
   61472     assert( rc!=SQLITE_BUSY );
   61473     if( rc!=SQLITE_OK ){
   61474       sqlite3DbFree(db, zMaster);
   61475       return rc;
   61476     }
   61477 
   61478     /* Delete the master journal file. This commits the transaction. After
   61479     ** doing this the directory is synced again before any individual
   61480     ** transaction files are deleted.
   61481     */
   61482     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   61483     sqlite3DbFree(db, zMaster);
   61484     zMaster = 0;
   61485     if( rc ){
   61486       return rc;
   61487     }
   61488 
   61489     /* All files and directories have already been synced, so the following
   61490     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   61491     ** deleting or truncating journals. If something goes wrong while
   61492     ** this is happening we don't really care. The integrity of the
   61493     ** transaction is already guaranteed, but some stray 'cold' journals
   61494     ** may be lying around. Returning an error code won't help matters.
   61495     */
   61496     disable_simulated_io_errors();
   61497     sqlite3BeginBenignMalloc();
   61498     for(i=0; i<db->nDb; i++){
   61499       Btree *pBt = db->aDb[i].pBt;
   61500       if( pBt ){
   61501         sqlite3BtreeCommitPhaseTwo(pBt, 1);
   61502       }
   61503     }
   61504     sqlite3EndBenignMalloc();
   61505     enable_simulated_io_errors();
   61506 
   61507     sqlite3VtabCommit(db);
   61508   }
   61509 #endif
   61510 
   61511   return rc;
   61512 }
   61513 
   61514 /*
   61515 ** This routine checks that the sqlite3.activeVdbeCnt count variable
   61516 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   61517 ** currently active. An assertion fails if the two counts do not match.
   61518 ** This is an internal self-check only - it is not an essential processing
   61519 ** step.
   61520 **
   61521 ** This is a no-op if NDEBUG is defined.
   61522 */
   61523 #ifndef NDEBUG
   61524 static void checkActiveVdbeCnt(sqlite3 *db){
   61525   Vdbe *p;
   61526   int cnt = 0;
   61527   int nWrite = 0;
   61528   p = db->pVdbe;
   61529   while( p ){
   61530     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
   61531       cnt++;
   61532       if( p->readOnly==0 ) nWrite++;
   61533     }
   61534     p = p->pNext;
   61535   }
   61536   assert( cnt==db->activeVdbeCnt );
   61537   assert( nWrite==db->writeVdbeCnt );
   61538 }
   61539 #else
   61540 #define checkActiveVdbeCnt(x)
   61541 #endif
   61542 
   61543 /*
   61544 ** If the Vdbe passed as the first argument opened a statement-transaction,
   61545 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   61546 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   61547 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   61548 ** statement transaction is commtted.
   61549 **
   61550 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   61551 ** Otherwise SQLITE_OK.
   61552 */
   61553 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   61554   sqlite3 *const db = p->db;
   61555   int rc = SQLITE_OK;
   61556 
   61557   /* If p->iStatement is greater than zero, then this Vdbe opened a
   61558   ** statement transaction that should be closed here. The only exception
   61559   ** is that an IO error may have occured, causing an emergency rollback.
   61560   ** In this case (db->nStatement==0), and there is nothing to do.
   61561   */
   61562   if( db->nStatement && p->iStatement ){
   61563     int i;
   61564     const int iSavepoint = p->iStatement-1;
   61565 
   61566     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   61567     assert( db->nStatement>0 );
   61568     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   61569 
   61570     for(i=0; i<db->nDb; i++){
   61571       int rc2 = SQLITE_OK;
   61572       Btree *pBt = db->aDb[i].pBt;
   61573       if( pBt ){
   61574         if( eOp==SAVEPOINT_ROLLBACK ){
   61575           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   61576         }
   61577         if( rc2==SQLITE_OK ){
   61578           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   61579         }
   61580         if( rc==SQLITE_OK ){
   61581           rc = rc2;
   61582         }
   61583       }
   61584     }
   61585     db->nStatement--;
   61586     p->iStatement = 0;
   61587 
   61588     if( rc==SQLITE_OK ){
   61589       if( eOp==SAVEPOINT_ROLLBACK ){
   61590         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
   61591       }
   61592       if( rc==SQLITE_OK ){
   61593         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
   61594       }
   61595     }
   61596 
   61597     /* If the statement transaction is being rolled back, also restore the
   61598     ** database handles deferred constraint counter to the value it had when
   61599     ** the statement transaction was opened.  */
   61600     if( eOp==SAVEPOINT_ROLLBACK ){
   61601       db->nDeferredCons = p->nStmtDefCons;
   61602     }
   61603   }
   61604   return rc;
   61605 }
   61606 
   61607 /*
   61608 ** This function is called when a transaction opened by the database
   61609 ** handle associated with the VM passed as an argument is about to be
   61610 ** committed. If there are outstanding deferred foreign key constraint
   61611 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   61612 **
   61613 ** If there are outstanding FK violations and this function returns
   61614 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
   61615 ** an error message to it. Then return SQLITE_ERROR.
   61616 */
   61617 #ifndef SQLITE_OMIT_FOREIGN_KEY
   61618 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   61619   sqlite3 *db = p->db;
   61620   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
   61621     p->rc = SQLITE_CONSTRAINT;
   61622     p->errorAction = OE_Abort;
   61623     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
   61624     return SQLITE_ERROR;
   61625   }
   61626   return SQLITE_OK;
   61627 }
   61628 #endif
   61629 
   61630 /*
   61631 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   61632 ** has made changes and is in autocommit mode, then commit those
   61633 ** changes.  If a rollback is needed, then do the rollback.
   61634 **
   61635 ** This routine is the only way to move the state of a VM from
   61636 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   61637 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   61638 **
   61639 ** Return an error code.  If the commit could not complete because of
   61640 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   61641 ** means the close did not happen and needs to be repeated.
   61642 */
   61643 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   61644   int rc;                         /* Used to store transient return codes */
   61645   sqlite3 *db = p->db;
   61646 
   61647   /* This function contains the logic that determines if a statement or
   61648   ** transaction will be committed or rolled back as a result of the
   61649   ** execution of this virtual machine.
   61650   **
   61651   ** If any of the following errors occur:
   61652   **
   61653   **     SQLITE_NOMEM
   61654   **     SQLITE_IOERR
   61655   **     SQLITE_FULL
   61656   **     SQLITE_INTERRUPT
   61657   **
   61658   ** Then the internal cache might have been left in an inconsistent
   61659   ** state.  We need to rollback the statement transaction, if there is
   61660   ** one, or the complete transaction if there is no statement transaction.
   61661   */
   61662 
   61663   if( p->db->mallocFailed ){
   61664     p->rc = SQLITE_NOMEM;
   61665   }
   61666   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
   61667   closeAllCursors(p);
   61668   if( p->magic!=VDBE_MAGIC_RUN ){
   61669     return SQLITE_OK;
   61670   }
   61671   checkActiveVdbeCnt(db);
   61672 
   61673   /* No commit or rollback needed if the program never started */
   61674   if( p->pc>=0 ){
   61675     int mrc;   /* Primary error code from p->rc */
   61676     int eStatementOp = 0;
   61677     int isSpecialError;            /* Set to true if a 'special' error */
   61678 
   61679     /* Lock all btrees used by the statement */
   61680     sqlite3VdbeEnter(p);
   61681 
   61682     /* Check for one of the special errors */
   61683     mrc = p->rc & 0xff;
   61684     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
   61685     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   61686                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   61687     if( isSpecialError ){
   61688       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   61689       ** no rollback is necessary. Otherwise, at least a savepoint
   61690       ** transaction must be rolled back to restore the database to a
   61691       ** consistent state.
   61692       **
   61693       ** Even if the statement is read-only, it is important to perform
   61694       ** a statement or transaction rollback operation. If the error
   61695       ** occured while writing to the journal, sub-journal or database
   61696       ** file as part of an effort to free up cache space (see function
   61697       ** pagerStress() in pager.c), the rollback is required to restore
   61698       ** the pager to a consistent state.
   61699       */
   61700       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   61701         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   61702           eStatementOp = SAVEPOINT_ROLLBACK;
   61703         }else{
   61704           /* We are forced to roll back the active transaction. Before doing
   61705           ** so, abort any other statements this handle currently has active.
   61706           */
   61707           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61708           sqlite3CloseSavepoints(db);
   61709           db->autoCommit = 1;
   61710         }
   61711       }
   61712     }
   61713 
   61714     /* Check for immediate foreign key violations. */
   61715     if( p->rc==SQLITE_OK ){
   61716       sqlite3VdbeCheckFk(p, 0);
   61717     }
   61718 
   61719     /* If the auto-commit flag is set and this is the only active writer
   61720     ** VM, then we do either a commit or rollback of the current transaction.
   61721     **
   61722     ** Note: This block also runs if one of the special errors handled
   61723     ** above has occurred.
   61724     */
   61725     if( !sqlite3VtabInSync(db)
   61726      && db->autoCommit
   61727      && db->writeVdbeCnt==(p->readOnly==0)
   61728     ){
   61729       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   61730         rc = sqlite3VdbeCheckFk(p, 1);
   61731         if( rc!=SQLITE_OK ){
   61732           if( NEVER(p->readOnly) ){
   61733             sqlite3VdbeLeave(p);
   61734             return SQLITE_ERROR;
   61735           }
   61736           rc = SQLITE_CONSTRAINT;
   61737         }else{
   61738           /* The auto-commit flag is true, the vdbe program was successful
   61739           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   61740           ** key constraints to hold up the transaction. This means a commit
   61741           ** is required. */
   61742           rc = vdbeCommit(db, p);
   61743         }
   61744         if( rc==SQLITE_BUSY && p->readOnly ){
   61745           sqlite3VdbeLeave(p);
   61746           return SQLITE_BUSY;
   61747         }else if( rc!=SQLITE_OK ){
   61748           p->rc = rc;
   61749           sqlite3RollbackAll(db, SQLITE_OK);
   61750         }else{
   61751           db->nDeferredCons = 0;
   61752           sqlite3CommitInternalChanges(db);
   61753         }
   61754       }else{
   61755         sqlite3RollbackAll(db, SQLITE_OK);
   61756       }
   61757       db->nStatement = 0;
   61758     }else if( eStatementOp==0 ){
   61759       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   61760         eStatementOp = SAVEPOINT_RELEASE;
   61761       }else if( p->errorAction==OE_Abort ){
   61762         eStatementOp = SAVEPOINT_ROLLBACK;
   61763       }else{
   61764         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61765         sqlite3CloseSavepoints(db);
   61766         db->autoCommit = 1;
   61767       }
   61768     }
   61769 
   61770     /* If eStatementOp is non-zero, then a statement transaction needs to
   61771     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   61772     ** do so. If this operation returns an error, and the current statement
   61773     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   61774     ** current statement error code.
   61775     */
   61776     if( eStatementOp ){
   61777       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   61778       if( rc ){
   61779         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
   61780           p->rc = rc;
   61781           sqlite3DbFree(db, p->zErrMsg);
   61782           p->zErrMsg = 0;
   61783         }
   61784         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61785         sqlite3CloseSavepoints(db);
   61786         db->autoCommit = 1;
   61787       }
   61788     }
   61789 
   61790     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   61791     ** has been rolled back, update the database connection change-counter.
   61792     */
   61793     if( p->changeCntOn ){
   61794       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   61795         sqlite3VdbeSetChanges(db, p->nChange);
   61796       }else{
   61797         sqlite3VdbeSetChanges(db, 0);
   61798       }
   61799       p->nChange = 0;
   61800     }
   61801 
   61802     /* Release the locks */
   61803     sqlite3VdbeLeave(p);
   61804   }
   61805 
   61806   /* We have successfully halted and closed the VM.  Record this fact. */
   61807   if( p->pc>=0 ){
   61808     db->activeVdbeCnt--;
   61809     if( !p->readOnly ){
   61810       db->writeVdbeCnt--;
   61811     }
   61812     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
   61813   }
   61814   p->magic = VDBE_MAGIC_HALT;
   61815   checkActiveVdbeCnt(db);
   61816   if( p->db->mallocFailed ){
   61817     p->rc = SQLITE_NOMEM;
   61818   }
   61819 
   61820   /* If the auto-commit flag is set to true, then any locks that were held
   61821   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   61822   ** to invoke any required unlock-notify callbacks.
   61823   */
   61824   if( db->autoCommit ){
   61825     sqlite3ConnectionUnlocked(db);
   61826   }
   61827 
   61828   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
   61829   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
   61830 }
   61831 
   61832 
   61833 /*
   61834 ** Each VDBE holds the result of the most recent sqlite3_step() call
   61835 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   61836 */
   61837 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   61838   p->rc = SQLITE_OK;
   61839 }
   61840 
   61841 /*
   61842 ** Copy the error code and error message belonging to the VDBE passed
   61843 ** as the first argument to its database handle (so that they will be
   61844 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
   61845 **
   61846 ** This function does not clear the VDBE error code or message, just
   61847 ** copies them to the database handle.
   61848 */
   61849 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
   61850   sqlite3 *db = p->db;
   61851   int rc = p->rc;
   61852   if( p->zErrMsg ){
   61853     u8 mallocFailed = db->mallocFailed;
   61854     sqlite3BeginBenignMalloc();
   61855     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   61856     sqlite3EndBenignMalloc();
   61857     db->mallocFailed = mallocFailed;
   61858     db->errCode = rc;
   61859   }else{
   61860     sqlite3Error(db, rc, 0);
   61861   }
   61862   return rc;
   61863 }
   61864 
   61865 /*
   61866 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   61867 ** Write any error messages into *pzErrMsg.  Return the result code.
   61868 **
   61869 ** After this routine is run, the VDBE should be ready to be executed
   61870 ** again.
   61871 **
   61872 ** To look at it another way, this routine resets the state of the
   61873 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   61874 ** VDBE_MAGIC_INIT.
   61875 */
   61876 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   61877   sqlite3 *db;
   61878   db = p->db;
   61879 
   61880   /* If the VM did not run to completion or if it encountered an
   61881   ** error, then it might not have been halted properly.  So halt
   61882   ** it now.
   61883   */
   61884   sqlite3VdbeHalt(p);
   61885 
   61886   /* If the VDBE has be run even partially, then transfer the error code
   61887   ** and error message from the VDBE into the main database structure.  But
   61888   ** if the VDBE has just been set to run but has not actually executed any
   61889   ** instructions yet, leave the main database error information unchanged.
   61890   */
   61891   if( p->pc>=0 ){
   61892     sqlite3VdbeTransferError(p);
   61893     sqlite3DbFree(db, p->zErrMsg);
   61894     p->zErrMsg = 0;
   61895     if( p->runOnlyOnce ) p->expired = 1;
   61896   }else if( p->rc && p->expired ){
   61897     /* The expired flag was set on the VDBE before the first call
   61898     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   61899     ** called), set the database error in this case as well.
   61900     */
   61901     sqlite3Error(db, p->rc, 0);
   61902     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   61903     sqlite3DbFree(db, p->zErrMsg);
   61904     p->zErrMsg = 0;
   61905   }
   61906 
   61907   /* Reclaim all memory used by the VDBE
   61908   */
   61909   Cleanup(p);
   61910 
   61911   /* Save profiling information from this VDBE run.
   61912   */
   61913 #ifdef VDBE_PROFILE
   61914   {
   61915     FILE *out = fopen("vdbe_profile.out", "a");
   61916     if( out ){
   61917       int i;
   61918       fprintf(out, "---- ");
   61919       for(i=0; i<p->nOp; i++){
   61920         fprintf(out, "%02x", p->aOp[i].opcode);
   61921       }
   61922       fprintf(out, "\n");
   61923       for(i=0; i<p->nOp; i++){
   61924         fprintf(out, "%6d %10lld %8lld ",
   61925            p->aOp[i].cnt,
   61926            p->aOp[i].cycles,
   61927            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   61928         );
   61929         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   61930       }
   61931       fclose(out);
   61932     }
   61933   }
   61934 #endif
   61935   p->magic = VDBE_MAGIC_INIT;
   61936   return p->rc & db->errMask;
   61937 }
   61938 
   61939 /*
   61940 ** Clean up and delete a VDBE after execution.  Return an integer which is
   61941 ** the result code.  Write any error message text into *pzErrMsg.
   61942 */
   61943 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   61944   int rc = SQLITE_OK;
   61945   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   61946     rc = sqlite3VdbeReset(p);
   61947     assert( (rc & p->db->errMask)==rc );
   61948   }
   61949   sqlite3VdbeDelete(p);
   61950   return rc;
   61951 }
   61952 
   61953 /*
   61954 ** Call the destructor for each auxdata entry in pVdbeFunc for which
   61955 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
   61956 ** are always destroyed.  To destroy all auxdata entries, call this
   61957 ** routine with mask==0.
   61958 */
   61959 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
   61960   int i;
   61961   for(i=0; i<pVdbeFunc->nAux; i++){
   61962     struct AuxData *pAux = &pVdbeFunc->apAux[i];
   61963     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
   61964       if( pAux->xDelete ){
   61965         pAux->xDelete(pAux->pAux);
   61966       }
   61967       pAux->pAux = 0;
   61968     }
   61969   }
   61970 }
   61971 
   61972 /*
   61973 ** Free all memory associated with the Vdbe passed as the second argument.
   61974 ** The difference between this function and sqlite3VdbeDelete() is that
   61975 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   61976 ** the database connection.
   61977 */
   61978 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
   61979   SubProgram *pSub, *pNext;
   61980   int i;
   61981   assert( p->db==0 || p->db==db );
   61982   releaseMemArray(p->aVar, p->nVar);
   61983   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   61984   for(pSub=p->pProgram; pSub; pSub=pNext){
   61985     pNext = pSub->pNext;
   61986     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   61987     sqlite3DbFree(db, pSub);
   61988   }
   61989   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
   61990   vdbeFreeOpArray(db, p->aOp, p->nOp);
   61991   sqlite3DbFree(db, p->aLabel);
   61992   sqlite3DbFree(db, p->aColName);
   61993   sqlite3DbFree(db, p->zSql);
   61994   sqlite3DbFree(db, p->pFree);
   61995 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   61996   sqlite3DbFree(db, p->zExplain);
   61997   sqlite3DbFree(db, p->pExplain);
   61998 #endif
   61999   sqlite3DbFree(db, p);
   62000 }
   62001 
   62002 /*
   62003 ** Delete an entire VDBE.
   62004 */
   62005 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   62006   sqlite3 *db;
   62007 
   62008   if( NEVER(p==0) ) return;
   62009   db = p->db;
   62010   if( p->pPrev ){
   62011     p->pPrev->pNext = p->pNext;
   62012   }else{
   62013     assert( db->pVdbe==p );
   62014     db->pVdbe = p->pNext;
   62015   }
   62016   if( p->pNext ){
   62017     p->pNext->pPrev = p->pPrev;
   62018   }
   62019   p->magic = VDBE_MAGIC_DEAD;
   62020   p->db = 0;
   62021   sqlite3VdbeDeleteObject(db, p);
   62022 }
   62023 
   62024 /*
   62025 ** Make sure the cursor p is ready to read or write the row to which it
   62026 ** was last positioned.  Return an error code if an OOM fault or I/O error
   62027 ** prevents us from positioning the cursor to its correct position.
   62028 **
   62029 ** If a MoveTo operation is pending on the given cursor, then do that
   62030 ** MoveTo now.  If no move is pending, check to see if the row has been
   62031 ** deleted out from under the cursor and if it has, mark the row as
   62032 ** a NULL row.
   62033 **
   62034 ** If the cursor is already pointing to the correct row and that row has
   62035 ** not been deleted out from under the cursor, then this routine is a no-op.
   62036 */
   62037 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   62038   if( p->deferredMoveto ){
   62039     int res, rc;
   62040 #ifdef SQLITE_TEST
   62041     extern int sqlite3_search_count;
   62042 #endif
   62043     assert( p->isTable );
   62044     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   62045     if( rc ) return rc;
   62046     p->lastRowid = p->movetoTarget;
   62047     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   62048     p->rowidIsValid = 1;
   62049 #ifdef SQLITE_TEST
   62050     sqlite3_search_count++;
   62051 #endif
   62052     p->deferredMoveto = 0;
   62053     p->cacheStatus = CACHE_STALE;
   62054   }else if( ALWAYS(p->pCursor) ){
   62055     int hasMoved;
   62056     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   62057     if( rc ) return rc;
   62058     if( hasMoved ){
   62059       p->cacheStatus = CACHE_STALE;
   62060       p->nullRow = 1;
   62061     }
   62062   }
   62063   return SQLITE_OK;
   62064 }
   62065 
   62066 /*
   62067 ** The following functions:
   62068 **
   62069 ** sqlite3VdbeSerialType()
   62070 ** sqlite3VdbeSerialTypeLen()
   62071 ** sqlite3VdbeSerialLen()
   62072 ** sqlite3VdbeSerialPut()
   62073 ** sqlite3VdbeSerialGet()
   62074 **
   62075 ** encapsulate the code that serializes values for storage in SQLite
   62076 ** data and index records. Each serialized value consists of a
   62077 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   62078 ** integer, stored as a varint.
   62079 **
   62080 ** In an SQLite index record, the serial type is stored directly before
   62081 ** the blob of data that it corresponds to. In a table record, all serial
   62082 ** types are stored at the start of the record, and the blobs of data at
   62083 ** the end. Hence these functions allow the caller to handle the
   62084 ** serial-type and data blob seperately.
   62085 **
   62086 ** The following table describes the various storage classes for data:
   62087 **
   62088 **   serial type        bytes of data      type
   62089 **   --------------     ---------------    ---------------
   62090 **      0                     0            NULL
   62091 **      1                     1            signed integer
   62092 **      2                     2            signed integer
   62093 **      3                     3            signed integer
   62094 **      4                     4            signed integer
   62095 **      5                     6            signed integer
   62096 **      6                     8            signed integer
   62097 **      7                     8            IEEE float
   62098 **      8                     0            Integer constant 0
   62099 **      9                     0            Integer constant 1
   62100 **     10,11                               reserved for expansion
   62101 **    N>=12 and even       (N-12)/2        BLOB
   62102 **    N>=13 and odd        (N-13)/2        text
   62103 **
   62104 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   62105 ** of SQLite will not understand those serial types.
   62106 */
   62107 
   62108 /*
   62109 ** Return the serial-type for the value stored in pMem.
   62110 */
   62111 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   62112   int flags = pMem->flags;
   62113   int n;
   62114 
   62115   if( flags&MEM_Null ){
   62116     return 0;
   62117   }
   62118   if( flags&MEM_Int ){
   62119     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   62120 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   62121     i64 i = pMem->u.i;
   62122     u64 u;
   62123     if( file_format>=4 && (i&1)==i ){
   62124       return 8+(u32)i;
   62125     }
   62126     if( i<0 ){
   62127       if( i<(-MAX_6BYTE) ) return 6;
   62128       /* Previous test prevents:  u = -(-9223372036854775808) */
   62129       u = -i;
   62130     }else{
   62131       u = i;
   62132     }
   62133     if( u<=127 ) return 1;
   62134     if( u<=32767 ) return 2;
   62135     if( u<=8388607 ) return 3;
   62136     if( u<=2147483647 ) return 4;
   62137     if( u<=MAX_6BYTE ) return 5;
   62138     return 6;
   62139   }
   62140   if( flags&MEM_Real ){
   62141     return 7;
   62142   }
   62143   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   62144   n = pMem->n;
   62145   if( flags & MEM_Zero ){
   62146     n += pMem->u.nZero;
   62147   }
   62148   assert( n>=0 );
   62149   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   62150 }
   62151 
   62152 /*
   62153 ** Return the length of the data corresponding to the supplied serial-type.
   62154 */
   62155 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   62156   if( serial_type>=12 ){
   62157     return (serial_type-12)/2;
   62158   }else{
   62159     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   62160     return aSize[serial_type];
   62161   }
   62162 }
   62163 
   62164 /*
   62165 ** If we are on an architecture with mixed-endian floating
   62166 ** points (ex: ARM7) then swap the lower 4 bytes with the
   62167 ** upper 4 bytes.  Return the result.
   62168 **
   62169 ** For most architectures, this is a no-op.
   62170 **
   62171 ** (later):  It is reported to me that the mixed-endian problem
   62172 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   62173 ** that early versions of GCC stored the two words of a 64-bit
   62174 ** float in the wrong order.  And that error has been propagated
   62175 ** ever since.  The blame is not necessarily with GCC, though.
   62176 ** GCC might have just copying the problem from a prior compiler.
   62177 ** I am also told that newer versions of GCC that follow a different
   62178 ** ABI get the byte order right.
   62179 **
   62180 ** Developers using SQLite on an ARM7 should compile and run their
   62181 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   62182 ** enabled, some asserts below will ensure that the byte order of
   62183 ** floating point values is correct.
   62184 **
   62185 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   62186 ** and has send his findings to the SQLite developers.  Frank
   62187 ** writes that some Linux kernels offer floating point hardware
   62188 ** emulation that uses only 32-bit mantissas instead of a full
   62189 ** 48-bits as required by the IEEE standard.  (This is the
   62190 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   62191 ** byte swapping becomes very complicated.  To avoid problems,
   62192 ** the necessary byte swapping is carried out using a 64-bit integer
   62193 ** rather than a 64-bit float.  Frank assures us that the code here
   62194 ** works for him.  We, the developers, have no way to independently
   62195 ** verify this, but Frank seems to know what he is talking about
   62196 ** so we trust him.
   62197 */
   62198 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   62199 static u64 floatSwap(u64 in){
   62200   union {
   62201     u64 r;
   62202     u32 i[2];
   62203   } u;
   62204   u32 t;
   62205 
   62206   u.r = in;
   62207   t = u.i[0];
   62208   u.i[0] = u.i[1];
   62209   u.i[1] = t;
   62210   return u.r;
   62211 }
   62212 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   62213 #else
   62214 # define swapMixedEndianFloat(X)
   62215 #endif
   62216 
   62217 /*
   62218 ** Write the serialized data blob for the value stored in pMem into
   62219 ** buf. It is assumed that the caller has allocated sufficient space.
   62220 ** Return the number of bytes written.
   62221 **
   62222 ** nBuf is the amount of space left in buf[].  nBuf must always be
   62223 ** large enough to hold the entire field.  Except, if the field is
   62224 ** a blob with a zero-filled tail, then buf[] might be just the right
   62225 ** size to hold everything except for the zero-filled tail.  If buf[]
   62226 ** is only big enough to hold the non-zero prefix, then only write that
   62227 ** prefix into buf[].  But if buf[] is large enough to hold both the
   62228 ** prefix and the tail then write the prefix and set the tail to all
   62229 ** zeros.
   62230 **
   62231 ** Return the number of bytes actually written into buf[].  The number
   62232 ** of bytes in the zero-filled tail is included in the return value only
   62233 ** if those bytes were zeroed in buf[].
   62234 */
   62235 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
   62236   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
   62237   u32 len;
   62238 
   62239   /* Integer and Real */
   62240   if( serial_type<=7 && serial_type>0 ){
   62241     u64 v;
   62242     u32 i;
   62243     if( serial_type==7 ){
   62244       assert( sizeof(v)==sizeof(pMem->r) );
   62245       memcpy(&v, &pMem->r, sizeof(v));
   62246       swapMixedEndianFloat(v);
   62247     }else{
   62248       v = pMem->u.i;
   62249     }
   62250     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   62251     assert( len<=(u32)nBuf );
   62252     while( i-- ){
   62253       buf[i] = (u8)(v&0xFF);
   62254       v >>= 8;
   62255     }
   62256     return len;
   62257   }
   62258 
   62259   /* String or blob */
   62260   if( serial_type>=12 ){
   62261     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   62262              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   62263     assert( pMem->n<=nBuf );
   62264     len = pMem->n;
   62265     memcpy(buf, pMem->z, len);
   62266     if( pMem->flags & MEM_Zero ){
   62267       len += pMem->u.nZero;
   62268       assert( nBuf>=0 );
   62269       if( len > (u32)nBuf ){
   62270         len = (u32)nBuf;
   62271       }
   62272       memset(&buf[pMem->n], 0, len-pMem->n);
   62273     }
   62274     return len;
   62275   }
   62276 
   62277   /* NULL or constants 0 or 1 */
   62278   return 0;
   62279 }
   62280 
   62281 /*
   62282 ** Deserialize the data blob pointed to by buf as serial type serial_type
   62283 ** and store the result in pMem.  Return the number of bytes read.
   62284 */
   62285 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   62286   const unsigned char *buf,     /* Buffer to deserialize from */
   62287   u32 serial_type,              /* Serial type to deserialize */
   62288   Mem *pMem                     /* Memory cell to write value into */
   62289 ){
   62290   switch( serial_type ){
   62291     case 10:   /* Reserved for future use */
   62292     case 11:   /* Reserved for future use */
   62293     case 0: {  /* NULL */
   62294       pMem->flags = MEM_Null;
   62295       break;
   62296     }
   62297     case 1: { /* 1-byte signed integer */
   62298       pMem->u.i = (signed char)buf[0];
   62299       pMem->flags = MEM_Int;
   62300       return 1;
   62301     }
   62302     case 2: { /* 2-byte signed integer */
   62303       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
   62304       pMem->flags = MEM_Int;
   62305       return 2;
   62306     }
   62307     case 3: { /* 3-byte signed integer */
   62308       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
   62309       pMem->flags = MEM_Int;
   62310       return 3;
   62311     }
   62312     case 4: { /* 4-byte signed integer */
   62313       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   62314       pMem->flags = MEM_Int;
   62315       return 4;
   62316     }
   62317     case 5: { /* 6-byte signed integer */
   62318       u64 x = (((signed char)buf[0])<<8) | buf[1];
   62319       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
   62320       x = (x<<32) | y;
   62321       pMem->u.i = *(i64*)&x;
   62322       pMem->flags = MEM_Int;
   62323       return 6;
   62324     }
   62325     case 6:   /* 8-byte signed integer */
   62326     case 7: { /* IEEE floating point */
   62327       u64 x;
   62328       u32 y;
   62329 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   62330       /* Verify that integers and floating point values use the same
   62331       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   62332       ** defined that 64-bit floating point values really are mixed
   62333       ** endian.
   62334       */
   62335       static const u64 t1 = ((u64)0x3ff00000)<<32;
   62336       static const double r1 = 1.0;
   62337       u64 t2 = t1;
   62338       swapMixedEndianFloat(t2);
   62339       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   62340 #endif
   62341 
   62342       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   62343       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
   62344       x = (x<<32) | y;
   62345       if( serial_type==6 ){
   62346         pMem->u.i = *(i64*)&x;
   62347         pMem->flags = MEM_Int;
   62348       }else{
   62349         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   62350         swapMixedEndianFloat(x);
   62351         memcpy(&pMem->r, &x, sizeof(x));
   62352         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   62353       }
   62354       return 8;
   62355     }
   62356     case 8:    /* Integer 0 */
   62357     case 9: {  /* Integer 1 */
   62358       pMem->u.i = serial_type-8;
   62359       pMem->flags = MEM_Int;
   62360       return 0;
   62361     }
   62362     default: {
   62363       u32 len = (serial_type-12)/2;
   62364       pMem->z = (char *)buf;
   62365       pMem->n = len;
   62366       pMem->xDel = 0;
   62367       if( serial_type&0x01 ){
   62368         pMem->flags = MEM_Str | MEM_Ephem;
   62369       }else{
   62370         pMem->flags = MEM_Blob | MEM_Ephem;
   62371       }
   62372       return len;
   62373     }
   62374   }
   62375   return 0;
   62376 }
   62377 
   62378 /*
   62379 ** This routine is used to allocate sufficient space for an UnpackedRecord
   62380 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
   62381 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
   62382 **
   62383 ** The space is either allocated using sqlite3DbMallocRaw() or from within
   62384 ** the unaligned buffer passed via the second and third arguments (presumably
   62385 ** stack space). If the former, then *ppFree is set to a pointer that should
   62386 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
   62387 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
   62388 ** before returning.
   62389 **
   62390 ** If an OOM error occurs, NULL is returned.
   62391 */
   62392 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
   62393   KeyInfo *pKeyInfo,              /* Description of the record */
   62394   char *pSpace,                   /* Unaligned space available */
   62395   int szSpace,                    /* Size of pSpace[] in bytes */
   62396   char **ppFree                   /* OUT: Caller should free this pointer */
   62397 ){
   62398   UnpackedRecord *p;              /* Unpacked record to return */
   62399   int nOff;                       /* Increment pSpace by nOff to align it */
   62400   int nByte;                      /* Number of bytes required for *p */
   62401 
   62402   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
   62403   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   62404   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   62405   */
   62406   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   62407   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   62408   if( nByte>szSpace+nOff ){
   62409     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   62410     *ppFree = (char *)p;
   62411     if( !p ) return 0;
   62412   }else{
   62413     p = (UnpackedRecord*)&pSpace[nOff];
   62414     *ppFree = 0;
   62415   }
   62416 
   62417   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   62418   p->pKeyInfo = pKeyInfo;
   62419   p->nField = pKeyInfo->nField + 1;
   62420   return p;
   62421 }
   62422 
   62423 /*
   62424 ** Given the nKey-byte encoding of a record in pKey[], populate the
   62425 ** UnpackedRecord structure indicated by the fourth argument with the
   62426 ** contents of the decoded record.
   62427 */
   62428 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   62429   KeyInfo *pKeyInfo,     /* Information about the record format */
   62430   int nKey,              /* Size of the binary record */
   62431   const void *pKey,      /* The binary record */
   62432   UnpackedRecord *p      /* Populate this structure before returning. */
   62433 ){
   62434   const unsigned char *aKey = (const unsigned char *)pKey;
   62435   int d;
   62436   u32 idx;                        /* Offset in aKey[] to read from */
   62437   u16 u;                          /* Unsigned loop counter */
   62438   u32 szHdr;
   62439   Mem *pMem = p->aMem;
   62440 
   62441   p->flags = 0;
   62442   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   62443   idx = getVarint32(aKey, szHdr);
   62444   d = szHdr;
   62445   u = 0;
   62446   while( idx<szHdr && u<p->nField && d<=nKey ){
   62447     u32 serial_type;
   62448 
   62449     idx += getVarint32(&aKey[idx], serial_type);
   62450     pMem->enc = pKeyInfo->enc;
   62451     pMem->db = pKeyInfo->db;
   62452     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
   62453     pMem->zMalloc = 0;
   62454     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   62455     pMem++;
   62456     u++;
   62457   }
   62458   assert( u<=pKeyInfo->nField + 1 );
   62459   p->nField = u;
   62460 }
   62461 
   62462 /*
   62463 ** This function compares the two table rows or index records
   62464 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   62465 ** or positive integer if key1 is less than, equal to or
   62466 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   62467 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   62468 ** key must be a parsed key such as obtained from
   62469 ** sqlite3VdbeParseRecord.
   62470 **
   62471 ** Key1 and Key2 do not have to contain the same number of fields.
   62472 ** The key with fewer fields is usually compares less than the
   62473 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
   62474 ** and the common prefixes are equal, then key1 is less than key2.
   62475 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
   62476 ** equal, then the keys are considered to be equal and
   62477 ** the parts beyond the common prefix are ignored.
   62478 */
   62479 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   62480   int nKey1, const void *pKey1, /* Left key */
   62481   UnpackedRecord *pPKey2        /* Right key */
   62482 ){
   62483   int d1;            /* Offset into aKey[] of next data element */
   62484   u32 idx1;          /* Offset into aKey[] of next header element */
   62485   u32 szHdr1;        /* Number of bytes in header */
   62486   int i = 0;
   62487   int nField;
   62488   int rc = 0;
   62489   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   62490   KeyInfo *pKeyInfo;
   62491   Mem mem1;
   62492 
   62493   pKeyInfo = pPKey2->pKeyInfo;
   62494   mem1.enc = pKeyInfo->enc;
   62495   mem1.db = pKeyInfo->db;
   62496   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   62497   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   62498 
   62499   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   62500   ** We could initialize it, as shown here, to silence those complaints.
   62501   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   62502   ** the unnecessary initialization has a measurable negative performance
   62503   ** impact, since this routine is a very high runner.  And so, we choose
   62504   ** to ignore the compiler warnings and leave this variable uninitialized.
   62505   */
   62506   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   62507 
   62508   idx1 = getVarint32(aKey1, szHdr1);
   62509   d1 = szHdr1;
   62510   nField = pKeyInfo->nField;
   62511   while( idx1<szHdr1 && i<pPKey2->nField ){
   62512     u32 serial_type1;
   62513 
   62514     /* Read the serial types for the next element in each key. */
   62515     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   62516     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
   62517 
   62518     /* Extract the values to be compared.
   62519     */
   62520     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   62521 
   62522     /* Do the comparison
   62523     */
   62524     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
   62525                            i<nField ? pKeyInfo->aColl[i] : 0);
   62526     if( rc!=0 ){
   62527       assert( mem1.zMalloc==0 );  /* See comment below */
   62528 
   62529       /* Invert the result if we are using DESC sort order. */
   62530       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
   62531         rc = -rc;
   62532       }
   62533 
   62534       /* If the PREFIX_SEARCH flag is set and all fields except the final
   62535       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
   62536       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
   62537       ** This is used by the OP_IsUnique opcode.
   62538       */
   62539       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
   62540         assert( idx1==szHdr1 && rc );
   62541         assert( mem1.flags & MEM_Int );
   62542         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
   62543         pPKey2->rowid = mem1.u.i;
   62544       }
   62545 
   62546       return rc;
   62547     }
   62548     i++;
   62549   }
   62550 
   62551   /* No memory allocation is ever used on mem1.  Prove this using
   62552   ** the following assert().  If the assert() fails, it indicates a
   62553   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   62554   */
   62555   assert( mem1.zMalloc==0 );
   62556 
   62557   /* rc==0 here means that one of the keys ran out of fields and
   62558   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
   62559   ** flag is set, then break the tie by treating key2 as larger.
   62560   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
   62561   ** are considered to be equal.  Otherwise, the longer key is the
   62562   ** larger.  As it happens, the pPKey2 will always be the longer
   62563   ** if there is a difference.
   62564   */
   62565   assert( rc==0 );
   62566   if( pPKey2->flags & UNPACKED_INCRKEY ){
   62567     rc = -1;
   62568   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
   62569     /* Leave rc==0 */
   62570   }else if( idx1<szHdr1 ){
   62571     rc = 1;
   62572   }
   62573   return rc;
   62574 }
   62575 
   62576 
   62577 /*
   62578 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   62579 ** Read the rowid (the last field in the record) and store it in *rowid.
   62580 ** Return SQLITE_OK if everything works, or an error code otherwise.
   62581 **
   62582 ** pCur might be pointing to text obtained from a corrupt database file.
   62583 ** So the content cannot be trusted.  Do appropriate checks on the content.
   62584 */
   62585 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   62586   i64 nCellKey = 0;
   62587   int rc;
   62588   u32 szHdr;        /* Size of the header */
   62589   u32 typeRowid;    /* Serial type of the rowid */
   62590   u32 lenRowid;     /* Size of the rowid */
   62591   Mem m, v;
   62592 
   62593   UNUSED_PARAMETER(db);
   62594 
   62595   /* Get the size of the index entry.  Only indices entries of less
   62596   ** than 2GiB are support - anything large must be database corruption.
   62597   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   62598   ** this code can safely assume that nCellKey is 32-bits
   62599   */
   62600   assert( sqlite3BtreeCursorIsValid(pCur) );
   62601   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   62602   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   62603   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   62604 
   62605   /* Read in the complete content of the index entry */
   62606   memset(&m, 0, sizeof(m));
   62607   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
   62608   if( rc ){
   62609     return rc;
   62610   }
   62611 
   62612   /* The index entry must begin with a header size */
   62613   (void)getVarint32((u8*)m.z, szHdr);
   62614   testcase( szHdr==3 );
   62615   testcase( szHdr==m.n );
   62616   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   62617     goto idx_rowid_corruption;
   62618   }
   62619 
   62620   /* The last field of the index should be an integer - the ROWID.
   62621   ** Verify that the last entry really is an integer. */
   62622   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   62623   testcase( typeRowid==1 );
   62624   testcase( typeRowid==2 );
   62625   testcase( typeRowid==3 );
   62626   testcase( typeRowid==4 );
   62627   testcase( typeRowid==5 );
   62628   testcase( typeRowid==6 );
   62629   testcase( typeRowid==8 );
   62630   testcase( typeRowid==9 );
   62631   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   62632     goto idx_rowid_corruption;
   62633   }
   62634   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   62635   testcase( (u32)m.n==szHdr+lenRowid );
   62636   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   62637     goto idx_rowid_corruption;
   62638   }
   62639 
   62640   /* Fetch the integer off the end of the index record */
   62641   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   62642   *rowid = v.u.i;
   62643   sqlite3VdbeMemRelease(&m);
   62644   return SQLITE_OK;
   62645 
   62646   /* Jump here if database corruption is detected after m has been
   62647   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   62648 idx_rowid_corruption:
   62649   testcase( m.zMalloc!=0 );
   62650   sqlite3VdbeMemRelease(&m);
   62651   return SQLITE_CORRUPT_BKPT;
   62652 }
   62653 
   62654 /*
   62655 ** Compare the key of the index entry that cursor pC is pointing to against
   62656 ** the key string in pUnpacked.  Write into *pRes a number
   62657 ** that is negative, zero, or positive if pC is less than, equal to,
   62658 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   62659 **
   62660 ** pUnpacked is either created without a rowid or is truncated so that it
   62661 ** omits the rowid at the end.  The rowid at the end of the index entry
   62662 ** is ignored as well.  Hence, this routine only compares the prefixes
   62663 ** of the keys prior to the final rowid, not the entire key.
   62664 */
   62665 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   62666   VdbeCursor *pC,             /* The cursor to compare against */
   62667   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
   62668   int *res                    /* Write the comparison result here */
   62669 ){
   62670   i64 nCellKey = 0;
   62671   int rc;
   62672   BtCursor *pCur = pC->pCursor;
   62673   Mem m;
   62674 
   62675   assert( sqlite3BtreeCursorIsValid(pCur) );
   62676   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   62677   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   62678   /* nCellKey will always be between 0 and 0xffffffff because of the say
   62679   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   62680   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   62681     *res = 0;
   62682     return SQLITE_CORRUPT_BKPT;
   62683   }
   62684   memset(&m, 0, sizeof(m));
   62685   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
   62686   if( rc ){
   62687     return rc;
   62688   }
   62689   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
   62690   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
   62691   sqlite3VdbeMemRelease(&m);
   62692   return SQLITE_OK;
   62693 }
   62694 
   62695 /*
   62696 ** This routine sets the value to be returned by subsequent calls to
   62697 ** sqlite3_changes() on the database handle 'db'.
   62698 */
   62699 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   62700   assert( sqlite3_mutex_held(db->mutex) );
   62701   db->nChange = nChange;
   62702   db->nTotalChange += nChange;
   62703 }
   62704 
   62705 /*
   62706 ** Set a flag in the vdbe to update the change counter when it is finalised
   62707 ** or reset.
   62708 */
   62709 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   62710   v->changeCntOn = 1;
   62711 }
   62712 
   62713 /*
   62714 ** Mark every prepared statement associated with a database connection
   62715 ** as expired.
   62716 **
   62717 ** An expired statement means that recompilation of the statement is
   62718 ** recommend.  Statements expire when things happen that make their
   62719 ** programs obsolete.  Removing user-defined functions or collating
   62720 ** sequences, or changing an authorization function are the types of
   62721 ** things that make prepared statements obsolete.
   62722 */
   62723 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   62724   Vdbe *p;
   62725   for(p = db->pVdbe; p; p=p->pNext){
   62726     p->expired = 1;
   62727   }
   62728 }
   62729 
   62730 /*
   62731 ** Return the database associated with the Vdbe.
   62732 */
   62733 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   62734   return v->db;
   62735 }
   62736 
   62737 /*
   62738 ** Return a pointer to an sqlite3_value structure containing the value bound
   62739 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   62740 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   62741 ** constants) to the value before returning it.
   62742 **
   62743 ** The returned value must be freed by the caller using sqlite3ValueFree().
   62744 */
   62745 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
   62746   assert( iVar>0 );
   62747   if( v ){
   62748     Mem *pMem = &v->aVar[iVar-1];
   62749     if( 0==(pMem->flags & MEM_Null) ){
   62750       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   62751       if( pRet ){
   62752         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   62753         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   62754         sqlite3VdbeMemStoreType((Mem *)pRet);
   62755       }
   62756       return pRet;
   62757     }
   62758   }
   62759   return 0;
   62760 }
   62761 
   62762 /*
   62763 ** Configure SQL variable iVar so that binding a new value to it signals
   62764 ** to sqlite3_reoptimize() that re-preparing the statement may result
   62765 ** in a better query plan.
   62766 */
   62767 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   62768   assert( iVar>0 );
   62769   if( iVar>32 ){
   62770     v->expmask = 0xffffffff;
   62771   }else{
   62772     v->expmask |= ((u32)1 << (iVar-1));
   62773   }
   62774 }
   62775 
   62776 /************** End of vdbeaux.c *********************************************/
   62777 /************** Begin file vdbeapi.c *****************************************/
   62778 /*
   62779 ** 2004 May 26
   62780 **
   62781 ** The author disclaims copyright to this source code.  In place of
   62782 ** a legal notice, here is a blessing:
   62783 **
   62784 **    May you do good and not evil.
   62785 **    May you find forgiveness for yourself and forgive others.
   62786 **    May you share freely, never taking more than you give.
   62787 **
   62788 *************************************************************************
   62789 **
   62790 ** This file contains code use to implement APIs that are part of the
   62791 ** VDBE.
   62792 */
   62793 
   62794 #ifndef SQLITE_OMIT_DEPRECATED
   62795 /*
   62796 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   62797 ** to be recompiled.  A statement needs to be recompiled whenever the
   62798 ** execution environment changes in a way that would alter the program
   62799 ** that sqlite3_prepare() generates.  For example, if new functions or
   62800 ** collating sequences are registered or if an authorizer function is
   62801 ** added or changed.
   62802 */
   62803 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   62804   Vdbe *p = (Vdbe*)pStmt;
   62805   return p==0 || p->expired;
   62806 }
   62807 #endif
   62808 
   62809 /*
   62810 ** Check on a Vdbe to make sure it has not been finalized.  Log
   62811 ** an error and return true if it has been finalized (or is otherwise
   62812 ** invalid).  Return false if it is ok.
   62813 */
   62814 static int vdbeSafety(Vdbe *p){
   62815   if( p->db==0 ){
   62816     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   62817     return 1;
   62818   }else{
   62819     return 0;
   62820   }
   62821 }
   62822 static int vdbeSafetyNotNull(Vdbe *p){
   62823   if( p==0 ){
   62824     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   62825     return 1;
   62826   }else{
   62827     return vdbeSafety(p);
   62828   }
   62829 }
   62830 
   62831 /*
   62832 ** The following routine destroys a virtual machine that is created by
   62833 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   62834 ** success/failure code that describes the result of executing the virtual
   62835 ** machine.
   62836 **
   62837 ** This routine sets the error code and string returned by
   62838 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   62839 */
   62840 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   62841   int rc;
   62842   if( pStmt==0 ){
   62843     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   62844     ** pointer is a harmless no-op. */
   62845     rc = SQLITE_OK;
   62846   }else{
   62847     Vdbe *v = (Vdbe*)pStmt;
   62848     sqlite3 *db = v->db;
   62849 #if SQLITE_THREADSAFE
   62850     sqlite3_mutex *mutex;
   62851 #endif
   62852     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   62853 #if SQLITE_THREADSAFE
   62854     mutex = v->db->mutex;
   62855 #endif
   62856     sqlite3_mutex_enter(mutex);
   62857     rc = sqlite3VdbeFinalize(v);
   62858     rc = sqlite3ApiExit(db, rc);
   62859     sqlite3_mutex_leave(mutex);
   62860   }
   62861   return rc;
   62862 }
   62863 
   62864 /*
   62865 ** Terminate the current execution of an SQL statement and reset it
   62866 ** back to its starting state so that it can be reused. A success code from
   62867 ** the prior execution is returned.
   62868 **
   62869 ** This routine sets the error code and string returned by
   62870 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   62871 */
   62872 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   62873   int rc;
   62874   if( pStmt==0 ){
   62875     rc = SQLITE_OK;
   62876   }else{
   62877     Vdbe *v = (Vdbe*)pStmt;
   62878     sqlite3_mutex_enter(v->db->mutex);
   62879     rc = sqlite3VdbeReset(v);
   62880     sqlite3VdbeRewind(v);
   62881     assert( (rc & (v->db->errMask))==rc );
   62882     rc = sqlite3ApiExit(v->db, rc);
   62883     sqlite3_mutex_leave(v->db->mutex);
   62884   }
   62885   return rc;
   62886 }
   62887 
   62888 /*
   62889 ** Set all the parameters in the compiled SQL statement to NULL.
   62890 */
   62891 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   62892   int i;
   62893   int rc = SQLITE_OK;
   62894   Vdbe *p = (Vdbe*)pStmt;
   62895 #if SQLITE_THREADSAFE
   62896   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   62897 #endif
   62898   sqlite3_mutex_enter(mutex);
   62899   for(i=0; i<p->nVar; i++){
   62900     sqlite3VdbeMemRelease(&p->aVar[i]);
   62901     p->aVar[i].flags = MEM_Null;
   62902   }
   62903   if( p->isPrepareV2 && p->expmask ){
   62904     p->expired = 1;
   62905   }
   62906   sqlite3_mutex_leave(mutex);
   62907   return rc;
   62908 }
   62909 
   62910 
   62911 /**************************** sqlite3_value_  *******************************
   62912 ** The following routines extract information from a Mem or sqlite3_value
   62913 ** structure.
   62914 */
   62915 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   62916   Mem *p = (Mem*)pVal;
   62917   if( p->flags & (MEM_Blob|MEM_Str) ){
   62918     sqlite3VdbeMemExpandBlob(p);
   62919     p->flags &= ~MEM_Str;
   62920     p->flags |= MEM_Blob;
   62921     return p->n ? p->z : 0;
   62922   }else{
   62923     return sqlite3_value_text(pVal);
   62924   }
   62925 }
   62926 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   62927   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   62928 }
   62929 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   62930   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   62931 }
   62932 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   62933   return sqlite3VdbeRealValue((Mem*)pVal);
   62934 }
   62935 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   62936   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   62937 }
   62938 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   62939   return sqlite3VdbeIntValue((Mem*)pVal);
   62940 }
   62941 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   62942   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   62943 }
   62944 #ifndef SQLITE_OMIT_UTF16
   62945 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   62946   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   62947 }
   62948 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   62949   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   62950 }
   62951 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   62952   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   62953 }
   62954 #endif /* SQLITE_OMIT_UTF16 */
   62955 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   62956   return pVal->type;
   62957 }
   62958 
   62959 /**************************** sqlite3_result_  *******************************
   62960 ** The following routines are used by user-defined functions to specify
   62961 ** the function result.
   62962 **
   62963 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   62964 ** result as a string or blob but if the string or blob is too large, it
   62965 ** then sets the error code to SQLITE_TOOBIG
   62966 */
   62967 static void setResultStrOrError(
   62968   sqlite3_context *pCtx,  /* Function context */
   62969   const char *z,          /* String pointer */
   62970   int n,                  /* Bytes in string, or negative */
   62971   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   62972   void (*xDel)(void*)     /* Destructor function */
   62973 ){
   62974   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   62975     sqlite3_result_error_toobig(pCtx);
   62976   }
   62977 }
   62978 SQLITE_API void sqlite3_result_blob(
   62979   sqlite3_context *pCtx,
   62980   const void *z,
   62981   int n,
   62982   void (*xDel)(void *)
   62983 ){
   62984   assert( n>=0 );
   62985   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62986   setResultStrOrError(pCtx, z, n, 0, xDel);
   62987 }
   62988 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   62989   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62990   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   62991 }
   62992 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   62993   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62994   pCtx->isError = SQLITE_ERROR;
   62995   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   62996 }
   62997 #ifndef SQLITE_OMIT_UTF16
   62998 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   62999   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63000   pCtx->isError = SQLITE_ERROR;
   63001   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   63002 }
   63003 #endif
   63004 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   63005   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63006   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   63007 }
   63008 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   63009   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63010   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   63011 }
   63012 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   63013   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63014   sqlite3VdbeMemSetNull(&pCtx->s);
   63015 }
   63016 SQLITE_API void sqlite3_result_text(
   63017   sqlite3_context *pCtx,
   63018   const char *z,
   63019   int n,
   63020   void (*xDel)(void *)
   63021 ){
   63022   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63023   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   63024 }
   63025 #ifndef SQLITE_OMIT_UTF16
   63026 SQLITE_API void sqlite3_result_text16(
   63027   sqlite3_context *pCtx,
   63028   const void *z,
   63029   int n,
   63030   void (*xDel)(void *)
   63031 ){
   63032   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63033   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   63034 }
   63035 SQLITE_API void sqlite3_result_text16be(
   63036   sqlite3_context *pCtx,
   63037   const void *z,
   63038   int n,
   63039   void (*xDel)(void *)
   63040 ){
   63041   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63042   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   63043 }
   63044 SQLITE_API void sqlite3_result_text16le(
   63045   sqlite3_context *pCtx,
   63046   const void *z,
   63047   int n,
   63048   void (*xDel)(void *)
   63049 ){
   63050   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63051   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   63052 }
   63053 #endif /* SQLITE_OMIT_UTF16 */
   63054 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   63055   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63056   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   63057 }
   63058 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   63059   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63060   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   63061 }
   63062 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   63063   pCtx->isError = errCode;
   63064   if( pCtx->s.flags & MEM_Null ){
   63065     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   63066                          SQLITE_UTF8, SQLITE_STATIC);
   63067   }
   63068 }
   63069 
   63070 /* Force an SQLITE_TOOBIG error. */
   63071 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   63072   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63073   pCtx->isError = SQLITE_TOOBIG;
   63074   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   63075                        SQLITE_UTF8, SQLITE_STATIC);
   63076 }
   63077 
   63078 /* An SQLITE_NOMEM error. */
   63079 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   63080   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63081   sqlite3VdbeMemSetNull(&pCtx->s);
   63082   pCtx->isError = SQLITE_NOMEM;
   63083   pCtx->s.db->mallocFailed = 1;
   63084 }
   63085 
   63086 /*
   63087 ** This function is called after a transaction has been committed. It
   63088 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   63089 */
   63090 static int doWalCallbacks(sqlite3 *db){
   63091   int rc = SQLITE_OK;
   63092 #ifndef SQLITE_OMIT_WAL
   63093   int i;
   63094   for(i=0; i<db->nDb; i++){
   63095     Btree *pBt = db->aDb[i].pBt;
   63096     if( pBt ){
   63097       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   63098       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   63099         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
   63100       }
   63101     }
   63102   }
   63103 #endif
   63104   return rc;
   63105 }
   63106 
   63107 /*
   63108 ** Execute the statement pStmt, either until a row of data is ready, the
   63109 ** statement is completely executed or an error occurs.
   63110 **
   63111 ** This routine implements the bulk of the logic behind the sqlite_step()
   63112 ** API.  The only thing omitted is the automatic recompile if a
   63113 ** schema change has occurred.  That detail is handled by the
   63114 ** outer sqlite3_step() wrapper procedure.
   63115 */
   63116 static int sqlite3Step(Vdbe *p){
   63117   sqlite3 *db;
   63118   int rc;
   63119 
   63120   assert(p);
   63121   if( p->magic!=VDBE_MAGIC_RUN ){
   63122     /* We used to require that sqlite3_reset() be called before retrying
   63123     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
   63124     ** with version 3.7.0, we changed this so that sqlite3_reset() would
   63125     ** be called automatically instead of throwing the SQLITE_MISUSE error.
   63126     ** This "automatic-reset" change is not technically an incompatibility,
   63127     ** since any application that receives an SQLITE_MISUSE is broken by
   63128     ** definition.
   63129     **
   63130     ** Nevertheless, some published applications that were originally written
   63131     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
   63132     ** returns, and those were broken by the automatic-reset change.  As a
   63133     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
   63134     ** legacy behavior of returning SQLITE_MISUSE for cases where the
   63135     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
   63136     ** or SQLITE_BUSY error.
   63137     */
   63138 #ifdef SQLITE_OMIT_AUTORESET
   63139     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
   63140       sqlite3_reset((sqlite3_stmt*)p);
   63141     }else{
   63142       return SQLITE_MISUSE_BKPT;
   63143     }
   63144 #else
   63145     sqlite3_reset((sqlite3_stmt*)p);
   63146 #endif
   63147   }
   63148 
   63149   /* Check that malloc() has not failed. If it has, return early. */
   63150   db = p->db;
   63151   if( db->mallocFailed ){
   63152     p->rc = SQLITE_NOMEM;
   63153     return SQLITE_NOMEM;
   63154   }
   63155 
   63156   if( p->pc<=0 && p->expired ){
   63157     p->rc = SQLITE_SCHEMA;
   63158     rc = SQLITE_ERROR;
   63159     goto end_of_step;
   63160   }
   63161   if( p->pc<0 ){
   63162     /* If there are no other statements currently running, then
   63163     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   63164     ** from interrupting a statement that has not yet started.
   63165     */
   63166     if( db->activeVdbeCnt==0 ){
   63167       db->u1.isInterrupted = 0;
   63168     }
   63169 
   63170     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
   63171 
   63172 #ifndef SQLITE_OMIT_TRACE
   63173     if( db->xProfile && !db->init.busy ){
   63174       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   63175     }
   63176 #endif
   63177 
   63178     db->activeVdbeCnt++;
   63179     if( p->readOnly==0 ) db->writeVdbeCnt++;
   63180     p->pc = 0;
   63181   }
   63182 #ifndef SQLITE_OMIT_EXPLAIN
   63183   if( p->explain ){
   63184     rc = sqlite3VdbeList(p);
   63185   }else
   63186 #endif /* SQLITE_OMIT_EXPLAIN */
   63187   {
   63188     db->vdbeExecCnt++;
   63189     rc = sqlite3VdbeExec(p);
   63190     db->vdbeExecCnt--;
   63191   }
   63192 
   63193 #ifndef SQLITE_OMIT_TRACE
   63194   /* Invoke the profile callback if there is one
   63195   */
   63196   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   63197     sqlite3_int64 iNow;
   63198     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   63199     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
   63200   }
   63201 #endif
   63202 
   63203   if( rc==SQLITE_DONE ){
   63204     assert( p->rc==SQLITE_OK );
   63205     p->rc = doWalCallbacks(db);
   63206     if( p->rc!=SQLITE_OK ){
   63207       rc = SQLITE_ERROR;
   63208     }
   63209   }
   63210 
   63211   db->errCode = rc;
   63212   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   63213     p->rc = SQLITE_NOMEM;
   63214   }
   63215 end_of_step:
   63216   /* At this point local variable rc holds the value that should be
   63217   ** returned if this statement was compiled using the legacy
   63218   ** sqlite3_prepare() interface. According to the docs, this can only
   63219   ** be one of the values in the first assert() below. Variable p->rc
   63220   ** contains the value that would be returned if sqlite3_finalize()
   63221   ** were called on statement p.
   63222   */
   63223   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   63224        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   63225   );
   63226   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   63227   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   63228     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   63229     ** error has occured, then return the error code in p->rc to the
   63230     ** caller. Set the error code in the database handle to the same value.
   63231     */
   63232     rc = sqlite3VdbeTransferError(p);
   63233   }
   63234   return (rc&db->errMask);
   63235 }
   63236 
   63237 /*
   63238 ** The maximum number of times that a statement will try to reparse
   63239 ** itself before giving up and returning SQLITE_SCHEMA.
   63240 */
   63241 #ifndef SQLITE_MAX_SCHEMA_RETRY
   63242 # define SQLITE_MAX_SCHEMA_RETRY 5
   63243 #endif
   63244 
   63245 /*
   63246 ** This is the top-level implementation of sqlite3_step().  Call
   63247 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   63248 ** call sqlite3Reprepare() and try again.
   63249 */
   63250 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   63251   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   63252   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   63253   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   63254   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   63255   sqlite3 *db;             /* The database connection */
   63256 
   63257   if( vdbeSafetyNotNull(v) ){
   63258     return SQLITE_MISUSE_BKPT;
   63259   }
   63260   db = v->db;
   63261   sqlite3_mutex_enter(db->mutex);
   63262   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   63263          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
   63264          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   63265     sqlite3_reset(pStmt);
   63266     assert( v->expired==0 );
   63267   }
   63268   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
   63269     /* This case occurs after failing to recompile an sql statement.
   63270     ** The error message from the SQL compiler has already been loaded
   63271     ** into the database handle. This block copies the error message
   63272     ** from the database handle into the statement and sets the statement
   63273     ** program counter to 0 to ensure that when the statement is
   63274     ** finalized or reset the parser error message is available via
   63275     ** sqlite3_errmsg() and sqlite3_errcode().
   63276     */
   63277     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   63278     sqlite3DbFree(db, v->zErrMsg);
   63279     if( !db->mallocFailed ){
   63280       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   63281       v->rc = rc2;
   63282     } else {
   63283       v->zErrMsg = 0;
   63284       v->rc = rc = SQLITE_NOMEM;
   63285     }
   63286   }
   63287   rc = sqlite3ApiExit(db, rc);
   63288   sqlite3_mutex_leave(db->mutex);
   63289   return rc;
   63290 }
   63291 
   63292 /*
   63293 ** Extract the user data from a sqlite3_context structure and return a
   63294 ** pointer to it.
   63295 */
   63296 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   63297   assert( p && p->pFunc );
   63298   return p->pFunc->pUserData;
   63299 }
   63300 
   63301 /*
   63302 ** Extract the user data from a sqlite3_context structure and return a
   63303 ** pointer to it.
   63304 **
   63305 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   63306 ** returns a copy of the pointer to the database connection (the 1st
   63307 ** parameter) of the sqlite3_create_function() and
   63308 ** sqlite3_create_function16() routines that originally registered the
   63309 ** application defined function.
   63310 */
   63311 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   63312   assert( p && p->pFunc );
   63313   return p->s.db;
   63314 }
   63315 
   63316 /*
   63317 ** The following is the implementation of an SQL function that always
   63318 ** fails with an error message stating that the function is used in the
   63319 ** wrong context.  The sqlite3_overload_function() API might construct
   63320 ** SQL function that use this routine so that the functions will exist
   63321 ** for name resolution but are actually overloaded by the xFindFunction
   63322 ** method of virtual tables.
   63323 */
   63324 SQLITE_PRIVATE void sqlite3InvalidFunction(
   63325   sqlite3_context *context,  /* The function calling context */
   63326   int NotUsed,               /* Number of arguments to the function */
   63327   sqlite3_value **NotUsed2   /* Value of each argument */
   63328 ){
   63329   const char *zName = context->pFunc->zName;
   63330   char *zErr;
   63331   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   63332   zErr = sqlite3_mprintf(
   63333       "unable to use function %s in the requested context", zName);
   63334   sqlite3_result_error(context, zErr, -1);
   63335   sqlite3_free(zErr);
   63336 }
   63337 
   63338 /*
   63339 ** Allocate or return the aggregate context for a user function.  A new
   63340 ** context is allocated on the first call.  Subsequent calls return the
   63341 ** same context that was returned on prior calls.
   63342 */
   63343 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   63344   Mem *pMem;
   63345   assert( p && p->pFunc && p->pFunc->xStep );
   63346   assert( sqlite3_mutex_held(p->s.db->mutex) );
   63347   pMem = p->pMem;
   63348   testcase( nByte<0 );
   63349   if( (pMem->flags & MEM_Agg)==0 ){
   63350     if( nByte<=0 ){
   63351       sqlite3VdbeMemReleaseExternal(pMem);
   63352       pMem->flags = MEM_Null;
   63353       pMem->z = 0;
   63354     }else{
   63355       sqlite3VdbeMemGrow(pMem, nByte, 0);
   63356       pMem->flags = MEM_Agg;
   63357       pMem->u.pDef = p->pFunc;
   63358       if( pMem->z ){
   63359         memset(pMem->z, 0, nByte);
   63360       }
   63361     }
   63362   }
   63363   return (void*)pMem->z;
   63364 }
   63365 
   63366 /*
   63367 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   63368 ** the user-function defined by pCtx.
   63369 */
   63370 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   63371   VdbeFunc *pVdbeFunc;
   63372 
   63373   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63374   pVdbeFunc = pCtx->pVdbeFunc;
   63375   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
   63376     return 0;
   63377   }
   63378   return pVdbeFunc->apAux[iArg].pAux;
   63379 }
   63380 
   63381 /*
   63382 ** Set the auxilary data pointer and delete function, for the iArg'th
   63383 ** argument to the user-function defined by pCtx. Any previous value is
   63384 ** deleted by calling the delete function specified when it was set.
   63385 */
   63386 SQLITE_API void sqlite3_set_auxdata(
   63387   sqlite3_context *pCtx,
   63388   int iArg,
   63389   void *pAux,
   63390   void (*xDelete)(void*)
   63391 ){
   63392   struct AuxData *pAuxData;
   63393   VdbeFunc *pVdbeFunc;
   63394   if( iArg<0 ) goto failed;
   63395 
   63396   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63397   pVdbeFunc = pCtx->pVdbeFunc;
   63398   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
   63399     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
   63400     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
   63401     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
   63402     if( !pVdbeFunc ){
   63403       goto failed;
   63404     }
   63405     pCtx->pVdbeFunc = pVdbeFunc;
   63406     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
   63407     pVdbeFunc->nAux = iArg+1;
   63408     pVdbeFunc->pFunc = pCtx->pFunc;
   63409   }
   63410 
   63411   pAuxData = &pVdbeFunc->apAux[iArg];
   63412   if( pAuxData->pAux && pAuxData->xDelete ){
   63413     pAuxData->xDelete(pAuxData->pAux);
   63414   }
   63415   pAuxData->pAux = pAux;
   63416   pAuxData->xDelete = xDelete;
   63417   return;
   63418 
   63419 failed:
   63420   if( xDelete ){
   63421     xDelete(pAux);
   63422   }
   63423 }
   63424 
   63425 #ifndef SQLITE_OMIT_DEPRECATED
   63426 /*
   63427 ** Return the number of times the Step function of a aggregate has been
   63428 ** called.
   63429 **
   63430 ** This function is deprecated.  Do not use it for new code.  It is
   63431 ** provide only to avoid breaking legacy code.  New aggregate function
   63432 ** implementations should keep their own counts within their aggregate
   63433 ** context.
   63434 */
   63435 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   63436   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   63437   return p->pMem->n;
   63438 }
   63439 #endif
   63440 
   63441 /*
   63442 ** Return the number of columns in the result set for the statement pStmt.
   63443 */
   63444 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   63445   Vdbe *pVm = (Vdbe *)pStmt;
   63446   return pVm ? pVm->nResColumn : 0;
   63447 }
   63448 
   63449 /*
   63450 ** Return the number of values available from the current row of the
   63451 ** currently executing statement pStmt.
   63452 */
   63453 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   63454   Vdbe *pVm = (Vdbe *)pStmt;
   63455   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   63456   return pVm->nResColumn;
   63457 }
   63458 
   63459 
   63460 /*
   63461 ** Check to see if column iCol of the given statement is valid.  If
   63462 ** it is, return a pointer to the Mem for the value of that column.
   63463 ** If iCol is not valid, return a pointer to a Mem which has a value
   63464 ** of NULL.
   63465 */
   63466 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   63467   Vdbe *pVm;
   63468   Mem *pOut;
   63469 
   63470   pVm = (Vdbe *)pStmt;
   63471   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   63472     sqlite3_mutex_enter(pVm->db->mutex);
   63473     pOut = &pVm->pResultSet[i];
   63474   }else{
   63475     /* If the value passed as the second argument is out of range, return
   63476     ** a pointer to the following static Mem object which contains the
   63477     ** value SQL NULL. Even though the Mem structure contains an element
   63478     ** of type i64, on certain architectures (x86) with certain compiler
   63479     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   63480     ** instead of an 8-byte one. This all works fine, except that when
   63481     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   63482     ** that a Mem structure is located on an 8-byte boundary. To prevent
   63483     ** these assert()s from failing, when building with SQLITE_DEBUG defined
   63484     ** using gcc, we force nullMem to be 8-byte aligned using the magical
   63485     ** __attribute__((aligned(8))) macro.  */
   63486     static const Mem nullMem
   63487 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   63488       __attribute__((aligned(8)))
   63489 #endif
   63490       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
   63491 #ifdef SQLITE_DEBUG
   63492          0, 0,  /* pScopyFrom, pFiller */
   63493 #endif
   63494          0, 0 };
   63495 
   63496     if( pVm && ALWAYS(pVm->db) ){
   63497       sqlite3_mutex_enter(pVm->db->mutex);
   63498       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   63499     }
   63500     pOut = (Mem*)&nullMem;
   63501   }
   63502   return pOut;
   63503 }
   63504 
   63505 /*
   63506 ** This function is called after invoking an sqlite3_value_XXX function on a
   63507 ** column value (i.e. a value returned by evaluating an SQL expression in the
   63508 ** select list of a SELECT statement) that may cause a malloc() failure. If
   63509 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   63510 ** code of statement pStmt set to SQLITE_NOMEM.
   63511 **
   63512 ** Specifically, this is called from within:
   63513 **
   63514 **     sqlite3_column_int()
   63515 **     sqlite3_column_int64()
   63516 **     sqlite3_column_text()
   63517 **     sqlite3_column_text16()
   63518 **     sqlite3_column_real()
   63519 **     sqlite3_column_bytes()
   63520 **     sqlite3_column_bytes16()
   63521 **     sqiite3_column_blob()
   63522 */
   63523 static void columnMallocFailure(sqlite3_stmt *pStmt)
   63524 {
   63525   /* If malloc() failed during an encoding conversion within an
   63526   ** sqlite3_column_XXX API, then set the return code of the statement to
   63527   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   63528   ** and _finalize() will return NOMEM.
   63529   */
   63530   Vdbe *p = (Vdbe *)pStmt;
   63531   if( p ){
   63532     p->rc = sqlite3ApiExit(p->db, p->rc);
   63533     sqlite3_mutex_leave(p->db->mutex);
   63534   }
   63535 }
   63536 
   63537 /**************************** sqlite3_column_  *******************************
   63538 ** The following routines are used to access elements of the current row
   63539 ** in the result set.
   63540 */
   63541 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   63542   const void *val;
   63543   val = sqlite3_value_blob( columnMem(pStmt,i) );
   63544   /* Even though there is no encoding conversion, value_blob() might
   63545   ** need to call malloc() to expand the result of a zeroblob()
   63546   ** expression.
   63547   */
   63548   columnMallocFailure(pStmt);
   63549   return val;
   63550 }
   63551 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   63552   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   63553   columnMallocFailure(pStmt);
   63554   return val;
   63555 }
   63556 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   63557   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   63558   columnMallocFailure(pStmt);
   63559   return val;
   63560 }
   63561 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   63562   double val = sqlite3_value_double( columnMem(pStmt,i) );
   63563   columnMallocFailure(pStmt);
   63564   return val;
   63565 }
   63566 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   63567   int val = sqlite3_value_int( columnMem(pStmt,i) );
   63568   columnMallocFailure(pStmt);
   63569   return val;
   63570 }
   63571 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   63572   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   63573   columnMallocFailure(pStmt);
   63574   return val;
   63575 }
   63576 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   63577   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   63578   columnMallocFailure(pStmt);
   63579   return val;
   63580 }
   63581 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   63582   Mem *pOut = columnMem(pStmt, i);
   63583   if( pOut->flags&MEM_Static ){
   63584     pOut->flags &= ~MEM_Static;
   63585     pOut->flags |= MEM_Ephem;
   63586   }
   63587   columnMallocFailure(pStmt);
   63588   return (sqlite3_value *)pOut;
   63589 }
   63590 #ifndef SQLITE_OMIT_UTF16
   63591 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   63592   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   63593   columnMallocFailure(pStmt);
   63594   return val;
   63595 }
   63596 #endif /* SQLITE_OMIT_UTF16 */
   63597 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   63598   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   63599   columnMallocFailure(pStmt);
   63600   return iType;
   63601 }
   63602 
   63603 /* The following function is experimental and subject to change or
   63604 ** removal */
   63605 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
   63606 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
   63607 **}
   63608 */
   63609 
   63610 /*
   63611 ** Convert the N-th element of pStmt->pColName[] into a string using
   63612 ** xFunc() then return that string.  If N is out of range, return 0.
   63613 **
   63614 ** There are up to 5 names for each column.  useType determines which
   63615 ** name is returned.  Here are the names:
   63616 **
   63617 **    0      The column name as it should be displayed for output
   63618 **    1      The datatype name for the column
   63619 **    2      The name of the database that the column derives from
   63620 **    3      The name of the table that the column derives from
   63621 **    4      The name of the table column that the result column derives from
   63622 **
   63623 ** If the result is not a simple column reference (if it is an expression
   63624 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   63625 */
   63626 static const void *columnName(
   63627   sqlite3_stmt *pStmt,
   63628   int N,
   63629   const void *(*xFunc)(Mem*),
   63630   int useType
   63631 ){
   63632   const void *ret = 0;
   63633   Vdbe *p = (Vdbe *)pStmt;
   63634   int n;
   63635   sqlite3 *db = p->db;
   63636 
   63637   assert( db!=0 );
   63638   n = sqlite3_column_count(pStmt);
   63639   if( N<n && N>=0 ){
   63640     N += useType*n;
   63641     sqlite3_mutex_enter(db->mutex);
   63642     assert( db->mallocFailed==0 );
   63643     ret = xFunc(&p->aColName[N]);
   63644      /* A malloc may have failed inside of the xFunc() call. If this
   63645     ** is the case, clear the mallocFailed flag and return NULL.
   63646     */
   63647     if( db->mallocFailed ){
   63648       db->mallocFailed = 0;
   63649       ret = 0;
   63650     }
   63651     sqlite3_mutex_leave(db->mutex);
   63652   }
   63653   return ret;
   63654 }
   63655 
   63656 /*
   63657 ** Return the name of the Nth column of the result set returned by SQL
   63658 ** statement pStmt.
   63659 */
   63660 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   63661   return columnName(
   63662       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   63663 }
   63664 #ifndef SQLITE_OMIT_UTF16
   63665 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   63666   return columnName(
   63667       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   63668 }
   63669 #endif
   63670 
   63671 /*
   63672 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   63673 ** not define OMIT_DECLTYPE.
   63674 */
   63675 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   63676 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   63677          and SQLITE_ENABLE_COLUMN_METADATA"
   63678 #endif
   63679 
   63680 #ifndef SQLITE_OMIT_DECLTYPE
   63681 /*
   63682 ** Return the column declaration type (if applicable) of the 'i'th column
   63683 ** of the result set of SQL statement pStmt.
   63684 */
   63685 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   63686   return columnName(
   63687       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   63688 }
   63689 #ifndef SQLITE_OMIT_UTF16
   63690 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   63691   return columnName(
   63692       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   63693 }
   63694 #endif /* SQLITE_OMIT_UTF16 */
   63695 #endif /* SQLITE_OMIT_DECLTYPE */
   63696 
   63697 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   63698 /*
   63699 ** Return the name of the database from which a result column derives.
   63700 ** NULL is returned if the result column is an expression or constant or
   63701 ** anything else which is not an unabiguous reference to a database column.
   63702 */
   63703 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   63704   return columnName(
   63705       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   63706 }
   63707 #ifndef SQLITE_OMIT_UTF16
   63708 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   63709   return columnName(
   63710       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   63711 }
   63712 #endif /* SQLITE_OMIT_UTF16 */
   63713 
   63714 /*
   63715 ** Return the name of the table from which a result column derives.
   63716 ** NULL is returned if the result column is an expression or constant or
   63717 ** anything else which is not an unabiguous reference to a database column.
   63718 */
   63719 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   63720   return columnName(
   63721       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   63722 }
   63723 #ifndef SQLITE_OMIT_UTF16
   63724 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   63725   return columnName(
   63726       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   63727 }
   63728 #endif /* SQLITE_OMIT_UTF16 */
   63729 
   63730 /*
   63731 ** Return the name of the table column from which a result column derives.
   63732 ** NULL is returned if the result column is an expression or constant or
   63733 ** anything else which is not an unabiguous reference to a database column.
   63734 */
   63735 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   63736   return columnName(
   63737       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   63738 }
   63739 #ifndef SQLITE_OMIT_UTF16
   63740 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   63741   return columnName(
   63742       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   63743 }
   63744 #endif /* SQLITE_OMIT_UTF16 */
   63745 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   63746 
   63747 
   63748 /******************************* sqlite3_bind_  ***************************
   63749 **
   63750 ** Routines used to attach values to wildcards in a compiled SQL statement.
   63751 */
   63752 /*
   63753 ** Unbind the value bound to variable i in virtual machine p. This is the
   63754 ** the same as binding a NULL value to the column. If the "i" parameter is
   63755 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   63756 **
   63757 ** A successful evaluation of this routine acquires the mutex on p.
   63758 ** the mutex is released if any kind of error occurs.
   63759 **
   63760 ** The error code stored in database p->db is overwritten with the return
   63761 ** value in any case.
   63762 */
   63763 static int vdbeUnbind(Vdbe *p, int i){
   63764   Mem *pVar;
   63765   if( vdbeSafetyNotNull(p) ){
   63766     return SQLITE_MISUSE_BKPT;
   63767   }
   63768   sqlite3_mutex_enter(p->db->mutex);
   63769   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   63770     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   63771     sqlite3_mutex_leave(p->db->mutex);
   63772     sqlite3_log(SQLITE_MISUSE,
   63773         "bind on a busy prepared statement: [%s]", p->zSql);
   63774     return SQLITE_MISUSE_BKPT;
   63775   }
   63776   if( i<1 || i>p->nVar ){
   63777     sqlite3Error(p->db, SQLITE_RANGE, 0);
   63778     sqlite3_mutex_leave(p->db->mutex);
   63779     return SQLITE_RANGE;
   63780   }
   63781   i--;
   63782   pVar = &p->aVar[i];
   63783   sqlite3VdbeMemRelease(pVar);
   63784   pVar->flags = MEM_Null;
   63785   sqlite3Error(p->db, SQLITE_OK, 0);
   63786 
   63787   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   63788   ** binding a new value to this variable invalidates the current query plan.
   63789   **
   63790   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   63791   ** parameter in the WHERE clause might influence the choice of query plan
   63792   ** for a statement, then the statement will be automatically recompiled,
   63793   ** as if there had been a schema change, on the first sqlite3_step() call
   63794   ** following any change to the bindings of that parameter.
   63795   */
   63796   if( p->isPrepareV2 &&
   63797      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   63798   ){
   63799     p->expired = 1;
   63800   }
   63801   return SQLITE_OK;
   63802 }
   63803 
   63804 /*
   63805 ** Bind a text or BLOB value.
   63806 */
   63807 static int bindText(
   63808   sqlite3_stmt *pStmt,   /* The statement to bind against */
   63809   int i,                 /* Index of the parameter to bind */
   63810   const void *zData,     /* Pointer to the data to be bound */
   63811   int nData,             /* Number of bytes of data to be bound */
   63812   void (*xDel)(void*),   /* Destructor for the data */
   63813   u8 encoding            /* Encoding for the data */
   63814 ){
   63815   Vdbe *p = (Vdbe *)pStmt;
   63816   Mem *pVar;
   63817   int rc;
   63818 
   63819   rc = vdbeUnbind(p, i);
   63820   if( rc==SQLITE_OK ){
   63821     if( zData!=0 ){
   63822       pVar = &p->aVar[i-1];
   63823       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   63824       if( rc==SQLITE_OK && encoding!=0 ){
   63825         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   63826       }
   63827       sqlite3Error(p->db, rc, 0);
   63828       rc = sqlite3ApiExit(p->db, rc);
   63829     }
   63830     sqlite3_mutex_leave(p->db->mutex);
   63831   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   63832     xDel((void*)zData);
   63833   }
   63834   return rc;
   63835 }
   63836 
   63837 
   63838 /*
   63839 ** Bind a blob value to an SQL statement variable.
   63840 */
   63841 SQLITE_API int sqlite3_bind_blob(
   63842   sqlite3_stmt *pStmt,
   63843   int i,
   63844   const void *zData,
   63845   int nData,
   63846   void (*xDel)(void*)
   63847 ){
   63848   return bindText(pStmt, i, zData, nData, xDel, 0);
   63849 }
   63850 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   63851   int rc;
   63852   Vdbe *p = (Vdbe *)pStmt;
   63853   rc = vdbeUnbind(p, i);
   63854   if( rc==SQLITE_OK ){
   63855     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   63856     sqlite3_mutex_leave(p->db->mutex);
   63857   }
   63858   return rc;
   63859 }
   63860 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   63861   return sqlite3_bind_int64(p, i, (i64)iValue);
   63862 }
   63863 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   63864   int rc;
   63865   Vdbe *p = (Vdbe *)pStmt;
   63866   rc = vdbeUnbind(p, i);
   63867   if( rc==SQLITE_OK ){
   63868     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   63869     sqlite3_mutex_leave(p->db->mutex);
   63870   }
   63871   return rc;
   63872 }
   63873 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   63874   int rc;
   63875   Vdbe *p = (Vdbe*)pStmt;
   63876   rc = vdbeUnbind(p, i);
   63877   if( rc==SQLITE_OK ){
   63878     sqlite3_mutex_leave(p->db->mutex);
   63879   }
   63880   return rc;
   63881 }
   63882 SQLITE_API int sqlite3_bind_text(
   63883   sqlite3_stmt *pStmt,
   63884   int i,
   63885   const char *zData,
   63886   int nData,
   63887   void (*xDel)(void*)
   63888 ){
   63889   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   63890 }
   63891 #ifndef SQLITE_OMIT_UTF16
   63892 SQLITE_API int sqlite3_bind_text16(
   63893   sqlite3_stmt *pStmt,
   63894   int i,
   63895   const void *zData,
   63896   int nData,
   63897   void (*xDel)(void*)
   63898 ){
   63899   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   63900 }
   63901 #endif /* SQLITE_OMIT_UTF16 */
   63902 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   63903   int rc;
   63904   switch( pValue->type ){
   63905     case SQLITE_INTEGER: {
   63906       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   63907       break;
   63908     }
   63909     case SQLITE_FLOAT: {
   63910       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   63911       break;
   63912     }
   63913     case SQLITE_BLOB: {
   63914       if( pValue->flags & MEM_Zero ){
   63915         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   63916       }else{
   63917         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   63918       }
   63919       break;
   63920     }
   63921     case SQLITE_TEXT: {
   63922       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   63923                               pValue->enc);
   63924       break;
   63925     }
   63926     default: {
   63927       rc = sqlite3_bind_null(pStmt, i);
   63928       break;
   63929     }
   63930   }
   63931   return rc;
   63932 }
   63933 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   63934   int rc;
   63935   Vdbe *p = (Vdbe *)pStmt;
   63936   rc = vdbeUnbind(p, i);
   63937   if( rc==SQLITE_OK ){
   63938     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   63939     sqlite3_mutex_leave(p->db->mutex);
   63940   }
   63941   return rc;
   63942 }
   63943 
   63944 /*
   63945 ** Return the number of wildcards that can be potentially bound to.
   63946 ** This routine is added to support DBD::SQLite.
   63947 */
   63948 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   63949   Vdbe *p = (Vdbe*)pStmt;
   63950   return p ? p->nVar : 0;
   63951 }
   63952 
   63953 /*
   63954 ** Return the name of a wildcard parameter.  Return NULL if the index
   63955 ** is out of range or if the wildcard is unnamed.
   63956 **
   63957 ** The result is always UTF-8.
   63958 */
   63959 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   63960   Vdbe *p = (Vdbe*)pStmt;
   63961   if( p==0 || i<1 || i>p->nzVar ){
   63962     return 0;
   63963   }
   63964   return p->azVar[i-1];
   63965 }
   63966 
   63967 /*
   63968 ** Given a wildcard parameter name, return the index of the variable
   63969 ** with that name.  If there is no variable with the given name,
   63970 ** return 0.
   63971 */
   63972 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   63973   int i;
   63974   if( p==0 ){
   63975     return 0;
   63976   }
   63977   if( zName ){
   63978     for(i=0; i<p->nzVar; i++){
   63979       const char *z = p->azVar[i];
   63980       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
   63981         return i+1;
   63982       }
   63983     }
   63984   }
   63985   return 0;
   63986 }
   63987 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   63988   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   63989 }
   63990 
   63991 /*
   63992 ** Transfer all bindings from the first statement over to the second.
   63993 */
   63994 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   63995   Vdbe *pFrom = (Vdbe*)pFromStmt;
   63996   Vdbe *pTo = (Vdbe*)pToStmt;
   63997   int i;
   63998   assert( pTo->db==pFrom->db );
   63999   assert( pTo->nVar==pFrom->nVar );
   64000   sqlite3_mutex_enter(pTo->db->mutex);
   64001   for(i=0; i<pFrom->nVar; i++){
   64002     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   64003   }
   64004   sqlite3_mutex_leave(pTo->db->mutex);
   64005   return SQLITE_OK;
   64006 }
   64007 
   64008 #ifndef SQLITE_OMIT_DEPRECATED
   64009 /*
   64010 ** Deprecated external interface.  Internal/core SQLite code
   64011 ** should call sqlite3TransferBindings.
   64012 **
   64013 ** Is is misuse to call this routine with statements from different
   64014 ** database connections.  But as this is a deprecated interface, we
   64015 ** will not bother to check for that condition.
   64016 **
   64017 ** If the two statements contain a different number of bindings, then
   64018 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   64019 ** SQLITE_OK is returned.
   64020 */
   64021 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   64022   Vdbe *pFrom = (Vdbe*)pFromStmt;
   64023   Vdbe *pTo = (Vdbe*)pToStmt;
   64024   if( pFrom->nVar!=pTo->nVar ){
   64025     return SQLITE_ERROR;
   64026   }
   64027   if( pTo->isPrepareV2 && pTo->expmask ){
   64028     pTo->expired = 1;
   64029   }
   64030   if( pFrom->isPrepareV2 && pFrom->expmask ){
   64031     pFrom->expired = 1;
   64032   }
   64033   return sqlite3TransferBindings(pFromStmt, pToStmt);
   64034 }
   64035 #endif
   64036 
   64037 /*
   64038 ** Return the sqlite3* database handle to which the prepared statement given
   64039 ** in the argument belongs.  This is the same database handle that was
   64040 ** the first argument to the sqlite3_prepare() that was used to create
   64041 ** the statement in the first place.
   64042 */
   64043 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   64044   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   64045 }
   64046 
   64047 /*
   64048 ** Return true if the prepared statement is guaranteed to not modify the
   64049 ** database.
   64050 */
   64051 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   64052   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   64053 }
   64054 
   64055 /*
   64056 ** Return true if the prepared statement is in need of being reset.
   64057 */
   64058 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   64059   Vdbe *v = (Vdbe*)pStmt;
   64060   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
   64061 }
   64062 
   64063 /*
   64064 ** Return a pointer to the next prepared statement after pStmt associated
   64065 ** with database connection pDb.  If pStmt is NULL, return the first
   64066 ** prepared statement for the database connection.  Return NULL if there
   64067 ** are no more.
   64068 */
   64069 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   64070   sqlite3_stmt *pNext;
   64071   sqlite3_mutex_enter(pDb->mutex);
   64072   if( pStmt==0 ){
   64073     pNext = (sqlite3_stmt*)pDb->pVdbe;
   64074   }else{
   64075     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   64076   }
   64077   sqlite3_mutex_leave(pDb->mutex);
   64078   return pNext;
   64079 }
   64080 
   64081 /*
   64082 ** Return the value of a status counter for a prepared statement
   64083 */
   64084 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   64085   Vdbe *pVdbe = (Vdbe*)pStmt;
   64086   int v = pVdbe->aCounter[op-1];
   64087   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
   64088   return v;
   64089 }
   64090 
   64091 /************** End of vdbeapi.c *********************************************/
   64092 /************** Begin file vdbetrace.c ***************************************/
   64093 /*
   64094 ** 2009 November 25
   64095 **
   64096 ** The author disclaims copyright to this source code.  In place of
   64097 ** a legal notice, here is a blessing:
   64098 **
   64099 **    May you do good and not evil.
   64100 **    May you find forgiveness for yourself and forgive others.
   64101 **    May you share freely, never taking more than you give.
   64102 **
   64103 *************************************************************************
   64104 **
   64105 ** This file contains code used to insert the values of host parameters
   64106 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   64107 **
   64108 ** The Vdbe parse-tree explainer is also found here.
   64109 */
   64110 
   64111 #ifndef SQLITE_OMIT_TRACE
   64112 
   64113 /*
   64114 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   64115 ** bytes in this text up to but excluding the first character in
   64116 ** a host parameter.  If the text contains no host parameters, return
   64117 ** the total number of bytes in the text.
   64118 */
   64119 static int findNextHostParameter(const char *zSql, int *pnToken){
   64120   int tokenType;
   64121   int nTotal = 0;
   64122   int n;
   64123 
   64124   *pnToken = 0;
   64125   while( zSql[0] ){
   64126     n = sqlite3GetToken((u8*)zSql, &tokenType);
   64127     assert( n>0 && tokenType!=TK_ILLEGAL );
   64128     if( tokenType==TK_VARIABLE ){
   64129       *pnToken = n;
   64130       break;
   64131     }
   64132     nTotal += n;
   64133     zSql += n;
   64134   }
   64135   return nTotal;
   64136 }
   64137 
   64138 /*
   64139 ** This function returns a pointer to a nul-terminated string in memory
   64140 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
   64141 ** string contains a copy of zRawSql but with host parameters expanded to
   64142 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
   64143 ** then the returned string holds a copy of zRawSql with "-- " prepended
   64144 ** to each line of text.
   64145 **
   64146 ** The calling function is responsible for making sure the memory returned
   64147 ** is eventually freed.
   64148 **
   64149 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   64150 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   64151 ** string literals, quoted identifier names, and comments.  For text forms,
   64152 ** the host parameter index is found by scanning the perpared
   64153 ** statement for the corresponding OP_Variable opcode.  Once the host
   64154 ** parameter index is known, locate the value in p->aVar[].  Then render
   64155 ** the value as a literal in place of the host parameter name.
   64156 */
   64157 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   64158   Vdbe *p,                 /* The prepared statement being evaluated */
   64159   const char *zRawSql      /* Raw text of the SQL statement */
   64160 ){
   64161   sqlite3 *db;             /* The database connection */
   64162   int idx = 0;             /* Index of a host parameter */
   64163   int nextIndex = 1;       /* Index of next ? host parameter */
   64164   int n;                   /* Length of a token prefix */
   64165   int nToken;              /* Length of the parameter token */
   64166   int i;                   /* Loop counter */
   64167   Mem *pVar;               /* Value of a host parameter */
   64168   StrAccum out;            /* Accumulate the output here */
   64169   char zBase[100];         /* Initial working space */
   64170 
   64171   db = p->db;
   64172   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   64173                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   64174   out.db = db;
   64175   if( db->vdbeExecCnt>1 ){
   64176     while( *zRawSql ){
   64177       const char *zStart = zRawSql;
   64178       while( *(zRawSql++)!='\n' && *zRawSql );
   64179       sqlite3StrAccumAppend(&out, "-- ", 3);
   64180       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
   64181     }
   64182   }else{
   64183     while( zRawSql[0] ){
   64184       n = findNextHostParameter(zRawSql, &nToken);
   64185       assert( n>0 );
   64186       sqlite3StrAccumAppend(&out, zRawSql, n);
   64187       zRawSql += n;
   64188       assert( zRawSql[0] || nToken==0 );
   64189       if( nToken==0 ) break;
   64190       if( zRawSql[0]=='?' ){
   64191         if( nToken>1 ){
   64192           assert( sqlite3Isdigit(zRawSql[1]) );
   64193           sqlite3GetInt32(&zRawSql[1], &idx);
   64194         }else{
   64195           idx = nextIndex;
   64196         }
   64197       }else{
   64198         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   64199         testcase( zRawSql[0]==':' );
   64200         testcase( zRawSql[0]=='$' );
   64201         testcase( zRawSql[0]=='@' );
   64202         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   64203         assert( idx>0 );
   64204       }
   64205       zRawSql += nToken;
   64206       nextIndex = idx + 1;
   64207       assert( idx>0 && idx<=p->nVar );
   64208       pVar = &p->aVar[idx-1];
   64209       if( pVar->flags & MEM_Null ){
   64210         sqlite3StrAccumAppend(&out, "NULL", 4);
   64211       }else if( pVar->flags & MEM_Int ){
   64212         sqlite3XPrintf(&out, "%lld", pVar->u.i);
   64213       }else if( pVar->flags & MEM_Real ){
   64214         sqlite3XPrintf(&out, "%!.15g", pVar->r);
   64215       }else if( pVar->flags & MEM_Str ){
   64216 #ifndef SQLITE_OMIT_UTF16
   64217         u8 enc = ENC(db);
   64218         if( enc!=SQLITE_UTF8 ){
   64219           Mem utf8;
   64220           memset(&utf8, 0, sizeof(utf8));
   64221           utf8.db = db;
   64222           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   64223           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   64224           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
   64225           sqlite3VdbeMemRelease(&utf8);
   64226         }else
   64227 #endif
   64228         {
   64229           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
   64230         }
   64231       }else if( pVar->flags & MEM_Zero ){
   64232         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
   64233       }else{
   64234         assert( pVar->flags & MEM_Blob );
   64235         sqlite3StrAccumAppend(&out, "x'", 2);
   64236         for(i=0; i<pVar->n; i++){
   64237           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
   64238         }
   64239         sqlite3StrAccumAppend(&out, "'", 1);
   64240       }
   64241     }
   64242   }
   64243   return sqlite3StrAccumFinish(&out);
   64244 }
   64245 
   64246 #endif /* #ifndef SQLITE_OMIT_TRACE */
   64247 
   64248 /*****************************************************************************
   64249 ** The following code implements the data-structure explaining logic
   64250 ** for the Vdbe.
   64251 */
   64252 
   64253 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   64254 
   64255 /*
   64256 ** Allocate a new Explain object
   64257 */
   64258 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
   64259   if( pVdbe ){
   64260     sqlite3BeginBenignMalloc();
   64261     Explain *p = sqlite3_malloc( sizeof(Explain) );
   64262     if( p ){
   64263       memset(p, 0, sizeof(*p));
   64264       p->pVdbe = pVdbe;
   64265       sqlite3_free(pVdbe->pExplain);
   64266       pVdbe->pExplain = p;
   64267       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
   64268                           SQLITE_MAX_LENGTH);
   64269       p->str.useMalloc = 2;
   64270     }else{
   64271       sqlite3EndBenignMalloc();
   64272     }
   64273   }
   64274 }
   64275 
   64276 /*
   64277 ** Return true if the Explain ends with a new-line.
   64278 */
   64279 static int endsWithNL(Explain *p){
   64280   return p && p->str.zText && p->str.nChar
   64281            && p->str.zText[p->str.nChar-1]=='\n';
   64282 }
   64283 
   64284 /*
   64285 ** Append text to the indentation
   64286 */
   64287 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
   64288   Explain *p;
   64289   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   64290     va_list ap;
   64291     if( p->nIndent && endsWithNL(p) ){
   64292       int n = p->nIndent;
   64293       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
   64294       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
   64295     }
   64296     va_start(ap, zFormat);
   64297     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
   64298     va_end(ap);
   64299   }
   64300 }
   64301 
   64302 /*
   64303 ** Append a '\n' if there is not already one.
   64304 */
   64305 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
   64306   Explain *p;
   64307   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
   64308     sqlite3StrAccumAppend(&p->str, "\n", 1);
   64309   }
   64310 }
   64311 
   64312 /*
   64313 ** Push a new indentation level.  Subsequent lines will be indented
   64314 ** so that they begin at the current cursor position.
   64315 */
   64316 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
   64317   Explain *p;
   64318   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   64319     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
   64320       const char *z = p->str.zText;
   64321       int i = p->str.nChar-1;
   64322       int x;
   64323       while( i>=0 && z[i]!='\n' ){ i--; }
   64324       x = (p->str.nChar - 1) - i;
   64325       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
   64326         x = p->aIndent[p->nIndent-1];
   64327       }
   64328       p->aIndent[p->nIndent] = x;
   64329     }
   64330     p->nIndent++;
   64331   }
   64332 }
   64333 
   64334 /*
   64335 ** Pop the indentation stack by one level.
   64336 */
   64337 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
   64338   if( p && p->pExplain ) p->pExplain->nIndent--;
   64339 }
   64340 
   64341 /*
   64342 ** Free the indentation structure
   64343 */
   64344 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
   64345   if( pVdbe && pVdbe->pExplain ){
   64346     sqlite3_free(pVdbe->zExplain);
   64347     sqlite3ExplainNL(pVdbe);
   64348     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
   64349     sqlite3_free(pVdbe->pExplain);
   64350     pVdbe->pExplain = 0;
   64351     sqlite3EndBenignMalloc();
   64352   }
   64353 }
   64354 
   64355 /*
   64356 ** Return the explanation of a virtual machine.
   64357 */
   64358 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
   64359   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
   64360 }
   64361 #endif /* defined(SQLITE_DEBUG) */
   64362 
   64363 /************** End of vdbetrace.c *******************************************/
   64364 /************** Begin file vdbe.c ********************************************/
   64365 /*
   64366 ** 2001 September 15
   64367 **
   64368 ** The author disclaims copyright to this source code.  In place of
   64369 ** a legal notice, here is a blessing:
   64370 **
   64371 **    May you do good and not evil.
   64372 **    May you find forgiveness for yourself and forgive others.
   64373 **    May you share freely, never taking more than you give.
   64374 **
   64375 *************************************************************************
   64376 ** The code in this file implements execution method of the
   64377 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
   64378 ** handles housekeeping details such as creating and deleting
   64379 ** VDBE instances.  This file is solely interested in executing
   64380 ** the VDBE program.
   64381 **
   64382 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
   64383 ** to a VDBE.
   64384 **
   64385 ** The SQL parser generates a program which is then executed by
   64386 ** the VDBE to do the work of the SQL statement.  VDBE programs are
   64387 ** similar in form to assembly language.  The program consists of
   64388 ** a linear sequence of operations.  Each operation has an opcode
   64389 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
   64390 ** is a null-terminated string.  Operand P5 is an unsigned character.
   64391 ** Few opcodes use all 5 operands.
   64392 **
   64393 ** Computation results are stored on a set of registers numbered beginning
   64394 ** with 1 and going up to Vdbe.nMem.  Each register can store
   64395 ** either an integer, a null-terminated string, a floating point
   64396 ** number, or the SQL "NULL" value.  An implicit conversion from one
   64397 ** type to the other occurs as necessary.
   64398 **
   64399 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
   64400 ** function which does the work of interpreting a VDBE program.
   64401 ** But other routines are also provided to help in building up
   64402 ** a program instruction by instruction.
   64403 **
   64404 ** Various scripts scan this source file in order to generate HTML
   64405 ** documentation, headers files, or other derived files.  The formatting
   64406 ** of the code in this file is, therefore, important.  See other comments
   64407 ** in this file for details.  If in doubt, do not deviate from existing
   64408 ** commenting and indentation practices when changing or adding code.
   64409 */
   64410 
   64411 /*
   64412 ** Invoke this macro on memory cells just prior to changing the
   64413 ** value of the cell.  This macro verifies that shallow copies are
   64414 ** not misused.
   64415 */
   64416 #ifdef SQLITE_DEBUG
   64417 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
   64418 #else
   64419 # define memAboutToChange(P,M)
   64420 #endif
   64421 
   64422 /*
   64423 ** The following global variable is incremented every time a cursor
   64424 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   64425 ** procedures use this information to make sure that indices are
   64426 ** working correctly.  This variable has no function other than to
   64427 ** help verify the correct operation of the library.
   64428 */
   64429 #ifdef SQLITE_TEST
   64430 SQLITE_API int sqlite3_search_count = 0;
   64431 #endif
   64432 
   64433 /*
   64434 ** When this global variable is positive, it gets decremented once before
   64435 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
   64436 ** field of the sqlite3 structure is set in order to simulate an interrupt.
   64437 **
   64438 ** This facility is used for testing purposes only.  It does not function
   64439 ** in an ordinary build.
   64440 */
   64441 #ifdef SQLITE_TEST
   64442 SQLITE_API int sqlite3_interrupt_count = 0;
   64443 #endif
   64444 
   64445 /*
   64446 ** The next global variable is incremented each type the OP_Sort opcode
   64447 ** is executed.  The test procedures use this information to make sure that
   64448 ** sorting is occurring or not occurring at appropriate times.   This variable
   64449 ** has no function other than to help verify the correct operation of the
   64450 ** library.
   64451 */
   64452 #ifdef SQLITE_TEST
   64453 SQLITE_API int sqlite3_sort_count = 0;
   64454 #endif
   64455 
   64456 /*
   64457 ** The next global variable records the size of the largest MEM_Blob
   64458 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   64459 ** use this information to make sure that the zero-blob functionality
   64460 ** is working correctly.   This variable has no function other than to
   64461 ** help verify the correct operation of the library.
   64462 */
   64463 #ifdef SQLITE_TEST
   64464 SQLITE_API int sqlite3_max_blobsize = 0;
   64465 static void updateMaxBlobsize(Mem *p){
   64466   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   64467     sqlite3_max_blobsize = p->n;
   64468   }
   64469 }
   64470 #endif
   64471 
   64472 /*
   64473 ** The next global variable is incremented each type the OP_Found opcode
   64474 ** is executed. This is used to test whether or not the foreign key
   64475 ** operation implemented using OP_FkIsZero is working. This variable
   64476 ** has no function other than to help verify the correct operation of the
   64477 ** library.
   64478 */
   64479 #ifdef SQLITE_TEST
   64480 SQLITE_API int sqlite3_found_count = 0;
   64481 #endif
   64482 
   64483 /*
   64484 ** Test a register to see if it exceeds the current maximum blob size.
   64485 ** If it does, record the new maximum blob size.
   64486 */
   64487 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   64488 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   64489 #else
   64490 # define UPDATE_MAX_BLOBSIZE(P)
   64491 #endif
   64492 
   64493 /*
   64494 ** Convert the given register into a string if it isn't one
   64495 ** already. Return non-zero if a malloc() fails.
   64496 */
   64497 #define Stringify(P, enc) \
   64498    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   64499      { goto no_mem; }
   64500 
   64501 /*
   64502 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   64503 ** a pointer to a dynamically allocated string where some other entity
   64504 ** is responsible for deallocating that string.  Because the register
   64505 ** does not control the string, it might be deleted without the register
   64506 ** knowing it.
   64507 **
   64508 ** This routine converts an ephemeral string into a dynamically allocated
   64509 ** string that the register itself controls.  In other words, it
   64510 ** converts an MEM_Ephem string into an MEM_Dyn string.
   64511 */
   64512 #define Deephemeralize(P) \
   64513    if( ((P)->flags&MEM_Ephem)!=0 \
   64514        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   64515 
   64516 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   64517 #ifdef SQLITE_OMIT_MERGE_SORT
   64518 # define isSorter(x) 0
   64519 #else
   64520 # define isSorter(x) ((x)->pSorter!=0)
   64521 #endif
   64522 
   64523 /*
   64524 ** Argument pMem points at a register that will be passed to a
   64525 ** user-defined function or returned to the user as the result of a query.
   64526 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
   64527 ** routines.
   64528 */
   64529 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
   64530   int flags = pMem->flags;
   64531   if( flags & MEM_Null ){
   64532     pMem->type = SQLITE_NULL;
   64533   }
   64534   else if( flags & MEM_Int ){
   64535     pMem->type = SQLITE_INTEGER;
   64536   }
   64537   else if( flags & MEM_Real ){
   64538     pMem->type = SQLITE_FLOAT;
   64539   }
   64540   else if( flags & MEM_Str ){
   64541     pMem->type = SQLITE_TEXT;
   64542   }else{
   64543     pMem->type = SQLITE_BLOB;
   64544   }
   64545 }
   64546 
   64547 /*
   64548 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   64549 ** if we run out of memory.
   64550 */
   64551 static VdbeCursor *allocateCursor(
   64552   Vdbe *p,              /* The virtual machine */
   64553   int iCur,             /* Index of the new VdbeCursor */
   64554   int nField,           /* Number of fields in the table or index */
   64555   int iDb,              /* Database the cursor belongs to, or -1 */
   64556   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   64557 ){
   64558   /* Find the memory cell that will be used to store the blob of memory
   64559   ** required for this VdbeCursor structure. It is convenient to use a
   64560   ** vdbe memory cell to manage the memory allocation required for a
   64561   ** VdbeCursor structure for the following reasons:
   64562   **
   64563   **   * Sometimes cursor numbers are used for a couple of different
   64564   **     purposes in a vdbe program. The different uses might require
   64565   **     different sized allocations. Memory cells provide growable
   64566   **     allocations.
   64567   **
   64568   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   64569   **     be freed lazily via the sqlite3_release_memory() API. This
   64570   **     minimizes the number of malloc calls made by the system.
   64571   **
   64572   ** Memory cells for cursors are allocated at the top of the address
   64573   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   64574   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   64575   */
   64576   Mem *pMem = &p->aMem[p->nMem-iCur];
   64577 
   64578   int nByte;
   64579   VdbeCursor *pCx = 0;
   64580   nByte =
   64581       ROUND8(sizeof(VdbeCursor)) +
   64582       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
   64583       2*nField*sizeof(u32);
   64584 
   64585   assert( iCur<p->nCursor );
   64586   if( p->apCsr[iCur] ){
   64587     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   64588     p->apCsr[iCur] = 0;
   64589   }
   64590   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   64591     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   64592     memset(pCx, 0, sizeof(VdbeCursor));
   64593     pCx->iDb = iDb;
   64594     pCx->nField = nField;
   64595     if( nField ){
   64596       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
   64597     }
   64598     if( isBtreeCursor ){
   64599       pCx->pCursor = (BtCursor*)
   64600           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
   64601       sqlite3BtreeCursorZero(pCx->pCursor);
   64602     }
   64603   }
   64604   return pCx;
   64605 }
   64606 
   64607 /*
   64608 ** Try to convert a value into a numeric representation if we can
   64609 ** do so without loss of information.  In other words, if the string
   64610 ** looks like a number, convert it into a number.  If it does not
   64611 ** look like a number, leave it alone.
   64612 */
   64613 static void applyNumericAffinity(Mem *pRec){
   64614   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
   64615     double rValue;
   64616     i64 iValue;
   64617     u8 enc = pRec->enc;
   64618     if( (pRec->flags&MEM_Str)==0 ) return;
   64619     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   64620     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   64621       pRec->u.i = iValue;
   64622       pRec->flags |= MEM_Int;
   64623     }else{
   64624       pRec->r = rValue;
   64625       pRec->flags |= MEM_Real;
   64626     }
   64627   }
   64628 }
   64629 
   64630 /*
   64631 ** Processing is determine by the affinity parameter:
   64632 **
   64633 ** SQLITE_AFF_INTEGER:
   64634 ** SQLITE_AFF_REAL:
   64635 ** SQLITE_AFF_NUMERIC:
   64636 **    Try to convert pRec to an integer representation or a
   64637 **    floating-point representation if an integer representation
   64638 **    is not possible.  Note that the integer representation is
   64639 **    always preferred, even if the affinity is REAL, because
   64640 **    an integer representation is more space efficient on disk.
   64641 **
   64642 ** SQLITE_AFF_TEXT:
   64643 **    Convert pRec to a text representation.
   64644 **
   64645 ** SQLITE_AFF_NONE:
   64646 **    No-op.  pRec is unchanged.
   64647 */
   64648 static void applyAffinity(
   64649   Mem *pRec,          /* The value to apply affinity to */
   64650   char affinity,      /* The affinity to be applied */
   64651   u8 enc              /* Use this text encoding */
   64652 ){
   64653   if( affinity==SQLITE_AFF_TEXT ){
   64654     /* Only attempt the conversion to TEXT if there is an integer or real
   64655     ** representation (blob and NULL do not get converted) but no string
   64656     ** representation.
   64657     */
   64658     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   64659       sqlite3VdbeMemStringify(pRec, enc);
   64660     }
   64661     pRec->flags &= ~(MEM_Real|MEM_Int);
   64662   }else if( affinity!=SQLITE_AFF_NONE ){
   64663     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   64664              || affinity==SQLITE_AFF_NUMERIC );
   64665     applyNumericAffinity(pRec);
   64666     if( pRec->flags & MEM_Real ){
   64667       sqlite3VdbeIntegerAffinity(pRec);
   64668     }
   64669   }
   64670 }
   64671 
   64672 /*
   64673 ** Try to convert the type of a function argument or a result column
   64674 ** into a numeric representation.  Use either INTEGER or REAL whichever
   64675 ** is appropriate.  But only do the conversion if it is possible without
   64676 ** loss of information and return the revised type of the argument.
   64677 */
   64678 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   64679   Mem *pMem = (Mem*)pVal;
   64680   if( pMem->type==SQLITE_TEXT ){
   64681     applyNumericAffinity(pMem);
   64682     sqlite3VdbeMemStoreType(pMem);
   64683   }
   64684   return pMem->type;
   64685 }
   64686 
   64687 /*
   64688 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   64689 ** not the internal Mem* type.
   64690 */
   64691 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   64692   sqlite3_value *pVal,
   64693   u8 affinity,
   64694   u8 enc
   64695 ){
   64696   applyAffinity((Mem *)pVal, affinity, enc);
   64697 }
   64698 
   64699 #ifdef SQLITE_DEBUG
   64700 /*
   64701 ** Write a nice string representation of the contents of cell pMem
   64702 ** into buffer zBuf, length nBuf.
   64703 */
   64704 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   64705   char *zCsr = zBuf;
   64706   int f = pMem->flags;
   64707 
   64708   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   64709 
   64710   if( f&MEM_Blob ){
   64711     int i;
   64712     char c;
   64713     if( f & MEM_Dyn ){
   64714       c = 'z';
   64715       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   64716     }else if( f & MEM_Static ){
   64717       c = 't';
   64718       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   64719     }else if( f & MEM_Ephem ){
   64720       c = 'e';
   64721       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   64722     }else{
   64723       c = 's';
   64724     }
   64725 
   64726     sqlite3_snprintf(100, zCsr, "%c", c);
   64727     zCsr += sqlite3Strlen30(zCsr);
   64728     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   64729     zCsr += sqlite3Strlen30(zCsr);
   64730     for(i=0; i<16 && i<pMem->n; i++){
   64731       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   64732       zCsr += sqlite3Strlen30(zCsr);
   64733     }
   64734     for(i=0; i<16 && i<pMem->n; i++){
   64735       char z = pMem->z[i];
   64736       if( z<32 || z>126 ) *zCsr++ = '.';
   64737       else *zCsr++ = z;
   64738     }
   64739 
   64740     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   64741     zCsr += sqlite3Strlen30(zCsr);
   64742     if( f & MEM_Zero ){
   64743       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   64744       zCsr += sqlite3Strlen30(zCsr);
   64745     }
   64746     *zCsr = '\0';
   64747   }else if( f & MEM_Str ){
   64748     int j, k;
   64749     zBuf[0] = ' ';
   64750     if( f & MEM_Dyn ){
   64751       zBuf[1] = 'z';
   64752       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   64753     }else if( f & MEM_Static ){
   64754       zBuf[1] = 't';
   64755       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   64756     }else if( f & MEM_Ephem ){
   64757       zBuf[1] = 'e';
   64758       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   64759     }else{
   64760       zBuf[1] = 's';
   64761     }
   64762     k = 2;
   64763     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   64764     k += sqlite3Strlen30(&zBuf[k]);
   64765     zBuf[k++] = '[';
   64766     for(j=0; j<15 && j<pMem->n; j++){
   64767       u8 c = pMem->z[j];
   64768       if( c>=0x20 && c<0x7f ){
   64769         zBuf[k++] = c;
   64770       }else{
   64771         zBuf[k++] = '.';
   64772       }
   64773     }
   64774     zBuf[k++] = ']';
   64775     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   64776     k += sqlite3Strlen30(&zBuf[k]);
   64777     zBuf[k++] = 0;
   64778   }
   64779 }
   64780 #endif
   64781 
   64782 #ifdef SQLITE_DEBUG
   64783 /*
   64784 ** Print the value of a register for tracing purposes:
   64785 */
   64786 static void memTracePrint(FILE *out, Mem *p){
   64787   if( p->flags & MEM_Null ){
   64788     fprintf(out, " NULL");
   64789   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   64790     fprintf(out, " si:%lld", p->u.i);
   64791   }else if( p->flags & MEM_Int ){
   64792     fprintf(out, " i:%lld", p->u.i);
   64793 #ifndef SQLITE_OMIT_FLOATING_POINT
   64794   }else if( p->flags & MEM_Real ){
   64795     fprintf(out, " r:%g", p->r);
   64796 #endif
   64797   }else if( p->flags & MEM_RowSet ){
   64798     fprintf(out, " (rowset)");
   64799   }else{
   64800     char zBuf[200];
   64801     sqlite3VdbeMemPrettyPrint(p, zBuf);
   64802     fprintf(out, " ");
   64803     fprintf(out, "%s", zBuf);
   64804   }
   64805 }
   64806 static void registerTrace(FILE *out, int iReg, Mem *p){
   64807   fprintf(out, "REG[%d] = ", iReg);
   64808   memTracePrint(out, p);
   64809   fprintf(out, "\n");
   64810 }
   64811 #endif
   64812 
   64813 #ifdef SQLITE_DEBUG
   64814 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
   64815 #else
   64816 #  define REGISTER_TRACE(R,M)
   64817 #endif
   64818 
   64819 
   64820 #ifdef VDBE_PROFILE
   64821 
   64822 /*
   64823 ** hwtime.h contains inline assembler code for implementing
   64824 ** high-performance timing routines.
   64825 */
   64826 /************** Include hwtime.h in the middle of vdbe.c *********************/
   64827 /************** Begin file hwtime.h ******************************************/
   64828 /*
   64829 ** 2008 May 27
   64830 **
   64831 ** The author disclaims copyright to this source code.  In place of
   64832 ** a legal notice, here is a blessing:
   64833 **
   64834 **    May you do good and not evil.
   64835 **    May you find forgiveness for yourself and forgive others.
   64836 **    May you share freely, never taking more than you give.
   64837 **
   64838 ******************************************************************************
   64839 **
   64840 ** This file contains inline asm code for retrieving "high-performance"
   64841 ** counters for x86 class CPUs.
   64842 */
   64843 #ifndef _HWTIME_H_
   64844 #define _HWTIME_H_
   64845 
   64846 /*
   64847 ** The following routine only works on pentium-class (or newer) processors.
   64848 ** It uses the RDTSC opcode to read the cycle count value out of the
   64849 ** processor and returns that value.  This can be used for high-res
   64850 ** profiling.
   64851 */
   64852 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   64853       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   64854 
   64855   #if defined(__GNUC__)
   64856 
   64857   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64858      unsigned int lo, hi;
   64859      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   64860      return (sqlite_uint64)hi << 32 | lo;
   64861   }
   64862 
   64863   #elif defined(_MSC_VER)
   64864 
   64865   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   64866      __asm {
   64867         rdtsc
   64868         ret       ; return value at EDX:EAX
   64869      }
   64870   }
   64871 
   64872   #endif
   64873 
   64874 #elif (defined(__GNUC__) && defined(__x86_64__))
   64875 
   64876   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64877       unsigned long val;
   64878       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   64879       return val;
   64880   }
   64881 
   64882 #elif (defined(__GNUC__) && defined(__ppc__))
   64883 
   64884   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64885       unsigned long long retval;
   64886       unsigned long junk;
   64887       __asm__ __volatile__ ("\n\
   64888           1:      mftbu   %1\n\
   64889                   mftb    %L0\n\
   64890                   mftbu   %0\n\
   64891                   cmpw    %0,%1\n\
   64892                   bne     1b"
   64893                   : "=r" (retval), "=r" (junk));
   64894       return retval;
   64895   }
   64896 
   64897 #else
   64898 
   64899   #error Need implementation of sqlite3Hwtime() for your platform.
   64900 
   64901   /*
   64902   ** To compile without implementing sqlite3Hwtime() for your platform,
   64903   ** you can remove the above #error and use the following
   64904   ** stub function.  You will lose timing support for many
   64905   ** of the debugging and testing utilities, but it should at
   64906   ** least compile and run.
   64907   */
   64908 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   64909 
   64910 #endif
   64911 
   64912 #endif /* !defined(_HWTIME_H_) */
   64913 
   64914 /************** End of hwtime.h **********************************************/
   64915 /************** Continuing where we left off in vdbe.c ***********************/
   64916 
   64917 #endif
   64918 
   64919 /*
   64920 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
   64921 ** sqlite3_interrupt() routine has been called.  If it has been, then
   64922 ** processing of the VDBE program is interrupted.
   64923 **
   64924 ** This macro added to every instruction that does a jump in order to
   64925 ** implement a loop.  This test used to be on every single instruction,
   64926 ** but that meant we more testing than we needed.  By only testing the
   64927 ** flag on jump instructions, we get a (small) speed improvement.
   64928 */
   64929 #define CHECK_FOR_INTERRUPT \
   64930    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   64931 
   64932 
   64933 #ifndef NDEBUG
   64934 /*
   64935 ** This function is only called from within an assert() expression. It
   64936 ** checks that the sqlite3.nTransaction variable is correctly set to
   64937 ** the number of non-transaction savepoints currently in the
   64938 ** linked list starting at sqlite3.pSavepoint.
   64939 **
   64940 ** Usage:
   64941 **
   64942 **     assert( checkSavepointCount(db) );
   64943 */
   64944 static int checkSavepointCount(sqlite3 *db){
   64945   int n = 0;
   64946   Savepoint *p;
   64947   for(p=db->pSavepoint; p; p=p->pNext) n++;
   64948   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   64949   return 1;
   64950 }
   64951 #endif
   64952 
   64953 /*
   64954 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   64955 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   64956 ** in memory obtained from sqlite3DbMalloc).
   64957 */
   64958 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
   64959   sqlite3 *db = p->db;
   64960   sqlite3DbFree(db, p->zErrMsg);
   64961   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   64962   sqlite3_free(pVtab->zErrMsg);
   64963   pVtab->zErrMsg = 0;
   64964 }
   64965 
   64966 
   64967 /*
   64968 ** Execute as much of a VDBE program as we can then return.
   64969 **
   64970 ** sqlite3VdbeMakeReady() must be called before this routine in order to
   64971 ** close the program with a final OP_Halt and to set up the callbacks
   64972 ** and the error message pointer.
   64973 **
   64974 ** Whenever a row or result data is available, this routine will either
   64975 ** invoke the result callback (if there is one) or return with
   64976 ** SQLITE_ROW.
   64977 **
   64978 ** If an attempt is made to open a locked database, then this routine
   64979 ** will either invoke the busy callback (if there is one) or it will
   64980 ** return SQLITE_BUSY.
   64981 **
   64982 ** If an error occurs, an error message is written to memory obtained
   64983 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
   64984 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
   64985 **
   64986 ** If the callback ever returns non-zero, then the program exits
   64987 ** immediately.  There will be no error message but the p->rc field is
   64988 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
   64989 **
   64990 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
   64991 ** routine to return SQLITE_ERROR.
   64992 **
   64993 ** Other fatal errors return SQLITE_ERROR.
   64994 **
   64995 ** After this routine has finished, sqlite3VdbeFinalize() should be
   64996 ** used to clean up the mess that was left behind.
   64997 */
   64998 SQLITE_PRIVATE int sqlite3VdbeExec(
   64999   Vdbe *p                    /* The VDBE */
   65000 ){
   65001   int pc=0;                  /* The program counter */
   65002   Op *aOp = p->aOp;          /* Copy of p->aOp */
   65003   Op *pOp;                   /* Current operation */
   65004   int rc = SQLITE_OK;        /* Value to return */
   65005   sqlite3 *db = p->db;       /* The database */
   65006   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   65007   u8 encoding = ENC(db);     /* The database encoding */
   65008 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   65009   int checkProgress;         /* True if progress callbacks are enabled */
   65010   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
   65011 #endif
   65012   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   65013   Mem *pIn1 = 0;             /* 1st input operand */
   65014   Mem *pIn2 = 0;             /* 2nd input operand */
   65015   Mem *pIn3 = 0;             /* 3rd input operand */
   65016   Mem *pOut = 0;             /* Output operand */
   65017   int iCompare = 0;          /* Result of last OP_Compare operation */
   65018   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   65019   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
   65020 #ifdef VDBE_PROFILE
   65021   u64 start;                 /* CPU clock count at start of opcode */
   65022   int origPc;                /* Program counter at start of opcode */
   65023 #endif
   65024   /********************************************************************
   65025   ** Automatically generated code
   65026   **
   65027   ** The following union is automatically generated by the
   65028   ** vdbe-compress.tcl script.  The purpose of this union is to
   65029   ** reduce the amount of stack space required by this function.
   65030   ** See comments in the vdbe-compress.tcl script for details.
   65031   */
   65032   union vdbeExecUnion {
   65033     struct OP_Yield_stack_vars {
   65034       int pcDest;
   65035     } aa;
   65036     struct OP_Null_stack_vars {
   65037       int cnt;
   65038     } ab;
   65039     struct OP_Variable_stack_vars {
   65040       Mem *pVar;       /* Value being transferred */
   65041     } ac;
   65042     struct OP_Move_stack_vars {
   65043       char *zMalloc;   /* Holding variable for allocated memory */
   65044       int n;           /* Number of registers left to copy */
   65045       int p1;          /* Register to copy from */
   65046       int p2;          /* Register to copy to */
   65047     } ad;
   65048     struct OP_ResultRow_stack_vars {
   65049       Mem *pMem;
   65050       int i;
   65051     } ae;
   65052     struct OP_Concat_stack_vars {
   65053       i64 nByte;
   65054     } af;
   65055     struct OP_Remainder_stack_vars {
   65056       int flags;      /* Combined MEM_* flags from both inputs */
   65057       i64 iA;         /* Integer value of left operand */
   65058       i64 iB;         /* Integer value of right operand */
   65059       double rA;      /* Real value of left operand */
   65060       double rB;      /* Real value of right operand */
   65061     } ag;
   65062     struct OP_Function_stack_vars {
   65063       int i;
   65064       Mem *pArg;
   65065       sqlite3_context ctx;
   65066       sqlite3_value **apVal;
   65067       int n;
   65068     } ah;
   65069     struct OP_ShiftRight_stack_vars {
   65070       i64 iA;
   65071       u64 uA;
   65072       i64 iB;
   65073       u8 op;
   65074     } ai;
   65075     struct OP_Ge_stack_vars {
   65076       int res;            /* Result of the comparison of pIn1 against pIn3 */
   65077       char affinity;      /* Affinity to use for comparison */
   65078       u16 flags1;         /* Copy of initial value of pIn1->flags */
   65079       u16 flags3;         /* Copy of initial value of pIn3->flags */
   65080     } aj;
   65081     struct OP_Compare_stack_vars {
   65082       int n;
   65083       int i;
   65084       int p1;
   65085       int p2;
   65086       const KeyInfo *pKeyInfo;
   65087       int idx;
   65088       CollSeq *pColl;    /* Collating sequence to use on this term */
   65089       int bRev;          /* True for DESCENDING sort order */
   65090     } ak;
   65091     struct OP_Or_stack_vars {
   65092       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   65093       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   65094     } al;
   65095     struct OP_IfNot_stack_vars {
   65096       int c;
   65097     } am;
   65098     struct OP_Column_stack_vars {
   65099       u32 payloadSize;   /* Number of bytes in the record */
   65100       i64 payloadSize64; /* Number of bytes in the record */
   65101       int p1;            /* P1 value of the opcode */
   65102       int p2;            /* column number to retrieve */
   65103       VdbeCursor *pC;    /* The VDBE cursor */
   65104       char *zRec;        /* Pointer to complete record-data */
   65105       BtCursor *pCrsr;   /* The BTree cursor */
   65106       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   65107       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   65108       int nField;        /* number of fields in the record */
   65109       int len;           /* The length of the serialized data for the column */
   65110       int i;             /* Loop counter */
   65111       char *zData;       /* Part of the record being decoded */
   65112       Mem *pDest;        /* Where to write the extracted value */
   65113       Mem sMem;          /* For storing the record being decoded */
   65114       u8 *zIdx;          /* Index into header */
   65115       u8 *zEndHdr;       /* Pointer to first byte after the header */
   65116       u32 offset;        /* Offset into the data */
   65117       u32 szField;       /* Number of bytes in the content of a field */
   65118       int szHdr;         /* Size of the header size field at start of record */
   65119       int avail;         /* Number of bytes of available data */
   65120       u32 t;             /* A type code from the record header */
   65121       Mem *pReg;         /* PseudoTable input register */
   65122     } an;
   65123     struct OP_Affinity_stack_vars {
   65124       const char *zAffinity;   /* The affinity to be applied */
   65125       char cAff;               /* A single character of affinity */
   65126     } ao;
   65127     struct OP_MakeRecord_stack_vars {
   65128       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   65129       Mem *pRec;             /* The new record */
   65130       u64 nData;             /* Number of bytes of data space */
   65131       int nHdr;              /* Number of bytes of header space */
   65132       i64 nByte;             /* Data space required for this record */
   65133       int nZero;             /* Number of zero bytes at the end of the record */
   65134       int nVarint;           /* Number of bytes in a varint */
   65135       u32 serial_type;       /* Type field */
   65136       Mem *pData0;           /* First field to be combined into the record */
   65137       Mem *pLast;            /* Last field of the record */
   65138       int nField;            /* Number of fields in the record */
   65139       char *zAffinity;       /* The affinity string for the record */
   65140       int file_format;       /* File format to use for encoding */
   65141       int i;                 /* Space used in zNewRecord[] */
   65142       int len;               /* Length of a field */
   65143     } ap;
   65144     struct OP_Count_stack_vars {
   65145       i64 nEntry;
   65146       BtCursor *pCrsr;
   65147     } aq;
   65148     struct OP_Savepoint_stack_vars {
   65149       int p1;                         /* Value of P1 operand */
   65150       char *zName;                    /* Name of savepoint */
   65151       int nName;
   65152       Savepoint *pNew;
   65153       Savepoint *pSavepoint;
   65154       Savepoint *pTmp;
   65155       int iSavepoint;
   65156       int ii;
   65157     } ar;
   65158     struct OP_AutoCommit_stack_vars {
   65159       int desiredAutoCommit;
   65160       int iRollback;
   65161       int turnOnAC;
   65162     } as;
   65163     struct OP_Transaction_stack_vars {
   65164       Btree *pBt;
   65165     } at;
   65166     struct OP_ReadCookie_stack_vars {
   65167       int iMeta;
   65168       int iDb;
   65169       int iCookie;
   65170     } au;
   65171     struct OP_SetCookie_stack_vars {
   65172       Db *pDb;
   65173     } av;
   65174     struct OP_VerifyCookie_stack_vars {
   65175       int iMeta;
   65176       int iGen;
   65177       Btree *pBt;
   65178     } aw;
   65179     struct OP_OpenWrite_stack_vars {
   65180       int nField;
   65181       KeyInfo *pKeyInfo;
   65182       int p2;
   65183       int iDb;
   65184       int wrFlag;
   65185       Btree *pX;
   65186       VdbeCursor *pCur;
   65187       Db *pDb;
   65188     } ax;
   65189     struct OP_OpenEphemeral_stack_vars {
   65190       VdbeCursor *pCx;
   65191     } ay;
   65192     struct OP_SorterOpen_stack_vars {
   65193       VdbeCursor *pCx;
   65194     } az;
   65195     struct OP_OpenPseudo_stack_vars {
   65196       VdbeCursor *pCx;
   65197     } ba;
   65198     struct OP_SeekGt_stack_vars {
   65199       int res;
   65200       int oc;
   65201       VdbeCursor *pC;
   65202       UnpackedRecord r;
   65203       int nField;
   65204       i64 iKey;      /* The rowid we are to seek to */
   65205     } bb;
   65206     struct OP_Seek_stack_vars {
   65207       VdbeCursor *pC;
   65208     } bc;
   65209     struct OP_Found_stack_vars {
   65210       int alreadyExists;
   65211       VdbeCursor *pC;
   65212       int res;
   65213       char *pFree;
   65214       UnpackedRecord *pIdxKey;
   65215       UnpackedRecord r;
   65216       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   65217     } bd;
   65218     struct OP_IsUnique_stack_vars {
   65219       u16 ii;
   65220       VdbeCursor *pCx;
   65221       BtCursor *pCrsr;
   65222       u16 nField;
   65223       Mem *aMx;
   65224       UnpackedRecord r;                  /* B-Tree index search key */
   65225       i64 R;                             /* Rowid stored in register P3 */
   65226     } be;
   65227     struct OP_NotExists_stack_vars {
   65228       VdbeCursor *pC;
   65229       BtCursor *pCrsr;
   65230       int res;
   65231       u64 iKey;
   65232     } bf;
   65233     struct OP_NewRowid_stack_vars {
   65234       i64 v;                 /* The new rowid */
   65235       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   65236       int res;               /* Result of an sqlite3BtreeLast() */
   65237       int cnt;               /* Counter to limit the number of searches */
   65238       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   65239       VdbeFrame *pFrame;     /* Root frame of VDBE */
   65240     } bg;
   65241     struct OP_InsertInt_stack_vars {
   65242       Mem *pData;       /* MEM cell holding data for the record to be inserted */
   65243       Mem *pKey;        /* MEM cell holding key  for the record */
   65244       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   65245       VdbeCursor *pC;   /* Cursor to table into which insert is written */
   65246       int nZero;        /* Number of zero-bytes to append */
   65247       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   65248       const char *zDb;  /* database name - used by the update hook */
   65249       const char *zTbl; /* Table name - used by the opdate hook */
   65250       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   65251     } bh;
   65252     struct OP_Delete_stack_vars {
   65253       i64 iKey;
   65254       VdbeCursor *pC;
   65255     } bi;
   65256     struct OP_SorterCompare_stack_vars {
   65257       VdbeCursor *pC;
   65258       int res;
   65259     } bj;
   65260     struct OP_SorterData_stack_vars {
   65261       VdbeCursor *pC;
   65262     } bk;
   65263     struct OP_RowData_stack_vars {
   65264       VdbeCursor *pC;
   65265       BtCursor *pCrsr;
   65266       u32 n;
   65267       i64 n64;
   65268     } bl;
   65269     struct OP_Rowid_stack_vars {
   65270       VdbeCursor *pC;
   65271       i64 v;
   65272       sqlite3_vtab *pVtab;
   65273       const sqlite3_module *pModule;
   65274     } bm;
   65275     struct OP_NullRow_stack_vars {
   65276       VdbeCursor *pC;
   65277     } bn;
   65278     struct OP_Last_stack_vars {
   65279       VdbeCursor *pC;
   65280       BtCursor *pCrsr;
   65281       int res;
   65282     } bo;
   65283     struct OP_Rewind_stack_vars {
   65284       VdbeCursor *pC;
   65285       BtCursor *pCrsr;
   65286       int res;
   65287     } bp;
   65288     struct OP_Next_stack_vars {
   65289       VdbeCursor *pC;
   65290       int res;
   65291     } bq;
   65292     struct OP_IdxInsert_stack_vars {
   65293       VdbeCursor *pC;
   65294       BtCursor *pCrsr;
   65295       int nKey;
   65296       const char *zKey;
   65297     } br;
   65298     struct OP_IdxDelete_stack_vars {
   65299       VdbeCursor *pC;
   65300       BtCursor *pCrsr;
   65301       int res;
   65302       UnpackedRecord r;
   65303     } bs;
   65304     struct OP_IdxRowid_stack_vars {
   65305       BtCursor *pCrsr;
   65306       VdbeCursor *pC;
   65307       i64 rowid;
   65308     } bt;
   65309     struct OP_IdxGE_stack_vars {
   65310       VdbeCursor *pC;
   65311       int res;
   65312       UnpackedRecord r;
   65313     } bu;
   65314     struct OP_Destroy_stack_vars {
   65315       int iMoved;
   65316       int iCnt;
   65317       Vdbe *pVdbe;
   65318       int iDb;
   65319     } bv;
   65320     struct OP_Clear_stack_vars {
   65321       int nChange;
   65322     } bw;
   65323     struct OP_CreateTable_stack_vars {
   65324       int pgno;
   65325       int flags;
   65326       Db *pDb;
   65327     } bx;
   65328     struct OP_ParseSchema_stack_vars {
   65329       int iDb;
   65330       const char *zMaster;
   65331       char *zSql;
   65332       InitData initData;
   65333     } by;
   65334     struct OP_IntegrityCk_stack_vars {
   65335       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   65336       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   65337       int j;          /* Loop counter */
   65338       int nErr;       /* Number of errors reported */
   65339       char *z;        /* Text of the error report */
   65340       Mem *pnErr;     /* Register keeping track of errors remaining */
   65341     } bz;
   65342     struct OP_RowSetRead_stack_vars {
   65343       i64 val;
   65344     } ca;
   65345     struct OP_RowSetTest_stack_vars {
   65346       int iSet;
   65347       int exists;
   65348     } cb;
   65349     struct OP_Program_stack_vars {
   65350       int nMem;               /* Number of memory registers for sub-program */
   65351       int nByte;              /* Bytes of runtime space required for sub-program */
   65352       Mem *pRt;               /* Register to allocate runtime space */
   65353       Mem *pMem;              /* Used to iterate through memory cells */
   65354       Mem *pEnd;              /* Last memory cell in new array */
   65355       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   65356       SubProgram *pProgram;   /* Sub-program to execute */
   65357       void *t;                /* Token identifying trigger */
   65358     } cc;
   65359     struct OP_Param_stack_vars {
   65360       VdbeFrame *pFrame;
   65361       Mem *pIn;
   65362     } cd;
   65363     struct OP_MemMax_stack_vars {
   65364       Mem *pIn1;
   65365       VdbeFrame *pFrame;
   65366     } ce;
   65367     struct OP_AggStep_stack_vars {
   65368       int n;
   65369       int i;
   65370       Mem *pMem;
   65371       Mem *pRec;
   65372       sqlite3_context ctx;
   65373       sqlite3_value **apVal;
   65374     } cf;
   65375     struct OP_AggFinal_stack_vars {
   65376       Mem *pMem;
   65377     } cg;
   65378     struct OP_Checkpoint_stack_vars {
   65379       int i;                          /* Loop counter */
   65380       int aRes[3];                    /* Results */
   65381       Mem *pMem;                      /* Write results here */
   65382     } ch;
   65383     struct OP_JournalMode_stack_vars {
   65384       Btree *pBt;                     /* Btree to change journal mode of */
   65385       Pager *pPager;                  /* Pager associated with pBt */
   65386       int eNew;                       /* New journal mode */
   65387       int eOld;                       /* The old journal mode */
   65388       const char *zFilename;          /* Name of database file for pPager */
   65389     } ci;
   65390     struct OP_IncrVacuum_stack_vars {
   65391       Btree *pBt;
   65392     } cj;
   65393     struct OP_VBegin_stack_vars {
   65394       VTable *pVTab;
   65395     } ck;
   65396     struct OP_VOpen_stack_vars {
   65397       VdbeCursor *pCur;
   65398       sqlite3_vtab_cursor *pVtabCursor;
   65399       sqlite3_vtab *pVtab;
   65400       sqlite3_module *pModule;
   65401     } cl;
   65402     struct OP_VFilter_stack_vars {
   65403       int nArg;
   65404       int iQuery;
   65405       const sqlite3_module *pModule;
   65406       Mem *pQuery;
   65407       Mem *pArgc;
   65408       sqlite3_vtab_cursor *pVtabCursor;
   65409       sqlite3_vtab *pVtab;
   65410       VdbeCursor *pCur;
   65411       int res;
   65412       int i;
   65413       Mem **apArg;
   65414     } cm;
   65415     struct OP_VColumn_stack_vars {
   65416       sqlite3_vtab *pVtab;
   65417       const sqlite3_module *pModule;
   65418       Mem *pDest;
   65419       sqlite3_context sContext;
   65420     } cn;
   65421     struct OP_VNext_stack_vars {
   65422       sqlite3_vtab *pVtab;
   65423       const sqlite3_module *pModule;
   65424       int res;
   65425       VdbeCursor *pCur;
   65426     } co;
   65427     struct OP_VRename_stack_vars {
   65428       sqlite3_vtab *pVtab;
   65429       Mem *pName;
   65430     } cp;
   65431     struct OP_VUpdate_stack_vars {
   65432       sqlite3_vtab *pVtab;
   65433       sqlite3_module *pModule;
   65434       int nArg;
   65435       int i;
   65436       sqlite_int64 rowid;
   65437       Mem **apArg;
   65438       Mem *pX;
   65439     } cq;
   65440     struct OP_Trace_stack_vars {
   65441       char *zTrace;
   65442       char *z;
   65443     } cr;
   65444   } u;
   65445   /* End automatically generated code
   65446   ********************************************************************/
   65447 
   65448   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   65449   sqlite3VdbeEnter(p);
   65450   if( p->rc==SQLITE_NOMEM ){
   65451     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   65452     ** sqlite3_column_text16() failed.  */
   65453     goto no_mem;
   65454   }
   65455   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   65456   p->rc = SQLITE_OK;
   65457   assert( p->explain==0 );
   65458   p->pResultSet = 0;
   65459   db->busyHandler.nBusy = 0;
   65460   CHECK_FOR_INTERRUPT;
   65461   sqlite3VdbeIOTraceSql(p);
   65462 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   65463   checkProgress = db->xProgress!=0;
   65464 #endif
   65465 #ifdef SQLITE_DEBUG
   65466   sqlite3BeginBenignMalloc();
   65467   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
   65468     int i;
   65469     printf("VDBE Program Listing:\n");
   65470     sqlite3VdbePrintSql(p);
   65471     for(i=0; i<p->nOp; i++){
   65472       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   65473     }
   65474   }
   65475   sqlite3EndBenignMalloc();
   65476 #endif
   65477   for(pc=p->pc; rc==SQLITE_OK; pc++){
   65478     assert( pc>=0 && pc<p->nOp );
   65479     if( db->mallocFailed ) goto no_mem;
   65480 #ifdef VDBE_PROFILE
   65481     origPc = pc;
   65482     start = sqlite3Hwtime();
   65483 #endif
   65484     pOp = &aOp[pc];
   65485 
   65486     /* Only allow tracing if SQLITE_DEBUG is defined.
   65487     */
   65488 #ifdef SQLITE_DEBUG
   65489     if( p->trace ){
   65490       if( pc==0 ){
   65491         printf("VDBE Execution Trace:\n");
   65492         sqlite3VdbePrintSql(p);
   65493       }
   65494       sqlite3VdbePrintOp(p->trace, pc, pOp);
   65495     }
   65496 #endif
   65497 
   65498 
   65499     /* Check to see if we need to simulate an interrupt.  This only happens
   65500     ** if we have a special test build.
   65501     */
   65502 #ifdef SQLITE_TEST
   65503     if( sqlite3_interrupt_count>0 ){
   65504       sqlite3_interrupt_count--;
   65505       if( sqlite3_interrupt_count==0 ){
   65506         sqlite3_interrupt(db);
   65507       }
   65508     }
   65509 #endif
   65510 
   65511 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   65512     /* Call the progress callback if it is configured and the required number
   65513     ** of VDBE ops have been executed (either since this invocation of
   65514     ** sqlite3VdbeExec() or since last time the progress callback was called).
   65515     ** If the progress callback returns non-zero, exit the virtual machine with
   65516     ** a return code SQLITE_ABORT.
   65517     */
   65518     if( checkProgress ){
   65519       if( db->nProgressOps==nProgressOps ){
   65520         int prc;
   65521         prc = db->xProgress(db->pProgressArg);
   65522         if( prc!=0 ){
   65523           rc = SQLITE_INTERRUPT;
   65524           goto vdbe_error_halt;
   65525         }
   65526         nProgressOps = 0;
   65527       }
   65528       nProgressOps++;
   65529     }
   65530 #endif
   65531 
   65532     /* On any opcode with the "out2-prerelase" tag, free any
   65533     ** external allocations out of mem[p2] and set mem[p2] to be
   65534     ** an undefined integer.  Opcodes will either fill in the integer
   65535     ** value or convert mem[p2] to a different type.
   65536     */
   65537     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   65538     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   65539       assert( pOp->p2>0 );
   65540       assert( pOp->p2<=p->nMem );
   65541       pOut = &aMem[pOp->p2];
   65542       memAboutToChange(p, pOut);
   65543       VdbeMemRelease(pOut);
   65544       pOut->flags = MEM_Int;
   65545     }
   65546 
   65547     /* Sanity checking on other operands */
   65548 #ifdef SQLITE_DEBUG
   65549     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   65550       assert( pOp->p1>0 );
   65551       assert( pOp->p1<=p->nMem );
   65552       assert( memIsValid(&aMem[pOp->p1]) );
   65553       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   65554     }
   65555     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   65556       assert( pOp->p2>0 );
   65557       assert( pOp->p2<=p->nMem );
   65558       assert( memIsValid(&aMem[pOp->p2]) );
   65559       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   65560     }
   65561     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   65562       assert( pOp->p3>0 );
   65563       assert( pOp->p3<=p->nMem );
   65564       assert( memIsValid(&aMem[pOp->p3]) );
   65565       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   65566     }
   65567     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   65568       assert( pOp->p2>0 );
   65569       assert( pOp->p2<=p->nMem );
   65570       memAboutToChange(p, &aMem[pOp->p2]);
   65571     }
   65572     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   65573       assert( pOp->p3>0 );
   65574       assert( pOp->p3<=p->nMem );
   65575       memAboutToChange(p, &aMem[pOp->p3]);
   65576     }
   65577 #endif
   65578 
   65579     switch( pOp->opcode ){
   65580 
   65581 /*****************************************************************************
   65582 ** What follows is a massive switch statement where each case implements a
   65583 ** separate instruction in the virtual machine.  If we follow the usual
   65584 ** indentation conventions, each case should be indented by 6 spaces.  But
   65585 ** that is a lot of wasted space on the left margin.  So the code within
   65586 ** the switch statement will break with convention and be flush-left. Another
   65587 ** big comment (similar to this one) will mark the point in the code where
   65588 ** we transition back to normal indentation.
   65589 **
   65590 ** The formatting of each case is important.  The makefile for SQLite
   65591 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   65592 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   65593 ** will be filled with #defines that give unique integer values to each
   65594 ** opcode and the opcodes.c file is filled with an array of strings where
   65595 ** each string is the symbolic name for the corresponding opcode.  If the
   65596 ** case statement is followed by a comment of the form "/# same as ... #/"
   65597 ** that comment is used to determine the particular value of the opcode.
   65598 **
   65599 ** Other keywords in the comment that follows each case are used to
   65600 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   65601 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   65602 ** the mkopcodeh.awk script for additional information.
   65603 **
   65604 ** Documentation about VDBE opcodes is generated by scanning this file
   65605 ** for lines of that contain "Opcode:".  That line and all subsequent
   65606 ** comment lines are used in the generation of the opcode.html documentation
   65607 ** file.
   65608 **
   65609 ** SUMMARY:
   65610 **
   65611 **     Formatting is important to scripts that scan this file.
   65612 **     Do not deviate from the formatting style currently in use.
   65613 **
   65614 *****************************************************************************/
   65615 
   65616 /* Opcode:  Goto * P2 * * *
   65617 **
   65618 ** An unconditional jump to address P2.
   65619 ** The next instruction executed will be
   65620 ** the one at index P2 from the beginning of
   65621 ** the program.
   65622 */
   65623 case OP_Goto: {             /* jump */
   65624   CHECK_FOR_INTERRUPT;
   65625   pc = pOp->p2 - 1;
   65626   break;
   65627 }
   65628 
   65629 /* Opcode:  Gosub P1 P2 * * *
   65630 **
   65631 ** Write the current address onto register P1
   65632 ** and then jump to address P2.
   65633 */
   65634 case OP_Gosub: {            /* jump */
   65635   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   65636   pIn1 = &aMem[pOp->p1];
   65637   assert( (pIn1->flags & MEM_Dyn)==0 );
   65638   memAboutToChange(p, pIn1);
   65639   pIn1->flags = MEM_Int;
   65640   pIn1->u.i = pc;
   65641   REGISTER_TRACE(pOp->p1, pIn1);
   65642   pc = pOp->p2 - 1;
   65643   break;
   65644 }
   65645 
   65646 /* Opcode:  Return P1 * * * *
   65647 **
   65648 ** Jump to the next instruction after the address in register P1.
   65649 */
   65650 case OP_Return: {           /* in1 */
   65651   pIn1 = &aMem[pOp->p1];
   65652   assert( pIn1->flags & MEM_Int );
   65653   pc = (int)pIn1->u.i;
   65654   break;
   65655 }
   65656 
   65657 /* Opcode:  Yield P1 * * * *
   65658 **
   65659 ** Swap the program counter with the value in register P1.
   65660 */
   65661 case OP_Yield: {            /* in1 */
   65662 #if 0  /* local variables moved into u.aa */
   65663   int pcDest;
   65664 #endif /* local variables moved into u.aa */
   65665   pIn1 = &aMem[pOp->p1];
   65666   assert( (pIn1->flags & MEM_Dyn)==0 );
   65667   pIn1->flags = MEM_Int;
   65668   u.aa.pcDest = (int)pIn1->u.i;
   65669   pIn1->u.i = pc;
   65670   REGISTER_TRACE(pOp->p1, pIn1);
   65671   pc = u.aa.pcDest;
   65672   break;
   65673 }
   65674 
   65675 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
   65676 **
   65677 ** Check the value in register P3.  If it is NULL then Halt using
   65678 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   65679 ** value in register P3 is not NULL, then this routine is a no-op.
   65680 */
   65681 case OP_HaltIfNull: {      /* in3 */
   65682   pIn3 = &aMem[pOp->p3];
   65683   if( (pIn3->flags & MEM_Null)==0 ) break;
   65684   /* Fall through into OP_Halt */
   65685 }
   65686 
   65687 /* Opcode:  Halt P1 P2 * P4 *
   65688 **
   65689 ** Exit immediately.  All open cursors, etc are closed
   65690 ** automatically.
   65691 **
   65692 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   65693 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   65694 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   65695 ** whether or not to rollback the current transaction.  Do not rollback
   65696 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   65697 ** then back out all changes that have occurred during this execution of the
   65698 ** VDBE, but do not rollback the transaction.
   65699 **
   65700 ** If P4 is not null then it is an error message string.
   65701 **
   65702 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   65703 ** every program.  So a jump past the last instruction of the program
   65704 ** is the same as executing Halt.
   65705 */
   65706 case OP_Halt: {
   65707   if( pOp->p1==SQLITE_OK && p->pFrame ){
   65708     /* Halt the sub-program. Return control to the parent frame. */
   65709     VdbeFrame *pFrame = p->pFrame;
   65710     p->pFrame = pFrame->pParent;
   65711     p->nFrame--;
   65712     sqlite3VdbeSetChanges(db, p->nChange);
   65713     pc = sqlite3VdbeFrameRestore(pFrame);
   65714     lastRowid = db->lastRowid;
   65715     if( pOp->p2==OE_Ignore ){
   65716       /* Instruction pc is the OP_Program that invoked the sub-program
   65717       ** currently being halted. If the p2 instruction of this OP_Halt
   65718       ** instruction is set to OE_Ignore, then the sub-program is throwing
   65719       ** an IGNORE exception. In this case jump to the address specified
   65720       ** as the p2 of the calling OP_Program.  */
   65721       pc = p->aOp[pc].p2-1;
   65722     }
   65723     aOp = p->aOp;
   65724     aMem = p->aMem;
   65725     break;
   65726   }
   65727 
   65728   p->rc = pOp->p1;
   65729   p->errorAction = (u8)pOp->p2;
   65730   p->pc = pc;
   65731   if( pOp->p4.z ){
   65732     assert( p->rc!=SQLITE_OK );
   65733     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   65734     testcase( sqlite3GlobalConfig.xLog!=0 );
   65735     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
   65736   }else if( p->rc ){
   65737     testcase( sqlite3GlobalConfig.xLog!=0 );
   65738     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
   65739   }
   65740   rc = sqlite3VdbeHalt(p);
   65741   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   65742   if( rc==SQLITE_BUSY ){
   65743     p->rc = rc = SQLITE_BUSY;
   65744   }else{
   65745     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
   65746     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
   65747     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   65748   }
   65749   goto vdbe_return;
   65750 }
   65751 
   65752 /* Opcode: Integer P1 P2 * * *
   65753 **
   65754 ** The 32-bit integer value P1 is written into register P2.
   65755 */
   65756 case OP_Integer: {         /* out2-prerelease */
   65757   pOut->u.i = pOp->p1;
   65758   break;
   65759 }
   65760 
   65761 /* Opcode: Int64 * P2 * P4 *
   65762 **
   65763 ** P4 is a pointer to a 64-bit integer value.
   65764 ** Write that value into register P2.
   65765 */
   65766 case OP_Int64: {           /* out2-prerelease */
   65767   assert( pOp->p4.pI64!=0 );
   65768   pOut->u.i = *pOp->p4.pI64;
   65769   break;
   65770 }
   65771 
   65772 #ifndef SQLITE_OMIT_FLOATING_POINT
   65773 /* Opcode: Real * P2 * P4 *
   65774 **
   65775 ** P4 is a pointer to a 64-bit floating point value.
   65776 ** Write that value into register P2.
   65777 */
   65778 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   65779   pOut->flags = MEM_Real;
   65780   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   65781   pOut->r = *pOp->p4.pReal;
   65782   break;
   65783 }
   65784 #endif
   65785 
   65786 /* Opcode: String8 * P2 * P4 *
   65787 **
   65788 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   65789 ** into an OP_String before it is executed for the first time.
   65790 */
   65791 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   65792   assert( pOp->p4.z!=0 );
   65793   pOp->opcode = OP_String;
   65794   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   65795 
   65796 #ifndef SQLITE_OMIT_UTF16
   65797   if( encoding!=SQLITE_UTF8 ){
   65798     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   65799     if( rc==SQLITE_TOOBIG ) goto too_big;
   65800     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   65801     assert( pOut->zMalloc==pOut->z );
   65802     assert( pOut->flags & MEM_Dyn );
   65803     pOut->zMalloc = 0;
   65804     pOut->flags |= MEM_Static;
   65805     pOut->flags &= ~MEM_Dyn;
   65806     if( pOp->p4type==P4_DYNAMIC ){
   65807       sqlite3DbFree(db, pOp->p4.z);
   65808     }
   65809     pOp->p4type = P4_DYNAMIC;
   65810     pOp->p4.z = pOut->z;
   65811     pOp->p1 = pOut->n;
   65812   }
   65813 #endif
   65814   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   65815     goto too_big;
   65816   }
   65817   /* Fall through to the next case, OP_String */
   65818 }
   65819 
   65820 /* Opcode: String P1 P2 * P4 *
   65821 **
   65822 ** The string value P4 of length P1 (bytes) is stored in register P2.
   65823 */
   65824 case OP_String: {          /* out2-prerelease */
   65825   assert( pOp->p4.z!=0 );
   65826   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   65827   pOut->z = pOp->p4.z;
   65828   pOut->n = pOp->p1;
   65829   pOut->enc = encoding;
   65830   UPDATE_MAX_BLOBSIZE(pOut);
   65831   break;
   65832 }
   65833 
   65834 /* Opcode: Null * P2 P3 * *
   65835 **
   65836 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
   65837 ** NULL into register P3 and ever register in between P2 and P3.  If P3
   65838 ** is less than P2 (typically P3 is zero) then only register P2 is
   65839 ** set to NULL
   65840 */
   65841 case OP_Null: {           /* out2-prerelease */
   65842 #if 0  /* local variables moved into u.ab */
   65843   int cnt;
   65844 #endif /* local variables moved into u.ab */
   65845   u.ab.cnt = pOp->p3-pOp->p2;
   65846   assert( pOp->p3<=p->nMem );
   65847   pOut->flags = MEM_Null;
   65848   while( u.ab.cnt>0 ){
   65849     pOut++;
   65850     memAboutToChange(p, pOut);
   65851     VdbeMemRelease(pOut);
   65852     pOut->flags = MEM_Null;
   65853     u.ab.cnt--;
   65854   }
   65855   break;
   65856 }
   65857 
   65858 
   65859 /* Opcode: Blob P1 P2 * P4
   65860 **
   65861 ** P4 points to a blob of data P1 bytes long.  Store this
   65862 ** blob in register P2.
   65863 */
   65864 case OP_Blob: {                /* out2-prerelease */
   65865   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   65866   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   65867   pOut->enc = encoding;
   65868   UPDATE_MAX_BLOBSIZE(pOut);
   65869   break;
   65870 }
   65871 
   65872 /* Opcode: Variable P1 P2 * P4 *
   65873 **
   65874 ** Transfer the values of bound parameter P1 into register P2
   65875 **
   65876 ** If the parameter is named, then its name appears in P4 and P3==1.
   65877 ** The P4 value is used by sqlite3_bind_parameter_name().
   65878 */
   65879 case OP_Variable: {            /* out2-prerelease */
   65880 #if 0  /* local variables moved into u.ac */
   65881   Mem *pVar;       /* Value being transferred */
   65882 #endif /* local variables moved into u.ac */
   65883 
   65884   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   65885   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
   65886   u.ac.pVar = &p->aVar[pOp->p1 - 1];
   65887   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
   65888     goto too_big;
   65889   }
   65890   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
   65891   UPDATE_MAX_BLOBSIZE(pOut);
   65892   break;
   65893 }
   65894 
   65895 /* Opcode: Move P1 P2 P3 * *
   65896 **
   65897 ** Move the values in register P1..P1+P3-1 over into
   65898 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
   65899 ** left holding a NULL.  It is an error for register ranges
   65900 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
   65901 */
   65902 case OP_Move: {
   65903 #if 0  /* local variables moved into u.ad */
   65904   char *zMalloc;   /* Holding variable for allocated memory */
   65905   int n;           /* Number of registers left to copy */
   65906   int p1;          /* Register to copy from */
   65907   int p2;          /* Register to copy to */
   65908 #endif /* local variables moved into u.ad */
   65909 
   65910   u.ad.n = pOp->p3;
   65911   u.ad.p1 = pOp->p1;
   65912   u.ad.p2 = pOp->p2;
   65913   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
   65914   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
   65915 
   65916   pIn1 = &aMem[u.ad.p1];
   65917   pOut = &aMem[u.ad.p2];
   65918   while( u.ad.n-- ){
   65919     assert( pOut<=&aMem[p->nMem] );
   65920     assert( pIn1<=&aMem[p->nMem] );
   65921     assert( memIsValid(pIn1) );
   65922     memAboutToChange(p, pOut);
   65923     u.ad.zMalloc = pOut->zMalloc;
   65924     pOut->zMalloc = 0;
   65925     sqlite3VdbeMemMove(pOut, pIn1);
   65926 #ifdef SQLITE_DEBUG
   65927     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
   65928       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
   65929     }
   65930 #endif
   65931     pIn1->zMalloc = u.ad.zMalloc;
   65932     REGISTER_TRACE(u.ad.p2++, pOut);
   65933     pIn1++;
   65934     pOut++;
   65935   }
   65936   break;
   65937 }
   65938 
   65939 /* Opcode: Copy P1 P2 * * *
   65940 **
   65941 ** Make a copy of register P1 into register P2.
   65942 **
   65943 ** This instruction makes a deep copy of the value.  A duplicate
   65944 ** is made of any string or blob constant.  See also OP_SCopy.
   65945 */
   65946 case OP_Copy: {             /* in1, out2 */
   65947   pIn1 = &aMem[pOp->p1];
   65948   pOut = &aMem[pOp->p2];
   65949   assert( pOut!=pIn1 );
   65950   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   65951   Deephemeralize(pOut);
   65952   REGISTER_TRACE(pOp->p2, pOut);
   65953   break;
   65954 }
   65955 
   65956 /* Opcode: SCopy P1 P2 * * *
   65957 **
   65958 ** Make a shallow copy of register P1 into register P2.
   65959 **
   65960 ** This instruction makes a shallow copy of the value.  If the value
   65961 ** is a string or blob, then the copy is only a pointer to the
   65962 ** original and hence if the original changes so will the copy.
   65963 ** Worse, if the original is deallocated, the copy becomes invalid.
   65964 ** Thus the program must guarantee that the original will not change
   65965 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   65966 ** copy.
   65967 */
   65968 case OP_SCopy: {            /* in1, out2 */
   65969   pIn1 = &aMem[pOp->p1];
   65970   pOut = &aMem[pOp->p2];
   65971   assert( pOut!=pIn1 );
   65972   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   65973 #ifdef SQLITE_DEBUG
   65974   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   65975 #endif
   65976   REGISTER_TRACE(pOp->p2, pOut);
   65977   break;
   65978 }
   65979 
   65980 /* Opcode: ResultRow P1 P2 * * *
   65981 **
   65982 ** The registers P1 through P1+P2-1 contain a single row of
   65983 ** results. This opcode causes the sqlite3_step() call to terminate
   65984 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   65985 ** structure to provide access to the top P1 values as the result
   65986 ** row.
   65987 */
   65988 case OP_ResultRow: {
   65989 #if 0  /* local variables moved into u.ae */
   65990   Mem *pMem;
   65991   int i;
   65992 #endif /* local variables moved into u.ae */
   65993   assert( p->nResColumn==pOp->p2 );
   65994   assert( pOp->p1>0 );
   65995   assert( pOp->p1+pOp->p2<=p->nMem+1 );
   65996 
   65997   /* If this statement has violated immediate foreign key constraints, do
   65998   ** not return the number of rows modified. And do not RELEASE the statement
   65999   ** transaction. It needs to be rolled back.  */
   66000   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   66001     assert( db->flags&SQLITE_CountRows );
   66002     assert( p->usesStmtJournal );
   66003     break;
   66004   }
   66005 
   66006   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   66007   ** DML statements invoke this opcode to return the number of rows
   66008   ** modified to the user. This is the only way that a VM that
   66009   ** opens a statement transaction may invoke this opcode.
   66010   **
   66011   ** In case this is such a statement, close any statement transaction
   66012   ** opened by this VM before returning control to the user. This is to
   66013   ** ensure that statement-transactions are always nested, not overlapping.
   66014   ** If the open statement-transaction is not closed here, then the user
   66015   ** may step another VM that opens its own statement transaction. This
   66016   ** may lead to overlapping statement transactions.
   66017   **
   66018   ** The statement transaction is never a top-level transaction.  Hence
   66019   ** the RELEASE call below can never fail.
   66020   */
   66021   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   66022   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   66023   if( NEVER(rc!=SQLITE_OK) ){
   66024     break;
   66025   }
   66026 
   66027   /* Invalidate all ephemeral cursor row caches */
   66028   p->cacheCtr = (p->cacheCtr + 2)|1;
   66029 
   66030   /* Make sure the results of the current row are \000 terminated
   66031   ** and have an assigned type.  The results are de-ephemeralized as
   66032   ** a side effect.
   66033   */
   66034   u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
   66035   for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
   66036     assert( memIsValid(&u.ae.pMem[u.ae.i]) );
   66037     Deephemeralize(&u.ae.pMem[u.ae.i]);
   66038     assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
   66039             || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
   66040     sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
   66041     sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
   66042     REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
   66043   }
   66044   if( db->mallocFailed ) goto no_mem;
   66045 
   66046   /* Return SQLITE_ROW
   66047   */
   66048   p->pc = pc + 1;
   66049   rc = SQLITE_ROW;
   66050   goto vdbe_return;
   66051 }
   66052 
   66053 /* Opcode: Concat P1 P2 P3 * *
   66054 **
   66055 ** Add the text in register P1 onto the end of the text in
   66056 ** register P2 and store the result in register P3.
   66057 ** If either the P1 or P2 text are NULL then store NULL in P3.
   66058 **
   66059 **   P3 = P2 || P1
   66060 **
   66061 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   66062 ** if P3 is the same register as P2, the implementation is able
   66063 ** to avoid a memcpy().
   66064 */
   66065 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   66066 #if 0  /* local variables moved into u.af */
   66067   i64 nByte;
   66068 #endif /* local variables moved into u.af */
   66069 
   66070   pIn1 = &aMem[pOp->p1];
   66071   pIn2 = &aMem[pOp->p2];
   66072   pOut = &aMem[pOp->p3];
   66073   assert( pIn1!=pOut );
   66074   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   66075     sqlite3VdbeMemSetNull(pOut);
   66076     break;
   66077   }
   66078   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   66079   Stringify(pIn1, encoding);
   66080   Stringify(pIn2, encoding);
   66081   u.af.nByte = pIn1->n + pIn2->n;
   66082   if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   66083     goto too_big;
   66084   }
   66085   MemSetTypeFlag(pOut, MEM_Str);
   66086   if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
   66087     goto no_mem;
   66088   }
   66089   if( pOut!=pIn2 ){
   66090     memcpy(pOut->z, pIn2->z, pIn2->n);
   66091   }
   66092   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   66093   pOut->z[u.af.nByte] = 0;
   66094   pOut->z[u.af.nByte+1] = 0;
   66095   pOut->flags |= MEM_Term;
   66096   pOut->n = (int)u.af.nByte;
   66097   pOut->enc = encoding;
   66098   UPDATE_MAX_BLOBSIZE(pOut);
   66099   break;
   66100 }
   66101 
   66102 /* Opcode: Add P1 P2 P3 * *
   66103 **
   66104 ** Add the value in register P1 to the value in register P2
   66105 ** and store the result in register P3.
   66106 ** If either input is NULL, the result is NULL.
   66107 */
   66108 /* Opcode: Multiply P1 P2 P3 * *
   66109 **
   66110 **
   66111 ** Multiply the value in register P1 by the value in register P2
   66112 ** and store the result in register P3.
   66113 ** If either input is NULL, the result is NULL.
   66114 */
   66115 /* Opcode: Subtract P1 P2 P3 * *
   66116 **
   66117 ** Subtract the value in register P1 from the value in register P2
   66118 ** and store the result in register P3.
   66119 ** If either input is NULL, the result is NULL.
   66120 */
   66121 /* Opcode: Divide P1 P2 P3 * *
   66122 **
   66123 ** Divide the value in register P1 by the value in register P2
   66124 ** and store the result in register P3 (P3=P2/P1). If the value in
   66125 ** register P1 is zero, then the result is NULL. If either input is
   66126 ** NULL, the result is NULL.
   66127 */
   66128 /* Opcode: Remainder P1 P2 P3 * *
   66129 **
   66130 ** Compute the remainder after integer division of the value in
   66131 ** register P1 by the value in register P2 and store the result in P3.
   66132 ** If the value in register P2 is zero the result is NULL.
   66133 ** If either operand is NULL, the result is NULL.
   66134 */
   66135 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   66136 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   66137 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   66138 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   66139 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   66140 #if 0  /* local variables moved into u.ag */
   66141   int flags;      /* Combined MEM_* flags from both inputs */
   66142   i64 iA;         /* Integer value of left operand */
   66143   i64 iB;         /* Integer value of right operand */
   66144   double rA;      /* Real value of left operand */
   66145   double rB;      /* Real value of right operand */
   66146 #endif /* local variables moved into u.ag */
   66147 
   66148   pIn1 = &aMem[pOp->p1];
   66149   applyNumericAffinity(pIn1);
   66150   pIn2 = &aMem[pOp->p2];
   66151   applyNumericAffinity(pIn2);
   66152   pOut = &aMem[pOp->p3];
   66153   u.ag.flags = pIn1->flags | pIn2->flags;
   66154   if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   66155   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
   66156     u.ag.iA = pIn1->u.i;
   66157     u.ag.iB = pIn2->u.i;
   66158     switch( pOp->opcode ){
   66159       case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66160       case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66161       case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66162       case OP_Divide: {
   66163         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66164         if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
   66165         u.ag.iB /= u.ag.iA;
   66166         break;
   66167       }
   66168       default: {
   66169         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66170         if( u.ag.iA==-1 ) u.ag.iA = 1;
   66171         u.ag.iB %= u.ag.iA;
   66172         break;
   66173       }
   66174     }
   66175     pOut->u.i = u.ag.iB;
   66176     MemSetTypeFlag(pOut, MEM_Int);
   66177   }else{
   66178 fp_math:
   66179     u.ag.rA = sqlite3VdbeRealValue(pIn1);
   66180     u.ag.rB = sqlite3VdbeRealValue(pIn2);
   66181     switch( pOp->opcode ){
   66182       case OP_Add:         u.ag.rB += u.ag.rA;       break;
   66183       case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
   66184       case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
   66185       case OP_Divide: {
   66186         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   66187         if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
   66188         u.ag.rB /= u.ag.rA;
   66189         break;
   66190       }
   66191       default: {
   66192         u.ag.iA = (i64)u.ag.rA;
   66193         u.ag.iB = (i64)u.ag.rB;
   66194         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66195         if( u.ag.iA==-1 ) u.ag.iA = 1;
   66196         u.ag.rB = (double)(u.ag.iB % u.ag.iA);
   66197         break;
   66198       }
   66199     }
   66200 #ifdef SQLITE_OMIT_FLOATING_POINT
   66201     pOut->u.i = u.ag.rB;
   66202     MemSetTypeFlag(pOut, MEM_Int);
   66203 #else
   66204     if( sqlite3IsNaN(u.ag.rB) ){
   66205       goto arithmetic_result_is_null;
   66206     }
   66207     pOut->r = u.ag.rB;
   66208     MemSetTypeFlag(pOut, MEM_Real);
   66209     if( (u.ag.flags & MEM_Real)==0 ){
   66210       sqlite3VdbeIntegerAffinity(pOut);
   66211     }
   66212 #endif
   66213   }
   66214   break;
   66215 
   66216 arithmetic_result_is_null:
   66217   sqlite3VdbeMemSetNull(pOut);
   66218   break;
   66219 }
   66220 
   66221 /* Opcode: CollSeq P1 * * P4
   66222 **
   66223 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   66224 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   66225 ** be returned. This is used by the built-in min(), max() and nullif()
   66226 ** functions.
   66227 **
   66228 ** If P1 is not zero, then it is a register that a subsequent min() or
   66229 ** max() aggregate will set to 1 if the current row is not the minimum or
   66230 ** maximum.  The P1 register is initialized to 0 by this instruction.
   66231 **
   66232 ** The interface used by the implementation of the aforementioned functions
   66233 ** to retrieve the collation sequence set by this opcode is not available
   66234 ** publicly, only to user functions defined in func.c.
   66235 */
   66236 case OP_CollSeq: {
   66237   assert( pOp->p4type==P4_COLLSEQ );
   66238   if( pOp->p1 ){
   66239     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
   66240   }
   66241   break;
   66242 }
   66243 
   66244 /* Opcode: Function P1 P2 P3 P4 P5
   66245 **
   66246 ** Invoke a user function (P4 is a pointer to a Function structure that
   66247 ** defines the function) with P5 arguments taken from register P2 and
   66248 ** successors.  The result of the function is stored in register P3.
   66249 ** Register P3 must not be one of the function inputs.
   66250 **
   66251 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   66252 ** function was determined to be constant at compile time. If the first
   66253 ** argument was constant then bit 0 of P1 is set. This is used to determine
   66254 ** whether meta data associated with a user function argument using the
   66255 ** sqlite3_set_auxdata() API may be safely retained until the next
   66256 ** invocation of this opcode.
   66257 **
   66258 ** See also: AggStep and AggFinal
   66259 */
   66260 case OP_Function: {
   66261 #if 0  /* local variables moved into u.ah */
   66262   int i;
   66263   Mem *pArg;
   66264   sqlite3_context ctx;
   66265   sqlite3_value **apVal;
   66266   int n;
   66267 #endif /* local variables moved into u.ah */
   66268 
   66269   u.ah.n = pOp->p5;
   66270   u.ah.apVal = p->apArg;
   66271   assert( u.ah.apVal || u.ah.n==0 );
   66272   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   66273   pOut = &aMem[pOp->p3];
   66274   memAboutToChange(p, pOut);
   66275 
   66276   assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
   66277   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
   66278   u.ah.pArg = &aMem[pOp->p2];
   66279   for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
   66280     assert( memIsValid(u.ah.pArg) );
   66281     u.ah.apVal[u.ah.i] = u.ah.pArg;
   66282     Deephemeralize(u.ah.pArg);
   66283     sqlite3VdbeMemStoreType(u.ah.pArg);
   66284     REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
   66285   }
   66286 
   66287   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
   66288   if( pOp->p4type==P4_FUNCDEF ){
   66289     u.ah.ctx.pFunc = pOp->p4.pFunc;
   66290     u.ah.ctx.pVdbeFunc = 0;
   66291   }else{
   66292     u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
   66293     u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
   66294   }
   66295 
   66296   u.ah.ctx.s.flags = MEM_Null;
   66297   u.ah.ctx.s.db = db;
   66298   u.ah.ctx.s.xDel = 0;
   66299   u.ah.ctx.s.zMalloc = 0;
   66300 
   66301   /* The output cell may already have a buffer allocated. Move
   66302   ** the pointer to u.ah.ctx.s so in case the user-function can use
   66303   ** the already allocated buffer instead of allocating a new one.
   66304   */
   66305   sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
   66306   MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
   66307 
   66308   u.ah.ctx.isError = 0;
   66309   if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   66310     assert( pOp>aOp );
   66311     assert( pOp[-1].p4type==P4_COLLSEQ );
   66312     assert( pOp[-1].opcode==OP_CollSeq );
   66313     u.ah.ctx.pColl = pOp[-1].p4.pColl;
   66314   }
   66315   db->lastRowid = lastRowid;
   66316   (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
   66317   lastRowid = db->lastRowid;
   66318 
   66319   /* If any auxiliary data functions have been called by this user function,
   66320   ** immediately call the destructor for any non-static values.
   66321   */
   66322   if( u.ah.ctx.pVdbeFunc ){
   66323     sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
   66324     pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
   66325     pOp->p4type = P4_VDBEFUNC;
   66326   }
   66327 
   66328   if( db->mallocFailed ){
   66329     /* Even though a malloc() has failed, the implementation of the
   66330     ** user function may have called an sqlite3_result_XXX() function
   66331     ** to return a value. The following call releases any resources
   66332     ** associated with such a value.
   66333     */
   66334     sqlite3VdbeMemRelease(&u.ah.ctx.s);
   66335     goto no_mem;
   66336   }
   66337 
   66338   /* If the function returned an error, throw an exception */
   66339   if( u.ah.ctx.isError ){
   66340     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
   66341     rc = u.ah.ctx.isError;
   66342   }
   66343 
   66344   /* Copy the result of the function into register P3 */
   66345   sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
   66346   sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
   66347   if( sqlite3VdbeMemTooBig(pOut) ){
   66348     goto too_big;
   66349   }
   66350 
   66351 #if 0
   66352   /* The app-defined function has done something that as caused this
   66353   ** statement to expire.  (Perhaps the function called sqlite3_exec()
   66354   ** with a CREATE TABLE statement.)
   66355   */
   66356   if( p->expired ) rc = SQLITE_ABORT;
   66357 #endif
   66358 
   66359   REGISTER_TRACE(pOp->p3, pOut);
   66360   UPDATE_MAX_BLOBSIZE(pOut);
   66361   break;
   66362 }
   66363 
   66364 /* Opcode: BitAnd P1 P2 P3 * *
   66365 **
   66366 ** Take the bit-wise AND of the values in register P1 and P2 and
   66367 ** store the result in register P3.
   66368 ** If either input is NULL, the result is NULL.
   66369 */
   66370 /* Opcode: BitOr P1 P2 P3 * *
   66371 **
   66372 ** Take the bit-wise OR of the values in register P1 and P2 and
   66373 ** store the result in register P3.
   66374 ** If either input is NULL, the result is NULL.
   66375 */
   66376 /* Opcode: ShiftLeft P1 P2 P3 * *
   66377 **
   66378 ** Shift the integer value in register P2 to the left by the
   66379 ** number of bits specified by the integer in register P1.
   66380 ** Store the result in register P3.
   66381 ** If either input is NULL, the result is NULL.
   66382 */
   66383 /* Opcode: ShiftRight P1 P2 P3 * *
   66384 **
   66385 ** Shift the integer value in register P2 to the right by the
   66386 ** number of bits specified by the integer in register P1.
   66387 ** Store the result in register P3.
   66388 ** If either input is NULL, the result is NULL.
   66389 */
   66390 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   66391 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   66392 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   66393 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   66394 #if 0  /* local variables moved into u.ai */
   66395   i64 iA;
   66396   u64 uA;
   66397   i64 iB;
   66398   u8 op;
   66399 #endif /* local variables moved into u.ai */
   66400 
   66401   pIn1 = &aMem[pOp->p1];
   66402   pIn2 = &aMem[pOp->p2];
   66403   pOut = &aMem[pOp->p3];
   66404   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   66405     sqlite3VdbeMemSetNull(pOut);
   66406     break;
   66407   }
   66408   u.ai.iA = sqlite3VdbeIntValue(pIn2);
   66409   u.ai.iB = sqlite3VdbeIntValue(pIn1);
   66410   u.ai.op = pOp->opcode;
   66411   if( u.ai.op==OP_BitAnd ){
   66412     u.ai.iA &= u.ai.iB;
   66413   }else if( u.ai.op==OP_BitOr ){
   66414     u.ai.iA |= u.ai.iB;
   66415   }else if( u.ai.iB!=0 ){
   66416     assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
   66417 
   66418     /* If shifting by a negative amount, shift in the other direction */
   66419     if( u.ai.iB<0 ){
   66420       assert( OP_ShiftRight==OP_ShiftLeft+1 );
   66421       u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
   66422       u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
   66423     }
   66424 
   66425     if( u.ai.iB>=64 ){
   66426       u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
   66427     }else{
   66428       memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
   66429       if( u.ai.op==OP_ShiftLeft ){
   66430         u.ai.uA <<= u.ai.iB;
   66431       }else{
   66432         u.ai.uA >>= u.ai.iB;
   66433         /* Sign-extend on a right shift of a negative number */
   66434         if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
   66435       }
   66436       memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
   66437     }
   66438   }
   66439   pOut->u.i = u.ai.iA;
   66440   MemSetTypeFlag(pOut, MEM_Int);
   66441   break;
   66442 }
   66443 
   66444 /* Opcode: AddImm  P1 P2 * * *
   66445 **
   66446 ** Add the constant P2 to the value in register P1.
   66447 ** The result is always an integer.
   66448 **
   66449 ** To force any register to be an integer, just add 0.
   66450 */
   66451 case OP_AddImm: {            /* in1 */
   66452   pIn1 = &aMem[pOp->p1];
   66453   memAboutToChange(p, pIn1);
   66454   sqlite3VdbeMemIntegerify(pIn1);
   66455   pIn1->u.i += pOp->p2;
   66456   break;
   66457 }
   66458 
   66459 /* Opcode: MustBeInt P1 P2 * * *
   66460 **
   66461 ** Force the value in register P1 to be an integer.  If the value
   66462 ** in P1 is not an integer and cannot be converted into an integer
   66463 ** without data loss, then jump immediately to P2, or if P2==0
   66464 ** raise an SQLITE_MISMATCH exception.
   66465 */
   66466 case OP_MustBeInt: {            /* jump, in1 */
   66467   pIn1 = &aMem[pOp->p1];
   66468   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   66469   if( (pIn1->flags & MEM_Int)==0 ){
   66470     if( pOp->p2==0 ){
   66471       rc = SQLITE_MISMATCH;
   66472       goto abort_due_to_error;
   66473     }else{
   66474       pc = pOp->p2 - 1;
   66475     }
   66476   }else{
   66477     MemSetTypeFlag(pIn1, MEM_Int);
   66478   }
   66479   break;
   66480 }
   66481 
   66482 #ifndef SQLITE_OMIT_FLOATING_POINT
   66483 /* Opcode: RealAffinity P1 * * * *
   66484 **
   66485 ** If register P1 holds an integer convert it to a real value.
   66486 **
   66487 ** This opcode is used when extracting information from a column that
   66488 ** has REAL affinity.  Such column values may still be stored as
   66489 ** integers, for space efficiency, but after extraction we want them
   66490 ** to have only a real value.
   66491 */
   66492 case OP_RealAffinity: {                  /* in1 */
   66493   pIn1 = &aMem[pOp->p1];
   66494   if( pIn1->flags & MEM_Int ){
   66495     sqlite3VdbeMemRealify(pIn1);
   66496   }
   66497   break;
   66498 }
   66499 #endif
   66500 
   66501 #ifndef SQLITE_OMIT_CAST
   66502 /* Opcode: ToText P1 * * * *
   66503 **
   66504 ** Force the value in register P1 to be text.
   66505 ** If the value is numeric, convert it to a string using the
   66506 ** equivalent of printf().  Blob values are unchanged and
   66507 ** are afterwards simply interpreted as text.
   66508 **
   66509 ** A NULL value is not changed by this routine.  It remains NULL.
   66510 */
   66511 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   66512   pIn1 = &aMem[pOp->p1];
   66513   memAboutToChange(p, pIn1);
   66514   if( pIn1->flags & MEM_Null ) break;
   66515   assert( MEM_Str==(MEM_Blob>>3) );
   66516   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   66517   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   66518   rc = ExpandBlob(pIn1);
   66519   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   66520   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   66521   UPDATE_MAX_BLOBSIZE(pIn1);
   66522   break;
   66523 }
   66524 
   66525 /* Opcode: ToBlob P1 * * * *
   66526 **
   66527 ** Force the value in register P1 to be a BLOB.
   66528 ** If the value is numeric, convert it to a string first.
   66529 ** Strings are simply reinterpreted as blobs with no change
   66530 ** to the underlying data.
   66531 **
   66532 ** A NULL value is not changed by this routine.  It remains NULL.
   66533 */
   66534 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   66535   pIn1 = &aMem[pOp->p1];
   66536   if( pIn1->flags & MEM_Null ) break;
   66537   if( (pIn1->flags & MEM_Blob)==0 ){
   66538     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   66539     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   66540     MemSetTypeFlag(pIn1, MEM_Blob);
   66541   }else{
   66542     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   66543   }
   66544   UPDATE_MAX_BLOBSIZE(pIn1);
   66545   break;
   66546 }
   66547 
   66548 /* Opcode: ToNumeric P1 * * * *
   66549 **
   66550 ** Force the value in register P1 to be numeric (either an
   66551 ** integer or a floating-point number.)
   66552 ** If the value is text or blob, try to convert it to an using the
   66553 ** equivalent of atoi() or atof() and store 0 if no such conversion
   66554 ** is possible.
   66555 **
   66556 ** A NULL value is not changed by this routine.  It remains NULL.
   66557 */
   66558 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   66559   pIn1 = &aMem[pOp->p1];
   66560   sqlite3VdbeMemNumerify(pIn1);
   66561   break;
   66562 }
   66563 #endif /* SQLITE_OMIT_CAST */
   66564 
   66565 /* Opcode: ToInt P1 * * * *
   66566 **
   66567 ** Force the value in register P1 to be an integer.  If
   66568 ** The value is currently a real number, drop its fractional part.
   66569 ** If the value is text or blob, try to convert it to an integer using the
   66570 ** equivalent of atoi() and store 0 if no such conversion is possible.
   66571 **
   66572 ** A NULL value is not changed by this routine.  It remains NULL.
   66573 */
   66574 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   66575   pIn1 = &aMem[pOp->p1];
   66576   if( (pIn1->flags & MEM_Null)==0 ){
   66577     sqlite3VdbeMemIntegerify(pIn1);
   66578   }
   66579   break;
   66580 }
   66581 
   66582 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
   66583 /* Opcode: ToReal P1 * * * *
   66584 **
   66585 ** Force the value in register P1 to be a floating point number.
   66586 ** If The value is currently an integer, convert it.
   66587 ** If the value is text or blob, try to convert it to an integer using the
   66588 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   66589 **
   66590 ** A NULL value is not changed by this routine.  It remains NULL.
   66591 */
   66592 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   66593   pIn1 = &aMem[pOp->p1];
   66594   memAboutToChange(p, pIn1);
   66595   if( (pIn1->flags & MEM_Null)==0 ){
   66596     sqlite3VdbeMemRealify(pIn1);
   66597   }
   66598   break;
   66599 }
   66600 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
   66601 
   66602 /* Opcode: Lt P1 P2 P3 P4 P5
   66603 **
   66604 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   66605 ** jump to address P2.
   66606 **
   66607 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   66608 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   66609 ** bit is clear then fall through if either operand is NULL.
   66610 **
   66611 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   66612 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   66613 ** to coerce both inputs according to this affinity before the
   66614 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   66615 ** affinity is used. Note that the affinity conversions are stored
   66616 ** back into the input registers P1 and P3.  So this opcode can cause
   66617 ** persistent changes to registers P1 and P3.
   66618 **
   66619 ** Once any conversions have taken place, and neither value is NULL,
   66620 ** the values are compared. If both values are blobs then memcmp() is
   66621 ** used to determine the results of the comparison.  If both values
   66622 ** are text, then the appropriate collating function specified in
   66623 ** P4 is  used to do the comparison.  If P4 is not specified then
   66624 ** memcmp() is used to compare text string.  If both values are
   66625 ** numeric, then a numeric comparison is used. If the two values
   66626 ** are of different types, then numbers are considered less than
   66627 ** strings and strings are considered less than blobs.
   66628 **
   66629 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   66630 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   66631 */
   66632 /* Opcode: Ne P1 P2 P3 P4 P5
   66633 **
   66634 ** This works just like the Lt opcode except that the jump is taken if
   66635 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   66636 ** additional information.
   66637 **
   66638 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   66639 ** true or false and is never NULL.  If both operands are NULL then the result
   66640 ** of comparison is false.  If either operand is NULL then the result is true.
   66641 ** If neither operand is NULL the result is the same as it would be if
   66642 ** the SQLITE_NULLEQ flag were omitted from P5.
   66643 */
   66644 /* Opcode: Eq P1 P2 P3 P4 P5
   66645 **
   66646 ** This works just like the Lt opcode except that the jump is taken if
   66647 ** the operands in registers P1 and P3 are equal.
   66648 ** See the Lt opcode for additional information.
   66649 **
   66650 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   66651 ** true or false and is never NULL.  If both operands are NULL then the result
   66652 ** of comparison is true.  If either operand is NULL then the result is false.
   66653 ** If neither operand is NULL the result is the same as it would be if
   66654 ** the SQLITE_NULLEQ flag were omitted from P5.
   66655 */
   66656 /* Opcode: Le P1 P2 P3 P4 P5
   66657 **
   66658 ** This works just like the Lt opcode except that the jump is taken if
   66659 ** the content of register P3 is less than or equal to the content of
   66660 ** register P1.  See the Lt opcode for additional information.
   66661 */
   66662 /* Opcode: Gt P1 P2 P3 P4 P5
   66663 **
   66664 ** This works just like the Lt opcode except that the jump is taken if
   66665 ** the content of register P3 is greater than the content of
   66666 ** register P1.  See the Lt opcode for additional information.
   66667 */
   66668 /* Opcode: Ge P1 P2 P3 P4 P5
   66669 **
   66670 ** This works just like the Lt opcode except that the jump is taken if
   66671 ** the content of register P3 is greater than or equal to the content of
   66672 ** register P1.  See the Lt opcode for additional information.
   66673 */
   66674 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   66675 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   66676 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   66677 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   66678 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   66679 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   66680 #if 0  /* local variables moved into u.aj */
   66681   int res;            /* Result of the comparison of pIn1 against pIn3 */
   66682   char affinity;      /* Affinity to use for comparison */
   66683   u16 flags1;         /* Copy of initial value of pIn1->flags */
   66684   u16 flags3;         /* Copy of initial value of pIn3->flags */
   66685 #endif /* local variables moved into u.aj */
   66686 
   66687   pIn1 = &aMem[pOp->p1];
   66688   pIn3 = &aMem[pOp->p3];
   66689   u.aj.flags1 = pIn1->flags;
   66690   u.aj.flags3 = pIn3->flags;
   66691   if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
   66692     /* One or both operands are NULL */
   66693     if( pOp->p5 & SQLITE_NULLEQ ){
   66694       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   66695       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   66696       ** or not both operands are null.
   66697       */
   66698       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   66699       u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
   66700     }else{
   66701       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   66702       ** then the result is always NULL.
   66703       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   66704       */
   66705       if( pOp->p5 & SQLITE_STOREP2 ){
   66706         pOut = &aMem[pOp->p2];
   66707         MemSetTypeFlag(pOut, MEM_Null);
   66708         REGISTER_TRACE(pOp->p2, pOut);
   66709       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
   66710         pc = pOp->p2-1;
   66711       }
   66712       break;
   66713     }
   66714   }else{
   66715     /* Neither operand is NULL.  Do a comparison. */
   66716     u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
   66717     if( u.aj.affinity ){
   66718       applyAffinity(pIn1, u.aj.affinity, encoding);
   66719       applyAffinity(pIn3, u.aj.affinity, encoding);
   66720       if( db->mallocFailed ) goto no_mem;
   66721     }
   66722 
   66723     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   66724     ExpandBlob(pIn1);
   66725     ExpandBlob(pIn3);
   66726     u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   66727   }
   66728   switch( pOp->opcode ){
   66729     case OP_Eq:    u.aj.res = u.aj.res==0;     break;
   66730     case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
   66731     case OP_Lt:    u.aj.res = u.aj.res<0;      break;
   66732     case OP_Le:    u.aj.res = u.aj.res<=0;     break;
   66733     case OP_Gt:    u.aj.res = u.aj.res>0;      break;
   66734     default:       u.aj.res = u.aj.res>=0;     break;
   66735   }
   66736 
   66737   if( pOp->p5 & SQLITE_STOREP2 ){
   66738     pOut = &aMem[pOp->p2];
   66739     memAboutToChange(p, pOut);
   66740     MemSetTypeFlag(pOut, MEM_Int);
   66741     pOut->u.i = u.aj.res;
   66742     REGISTER_TRACE(pOp->p2, pOut);
   66743   }else if( u.aj.res ){
   66744     pc = pOp->p2-1;
   66745   }
   66746 
   66747   /* Undo any changes made by applyAffinity() to the input registers. */
   66748   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
   66749   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
   66750   break;
   66751 }
   66752 
   66753 /* Opcode: Permutation * * * P4 *
   66754 **
   66755 ** Set the permutation used by the OP_Compare operator to be the array
   66756 ** of integers in P4.
   66757 **
   66758 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
   66759 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
   66760 ** immediately prior to the OP_Compare.
   66761 */
   66762 case OP_Permutation: {
   66763   assert( pOp->p4type==P4_INTARRAY );
   66764   assert( pOp->p4.ai );
   66765   aPermute = pOp->p4.ai;
   66766   break;
   66767 }
   66768 
   66769 /* Opcode: Compare P1 P2 P3 P4 *
   66770 **
   66771 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   66772 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   66773 ** the comparison for use by the next OP_Jump instruct.
   66774 **
   66775 ** P4 is a KeyInfo structure that defines collating sequences and sort
   66776 ** orders for the comparison.  The permutation applies to registers
   66777 ** only.  The KeyInfo elements are used sequentially.
   66778 **
   66779 ** The comparison is a sort comparison, so NULLs compare equal,
   66780 ** NULLs are less than numbers, numbers are less than strings,
   66781 ** and strings are less than blobs.
   66782 */
   66783 case OP_Compare: {
   66784 #if 0  /* local variables moved into u.ak */
   66785   int n;
   66786   int i;
   66787   int p1;
   66788   int p2;
   66789   const KeyInfo *pKeyInfo;
   66790   int idx;
   66791   CollSeq *pColl;    /* Collating sequence to use on this term */
   66792   int bRev;          /* True for DESCENDING sort order */
   66793 #endif /* local variables moved into u.ak */
   66794 
   66795   u.ak.n = pOp->p3;
   66796   u.ak.pKeyInfo = pOp->p4.pKeyInfo;
   66797   assert( u.ak.n>0 );
   66798   assert( u.ak.pKeyInfo!=0 );
   66799   u.ak.p1 = pOp->p1;
   66800   u.ak.p2 = pOp->p2;
   66801 #if SQLITE_DEBUG
   66802   if( aPermute ){
   66803     int k, mx = 0;
   66804     for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   66805     assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
   66806     assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
   66807   }else{
   66808     assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
   66809     assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
   66810   }
   66811 #endif /* SQLITE_DEBUG */
   66812   for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
   66813     u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
   66814     assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
   66815     assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
   66816     REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
   66817     REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
   66818     assert( u.ak.i<u.ak.pKeyInfo->nField );
   66819     u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
   66820     u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
   66821     iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
   66822     if( iCompare ){
   66823       if( u.ak.bRev ) iCompare = -iCompare;
   66824       break;
   66825     }
   66826   }
   66827   aPermute = 0;
   66828   break;
   66829 }
   66830 
   66831 /* Opcode: Jump P1 P2 P3 * *
   66832 **
   66833 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   66834 ** in the most recent OP_Compare instruction the P1 vector was less than
   66835 ** equal to, or greater than the P2 vector, respectively.
   66836 */
   66837 case OP_Jump: {             /* jump */
   66838   if( iCompare<0 ){
   66839     pc = pOp->p1 - 1;
   66840   }else if( iCompare==0 ){
   66841     pc = pOp->p2 - 1;
   66842   }else{
   66843     pc = pOp->p3 - 1;
   66844   }
   66845   break;
   66846 }
   66847 
   66848 /* Opcode: And P1 P2 P3 * *
   66849 **
   66850 ** Take the logical AND of the values in registers P1 and P2 and
   66851 ** write the result into register P3.
   66852 **
   66853 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   66854 ** the other input is NULL.  A NULL and true or two NULLs give
   66855 ** a NULL output.
   66856 */
   66857 /* Opcode: Or P1 P2 P3 * *
   66858 **
   66859 ** Take the logical OR of the values in register P1 and P2 and
   66860 ** store the answer in register P3.
   66861 **
   66862 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   66863 ** even if the other input is NULL.  A NULL and false or two NULLs
   66864 ** give a NULL output.
   66865 */
   66866 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   66867 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   66868 #if 0  /* local variables moved into u.al */
   66869   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   66870   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   66871 #endif /* local variables moved into u.al */
   66872 
   66873   pIn1 = &aMem[pOp->p1];
   66874   if( pIn1->flags & MEM_Null ){
   66875     u.al.v1 = 2;
   66876   }else{
   66877     u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
   66878   }
   66879   pIn2 = &aMem[pOp->p2];
   66880   if( pIn2->flags & MEM_Null ){
   66881     u.al.v2 = 2;
   66882   }else{
   66883     u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
   66884   }
   66885   if( pOp->opcode==OP_And ){
   66886     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   66887     u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
   66888   }else{
   66889     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   66890     u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
   66891   }
   66892   pOut = &aMem[pOp->p3];
   66893   if( u.al.v1==2 ){
   66894     MemSetTypeFlag(pOut, MEM_Null);
   66895   }else{
   66896     pOut->u.i = u.al.v1;
   66897     MemSetTypeFlag(pOut, MEM_Int);
   66898   }
   66899   break;
   66900 }
   66901 
   66902 /* Opcode: Not P1 P2 * * *
   66903 **
   66904 ** Interpret the value in register P1 as a boolean value.  Store the
   66905 ** boolean complement in register P2.  If the value in register P1 is
   66906 ** NULL, then a NULL is stored in P2.
   66907 */
   66908 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   66909   pIn1 = &aMem[pOp->p1];
   66910   pOut = &aMem[pOp->p2];
   66911   if( pIn1->flags & MEM_Null ){
   66912     sqlite3VdbeMemSetNull(pOut);
   66913   }else{
   66914     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   66915   }
   66916   break;
   66917 }
   66918 
   66919 /* Opcode: BitNot P1 P2 * * *
   66920 **
   66921 ** Interpret the content of register P1 as an integer.  Store the
   66922 ** ones-complement of the P1 value into register P2.  If P1 holds
   66923 ** a NULL then store a NULL in P2.
   66924 */
   66925 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   66926   pIn1 = &aMem[pOp->p1];
   66927   pOut = &aMem[pOp->p2];
   66928   if( pIn1->flags & MEM_Null ){
   66929     sqlite3VdbeMemSetNull(pOut);
   66930   }else{
   66931     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
   66932   }
   66933   break;
   66934 }
   66935 
   66936 /* Opcode: Once P1 P2 * * *
   66937 **
   66938 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
   66939 ** set the flag and fall through to the next instruction.
   66940 **
   66941 ** See also: JumpOnce
   66942 */
   66943 case OP_Once: {             /* jump */
   66944   assert( pOp->p1<p->nOnceFlag );
   66945   if( p->aOnceFlag[pOp->p1] ){
   66946     pc = pOp->p2-1;
   66947   }else{
   66948     p->aOnceFlag[pOp->p1] = 1;
   66949   }
   66950   break;
   66951 }
   66952 
   66953 /* Opcode: If P1 P2 P3 * *
   66954 **
   66955 ** Jump to P2 if the value in register P1 is true.  The value
   66956 ** is considered true if it is numeric and non-zero.  If the value
   66957 ** in P1 is NULL then take the jump if P3 is non-zero.
   66958 */
   66959 /* Opcode: IfNot P1 P2 P3 * *
   66960 **
   66961 ** Jump to P2 if the value in register P1 is False.  The value
   66962 ** is considered false if it has a numeric value of zero.  If the value
   66963 ** in P1 is NULL then take the jump if P3 is zero.
   66964 */
   66965 case OP_If:                 /* jump, in1 */
   66966 case OP_IfNot: {            /* jump, in1 */
   66967 #if 0  /* local variables moved into u.am */
   66968   int c;
   66969 #endif /* local variables moved into u.am */
   66970   pIn1 = &aMem[pOp->p1];
   66971   if( pIn1->flags & MEM_Null ){
   66972     u.am.c = pOp->p3;
   66973   }else{
   66974 #ifdef SQLITE_OMIT_FLOATING_POINT
   66975     u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
   66976 #else
   66977     u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
   66978 #endif
   66979     if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
   66980   }
   66981   if( u.am.c ){
   66982     pc = pOp->p2-1;
   66983   }
   66984   break;
   66985 }
   66986 
   66987 /* Opcode: IsNull P1 P2 * * *
   66988 **
   66989 ** Jump to P2 if the value in register P1 is NULL.
   66990 */
   66991 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   66992   pIn1 = &aMem[pOp->p1];
   66993   if( (pIn1->flags & MEM_Null)!=0 ){
   66994     pc = pOp->p2 - 1;
   66995   }
   66996   break;
   66997 }
   66998 
   66999 /* Opcode: NotNull P1 P2 * * *
   67000 **
   67001 ** Jump to P2 if the value in register P1 is not NULL.
   67002 */
   67003 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   67004   pIn1 = &aMem[pOp->p1];
   67005   if( (pIn1->flags & MEM_Null)==0 ){
   67006     pc = pOp->p2 - 1;
   67007   }
   67008   break;
   67009 }
   67010 
   67011 /* Opcode: Column P1 P2 P3 P4 P5
   67012 **
   67013 ** Interpret the data that cursor P1 points to as a structure built using
   67014 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   67015 ** information about the format of the data.)  Extract the P2-th column
   67016 ** from this record.  If there are less that (P2+1)
   67017 ** values in the record, extract a NULL.
   67018 **
   67019 ** The value extracted is stored in register P3.
   67020 **
   67021 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   67022 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   67023 ** the result.
   67024 **
   67025 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   67026 ** then the cache of the cursor is reset prior to extracting the column.
   67027 ** The first OP_Column against a pseudo-table after the value of the content
   67028 ** register has changed should have this bit set.
   67029 */
   67030 case OP_Column: {
   67031 #if 0  /* local variables moved into u.an */
   67032   u32 payloadSize;   /* Number of bytes in the record */
   67033   i64 payloadSize64; /* Number of bytes in the record */
   67034   int p1;            /* P1 value of the opcode */
   67035   int p2;            /* column number to retrieve */
   67036   VdbeCursor *pC;    /* The VDBE cursor */
   67037   char *zRec;        /* Pointer to complete record-data */
   67038   BtCursor *pCrsr;   /* The BTree cursor */
   67039   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   67040   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   67041   int nField;        /* number of fields in the record */
   67042   int len;           /* The length of the serialized data for the column */
   67043   int i;             /* Loop counter */
   67044   char *zData;       /* Part of the record being decoded */
   67045   Mem *pDest;        /* Where to write the extracted value */
   67046   Mem sMem;          /* For storing the record being decoded */
   67047   u8 *zIdx;          /* Index into header */
   67048   u8 *zEndHdr;       /* Pointer to first byte after the header */
   67049   u32 offset;        /* Offset into the data */
   67050   u32 szField;       /* Number of bytes in the content of a field */
   67051   int szHdr;         /* Size of the header size field at start of record */
   67052   int avail;         /* Number of bytes of available data */
   67053   u32 t;             /* A type code from the record header */
   67054   Mem *pReg;         /* PseudoTable input register */
   67055 #endif /* local variables moved into u.an */
   67056 
   67057 
   67058   u.an.p1 = pOp->p1;
   67059   u.an.p2 = pOp->p2;
   67060   u.an.pC = 0;
   67061   memset(&u.an.sMem, 0, sizeof(u.an.sMem));
   67062   assert( u.an.p1<p->nCursor );
   67063   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   67064   u.an.pDest = &aMem[pOp->p3];
   67065   memAboutToChange(p, u.an.pDest);
   67066   u.an.zRec = 0;
   67067 
   67068   /* This block sets the variable u.an.payloadSize to be the total number of
   67069   ** bytes in the record.
   67070   **
   67071   ** u.an.zRec is set to be the complete text of the record if it is available.
   67072   ** The complete record text is always available for pseudo-tables
   67073   ** If the record is stored in a cursor, the complete record text
   67074   ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
   67075   ** If the data is unavailable,  u.an.zRec is set to NULL.
   67076   **
   67077   ** We also compute the number of columns in the record.  For cursors,
   67078   ** the number of columns is stored in the VdbeCursor.nField element.
   67079   */
   67080   u.an.pC = p->apCsr[u.an.p1];
   67081   assert( u.an.pC!=0 );
   67082 #ifndef SQLITE_OMIT_VIRTUALTABLE
   67083   assert( u.an.pC->pVtabCursor==0 );
   67084 #endif
   67085   u.an.pCrsr = u.an.pC->pCursor;
   67086   if( u.an.pCrsr!=0 ){
   67087     /* The record is stored in a B-Tree */
   67088     rc = sqlite3VdbeCursorMoveto(u.an.pC);
   67089     if( rc ) goto abort_due_to_error;
   67090     if( u.an.pC->nullRow ){
   67091       u.an.payloadSize = 0;
   67092     }else if( u.an.pC->cacheStatus==p->cacheCtr ){
   67093       u.an.payloadSize = u.an.pC->payloadSize;
   67094       u.an.zRec = (char*)u.an.pC->aRow;
   67095     }else if( u.an.pC->isIndex ){
   67096       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
   67097       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
   67098       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
   67099       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   67100       ** payload size, so it is impossible for u.an.payloadSize64 to be
   67101       ** larger than 32 bits. */
   67102       assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
   67103       u.an.payloadSize = (u32)u.an.payloadSize64;
   67104     }else{
   67105       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
   67106       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
   67107       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   67108     }
   67109   }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
   67110     u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
   67111     assert( u.an.pReg->flags & MEM_Blob );
   67112     assert( memIsValid(u.an.pReg) );
   67113     u.an.payloadSize = u.an.pReg->n;
   67114     u.an.zRec = u.an.pReg->z;
   67115     u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
   67116     assert( u.an.payloadSize==0 || u.an.zRec!=0 );
   67117   }else{
   67118     /* Consider the row to be NULL */
   67119     u.an.payloadSize = 0;
   67120   }
   67121 
   67122   /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
   67123   ** nullRow or because of a corrupt database. */
   67124   if( u.an.payloadSize==0 ){
   67125     MemSetTypeFlag(u.an.pDest, MEM_Null);
   67126     goto op_column_out;
   67127   }
   67128   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
   67129   if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   67130     goto too_big;
   67131   }
   67132 
   67133   u.an.nField = u.an.pC->nField;
   67134   assert( u.an.p2<u.an.nField );
   67135 
   67136   /* Read and parse the table header.  Store the results of the parse
   67137   ** into the record header cache fields of the cursor.
   67138   */
   67139   u.an.aType = u.an.pC->aType;
   67140   if( u.an.pC->cacheStatus==p->cacheCtr ){
   67141     u.an.aOffset = u.an.pC->aOffset;
   67142   }else{
   67143     assert(u.an.aType);
   67144     u.an.avail = 0;
   67145     u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
   67146     u.an.pC->payloadSize = u.an.payloadSize;
   67147     u.an.pC->cacheStatus = p->cacheCtr;
   67148 
   67149     /* Figure out how many bytes are in the header */
   67150     if( u.an.zRec ){
   67151       u.an.zData = u.an.zRec;
   67152     }else{
   67153       if( u.an.pC->isIndex ){
   67154         u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
   67155       }else{
   67156         u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
   67157       }
   67158       /* If KeyFetch()/DataFetch() managed to get the entire payload,
   67159       ** save the payload in the u.an.pC->aRow cache.  That will save us from
   67160       ** having to make additional calls to fetch the content portion of
   67161       ** the record.
   67162       */
   67163       assert( u.an.avail>=0 );
   67164       if( u.an.payloadSize <= (u32)u.an.avail ){
   67165         u.an.zRec = u.an.zData;
   67166         u.an.pC->aRow = (u8*)u.an.zData;
   67167       }else{
   67168         u.an.pC->aRow = 0;
   67169       }
   67170     }
   67171     /* The following assert is true in all cases accept when
   67172     ** the database file has been corrupted externally.
   67173     **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
   67174     u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
   67175 
   67176     /* Make sure a corrupt database has not given us an oversize header.
   67177     ** Do this now to avoid an oversize memory allocation.
   67178     **
   67179     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   67180     ** types use so much data space that there can only be 4096 and 32 of
   67181     ** them, respectively.  So the maximum header length results from a
   67182     ** 3-byte type for each of the maximum of 32768 columns plus three
   67183     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   67184     */
   67185     if( u.an.offset > 98307 ){
   67186       rc = SQLITE_CORRUPT_BKPT;
   67187       goto op_column_out;
   67188     }
   67189 
   67190     /* Compute in u.an.len the number of bytes of data we need to read in order
   67191     ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
   67192     ** u.an.nField might be significantly less than the true number of columns
   67193     ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
   67194     ** We want to minimize u.an.len in order to limit the size of the memory
   67195     ** allocation, especially if a corrupt database file has caused u.an.offset
   67196     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
   67197     ** still exceed Robson memory allocation limits on some configurations.
   67198     ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
   67199     ** will likely be much smaller since u.an.nField will likely be less than
   67200     ** 20 or so.  This insures that Robson memory allocation limits are
   67201     ** not exceeded even for corrupt database files.
   67202     */
   67203     u.an.len = u.an.nField*5 + 3;
   67204     if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
   67205 
   67206     /* The KeyFetch() or DataFetch() above are fast and will get the entire
   67207     ** record header in most cases.  But they will fail to get the complete
   67208     ** record header if the record header does not fit on a single page
   67209     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
   67210     ** acquire the complete header text.
   67211     */
   67212     if( !u.an.zRec && u.an.avail<u.an.len ){
   67213       u.an.sMem.flags = 0;
   67214       u.an.sMem.db = 0;
   67215       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
   67216       if( rc!=SQLITE_OK ){
   67217         goto op_column_out;
   67218       }
   67219       u.an.zData = u.an.sMem.z;
   67220     }
   67221     u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
   67222     u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
   67223 
   67224     /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
   67225     ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
   67226     ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
   67227     ** of the record to the start of the data for the u.an.i-th column
   67228     */
   67229     for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
   67230       if( u.an.zIdx<u.an.zEndHdr ){
   67231         u.an.aOffset[u.an.i] = u.an.offset;
   67232         if( u.an.zIdx[0]<0x80 ){
   67233           u.an.t = u.an.zIdx[0];
   67234           u.an.zIdx++;
   67235         }else{
   67236           u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
   67237         }
   67238         u.an.aType[u.an.i] = u.an.t;
   67239         u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
   67240         u.an.offset += u.an.szField;
   67241         if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
   67242           u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   67243           break;
   67244         }
   67245       }else{
   67246         /* If u.an.i is less that u.an.nField, then there are less fields in this
   67247         ** record than SetNumColumns indicated there are columns in the
   67248         ** table. Set the u.an.offset for any extra columns not present in
   67249         ** the record to 0. This tells code below to store a NULL
   67250         ** instead of deserializing a value from the record.
   67251         */
   67252         u.an.aOffset[u.an.i] = 0;
   67253       }
   67254     }
   67255     sqlite3VdbeMemRelease(&u.an.sMem);
   67256     u.an.sMem.flags = MEM_Null;
   67257 
   67258     /* If we have read more header data than was contained in the header,
   67259     ** or if the end of the last field appears to be past the end of the
   67260     ** record, or if the end of the last field appears to be before the end
   67261     ** of the record (when all fields present), then we must be dealing
   67262     ** with a corrupt database.
   67263     */
   67264     if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
   67265          || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
   67266       rc = SQLITE_CORRUPT_BKPT;
   67267       goto op_column_out;
   67268     }
   67269   }
   67270 
   67271   /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
   67272   ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
   67273   ** then there are not enough fields in the record to satisfy the
   67274   ** request.  In this case, set the value NULL or to P4 if P4 is
   67275   ** a pointer to a Mem object.
   67276   */
   67277   if( u.an.aOffset[u.an.p2] ){
   67278     assert( rc==SQLITE_OK );
   67279     if( u.an.zRec ){
   67280       VdbeMemRelease(u.an.pDest);
   67281       sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
   67282     }else{
   67283       u.an.len = sqlite3VdbeSerialTypeLen(u.an.aType[u.an.p2]);
   67284       sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
   67285       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len, u.an.pC->isIndex, &u.an.sMem);
   67286       if( rc!=SQLITE_OK ){
   67287         goto op_column_out;
   67288       }
   67289       u.an.zData = u.an.sMem.z;
   67290       sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.aType[u.an.p2], u.an.pDest);
   67291     }
   67292     u.an.pDest->enc = encoding;
   67293   }else{
   67294     if( pOp->p4type==P4_MEM ){
   67295       sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
   67296     }else{
   67297       MemSetTypeFlag(u.an.pDest, MEM_Null);
   67298     }
   67299   }
   67300 
   67301   /* If we dynamically allocated space to hold the data (in the
   67302   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   67303   ** dynamically allocated space over to the u.an.pDest structure.
   67304   ** This prevents a memory copy.
   67305   */
   67306   if( u.an.sMem.zMalloc ){
   67307     assert( u.an.sMem.z==u.an.sMem.zMalloc );
   67308     assert( !(u.an.pDest->flags & MEM_Dyn) );
   67309     assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
   67310     u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
   67311     u.an.pDest->flags |= MEM_Term;
   67312     u.an.pDest->z = u.an.sMem.z;
   67313     u.an.pDest->zMalloc = u.an.sMem.zMalloc;
   67314   }
   67315 
   67316   rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
   67317 
   67318 op_column_out:
   67319   UPDATE_MAX_BLOBSIZE(u.an.pDest);
   67320   REGISTER_TRACE(pOp->p3, u.an.pDest);
   67321   break;
   67322 }
   67323 
   67324 /* Opcode: Affinity P1 P2 * P4 *
   67325 **
   67326 ** Apply affinities to a range of P2 registers starting with P1.
   67327 **
   67328 ** P4 is a string that is P2 characters long. The nth character of the
   67329 ** string indicates the column affinity that should be used for the nth
   67330 ** memory cell in the range.
   67331 */
   67332 case OP_Affinity: {
   67333 #if 0  /* local variables moved into u.ao */
   67334   const char *zAffinity;   /* The affinity to be applied */
   67335   char cAff;               /* A single character of affinity */
   67336 #endif /* local variables moved into u.ao */
   67337 
   67338   u.ao.zAffinity = pOp->p4.z;
   67339   assert( u.ao.zAffinity!=0 );
   67340   assert( u.ao.zAffinity[pOp->p2]==0 );
   67341   pIn1 = &aMem[pOp->p1];
   67342   while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
   67343     assert( pIn1 <= &p->aMem[p->nMem] );
   67344     assert( memIsValid(pIn1) );
   67345     ExpandBlob(pIn1);
   67346     applyAffinity(pIn1, u.ao.cAff, encoding);
   67347     pIn1++;
   67348   }
   67349   break;
   67350 }
   67351 
   67352 /* Opcode: MakeRecord P1 P2 P3 P4 *
   67353 **
   67354 ** Convert P2 registers beginning with P1 into the [record format]
   67355 ** use as a data record in a database table or as a key
   67356 ** in an index.  The OP_Column opcode can decode the record later.
   67357 **
   67358 ** P4 may be a string that is P2 characters long.  The nth character of the
   67359 ** string indicates the column affinity that should be used for the nth
   67360 ** field of the index key.
   67361 **
   67362 ** The mapping from character to affinity is given by the SQLITE_AFF_
   67363 ** macros defined in sqliteInt.h.
   67364 **
   67365 ** If P4 is NULL then all index fields have the affinity NONE.
   67366 */
   67367 case OP_MakeRecord: {
   67368 #if 0  /* local variables moved into u.ap */
   67369   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   67370   Mem *pRec;             /* The new record */
   67371   u64 nData;             /* Number of bytes of data space */
   67372   int nHdr;              /* Number of bytes of header space */
   67373   i64 nByte;             /* Data space required for this record */
   67374   int nZero;             /* Number of zero bytes at the end of the record */
   67375   int nVarint;           /* Number of bytes in a varint */
   67376   u32 serial_type;       /* Type field */
   67377   Mem *pData0;           /* First field to be combined into the record */
   67378   Mem *pLast;            /* Last field of the record */
   67379   int nField;            /* Number of fields in the record */
   67380   char *zAffinity;       /* The affinity string for the record */
   67381   int file_format;       /* File format to use for encoding */
   67382   int i;                 /* Space used in zNewRecord[] */
   67383   int len;               /* Length of a field */
   67384 #endif /* local variables moved into u.ap */
   67385 
   67386   /* Assuming the record contains N fields, the record format looks
   67387   ** like this:
   67388   **
   67389   ** ------------------------------------------------------------------------
   67390   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   67391   ** ------------------------------------------------------------------------
   67392   **
   67393   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   67394   ** and so froth.
   67395   **
   67396   ** Each type field is a varint representing the serial type of the
   67397   ** corresponding data element (see sqlite3VdbeSerialType()). The
   67398   ** hdr-size field is also a varint which is the offset from the beginning
   67399   ** of the record to data0.
   67400   */
   67401   u.ap.nData = 0;         /* Number of bytes of data space */
   67402   u.ap.nHdr = 0;          /* Number of bytes of header space */
   67403   u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
   67404   u.ap.nField = pOp->p1;
   67405   u.ap.zAffinity = pOp->p4.z;
   67406   assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
   67407   u.ap.pData0 = &aMem[u.ap.nField];
   67408   u.ap.nField = pOp->p2;
   67409   u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
   67410   u.ap.file_format = p->minWriteFileFormat;
   67411 
   67412   /* Identify the output register */
   67413   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   67414   pOut = &aMem[pOp->p3];
   67415   memAboutToChange(p, pOut);
   67416 
   67417   /* Loop through the elements that will make up the record to figure
   67418   ** out how much space is required for the new record.
   67419   */
   67420   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
   67421     assert( memIsValid(u.ap.pRec) );
   67422     if( u.ap.zAffinity ){
   67423       applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
   67424     }
   67425     if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
   67426       sqlite3VdbeMemExpandBlob(u.ap.pRec);
   67427     }
   67428     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
   67429     u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
   67430     u.ap.nData += u.ap.len;
   67431     u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
   67432     if( u.ap.pRec->flags & MEM_Zero ){
   67433       /* Only pure zero-filled BLOBs can be input to this Opcode.
   67434       ** We do not allow blobs with a prefix and a zero-filled tail. */
   67435       u.ap.nZero += u.ap.pRec->u.nZero;
   67436     }else if( u.ap.len ){
   67437       u.ap.nZero = 0;
   67438     }
   67439   }
   67440 
   67441   /* Add the initial header varint and total the size */
   67442   u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
   67443   if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
   67444     u.ap.nHdr++;
   67445   }
   67446   u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
   67447   if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   67448     goto too_big;
   67449   }
   67450 
   67451   /* Make sure the output register has a buffer large enough to store
   67452   ** the new record. The output register (pOp->p3) is not allowed to
   67453   ** be one of the input registers (because the following call to
   67454   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   67455   */
   67456   if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
   67457     goto no_mem;
   67458   }
   67459   u.ap.zNewRecord = (u8 *)pOut->z;
   67460 
   67461   /* Write the record */
   67462   u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
   67463   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
   67464     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
   67465     u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
   67466   }
   67467   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
   67468     u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
   67469   }
   67470   assert( u.ap.i==u.ap.nByte );
   67471 
   67472   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   67473   pOut->n = (int)u.ap.nByte;
   67474   pOut->flags = MEM_Blob | MEM_Dyn;
   67475   pOut->xDel = 0;
   67476   if( u.ap.nZero ){
   67477     pOut->u.nZero = u.ap.nZero;
   67478     pOut->flags |= MEM_Zero;
   67479   }
   67480   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   67481   REGISTER_TRACE(pOp->p3, pOut);
   67482   UPDATE_MAX_BLOBSIZE(pOut);
   67483   break;
   67484 }
   67485 
   67486 /* Opcode: Count P1 P2 * * *
   67487 **
   67488 ** Store the number of entries (an integer value) in the table or index
   67489 ** opened by cursor P1 in register P2
   67490 */
   67491 #ifndef SQLITE_OMIT_BTREECOUNT
   67492 case OP_Count: {         /* out2-prerelease */
   67493 #if 0  /* local variables moved into u.aq */
   67494   i64 nEntry;
   67495   BtCursor *pCrsr;
   67496 #endif /* local variables moved into u.aq */
   67497 
   67498   u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
   67499   if( ALWAYS(u.aq.pCrsr) ){
   67500     rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
   67501   }else{
   67502     u.aq.nEntry = 0;
   67503   }
   67504   pOut->u.i = u.aq.nEntry;
   67505   break;
   67506 }
   67507 #endif
   67508 
   67509 /* Opcode: Savepoint P1 * * P4 *
   67510 **
   67511 ** Open, release or rollback the savepoint named by parameter P4, depending
   67512 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   67513 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   67514 */
   67515 case OP_Savepoint: {
   67516 #if 0  /* local variables moved into u.ar */
   67517   int p1;                         /* Value of P1 operand */
   67518   char *zName;                    /* Name of savepoint */
   67519   int nName;
   67520   Savepoint *pNew;
   67521   Savepoint *pSavepoint;
   67522   Savepoint *pTmp;
   67523   int iSavepoint;
   67524   int ii;
   67525 #endif /* local variables moved into u.ar */
   67526 
   67527   u.ar.p1 = pOp->p1;
   67528   u.ar.zName = pOp->p4.z;
   67529 
   67530   /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
   67531   ** transaction, then there cannot be any savepoints.
   67532   */
   67533   assert( db->pSavepoint==0 || db->autoCommit==0 );
   67534   assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
   67535   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   67536   assert( checkSavepointCount(db) );
   67537 
   67538   if( u.ar.p1==SAVEPOINT_BEGIN ){
   67539     if( db->writeVdbeCnt>0 ){
   67540       /* A new savepoint cannot be created if there are active write
   67541       ** statements (i.e. open read/write incremental blob handles).
   67542       */
   67543       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   67544         "SQL statements in progress");
   67545       rc = SQLITE_BUSY;
   67546     }else{
   67547       u.ar.nName = sqlite3Strlen30(u.ar.zName);
   67548 
   67549 #ifndef SQLITE_OMIT_VIRTUALTABLE
   67550       /* This call is Ok even if this savepoint is actually a transaction
   67551       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
   67552       ** If this is a transaction savepoint being opened, it is guaranteed
   67553       ** that the db->aVTrans[] array is empty.  */
   67554       assert( db->autoCommit==0 || db->nVTrans==0 );
   67555       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
   67556                                 db->nStatement+db->nSavepoint);
   67557       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   67558 #endif
   67559 
   67560       /* Create a new savepoint structure. */
   67561       u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
   67562       if( u.ar.pNew ){
   67563         u.ar.pNew->zName = (char *)&u.ar.pNew[1];
   67564         memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
   67565 
   67566         /* If there is no open transaction, then mark this as a special
   67567         ** "transaction savepoint". */
   67568         if( db->autoCommit ){
   67569           db->autoCommit = 0;
   67570           db->isTransactionSavepoint = 1;
   67571         }else{
   67572           db->nSavepoint++;
   67573         }
   67574 
   67575         /* Link the new savepoint into the database handle's list. */
   67576         u.ar.pNew->pNext = db->pSavepoint;
   67577         db->pSavepoint = u.ar.pNew;
   67578         u.ar.pNew->nDeferredCons = db->nDeferredCons;
   67579       }
   67580     }
   67581   }else{
   67582     u.ar.iSavepoint = 0;
   67583 
   67584     /* Find the named savepoint. If there is no such savepoint, then an
   67585     ** an error is returned to the user.  */
   67586     for(
   67587       u.ar.pSavepoint = db->pSavepoint;
   67588       u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
   67589       u.ar.pSavepoint = u.ar.pSavepoint->pNext
   67590     ){
   67591       u.ar.iSavepoint++;
   67592     }
   67593     if( !u.ar.pSavepoint ){
   67594       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
   67595       rc = SQLITE_ERROR;
   67596     }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
   67597       /* It is not possible to release (commit) a savepoint if there are
   67598       ** active write statements.
   67599       */
   67600       sqlite3SetString(&p->zErrMsg, db,
   67601         "cannot release savepoint - SQL statements in progress"
   67602       );
   67603       rc = SQLITE_BUSY;
   67604     }else{
   67605 
   67606       /* Determine whether or not this is a transaction savepoint. If so,
   67607       ** and this is a RELEASE command, then the current transaction
   67608       ** is committed.
   67609       */
   67610       int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
   67611       if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
   67612         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   67613           goto vdbe_return;
   67614         }
   67615         db->autoCommit = 1;
   67616         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   67617           p->pc = pc;
   67618           db->autoCommit = 0;
   67619           p->rc = rc = SQLITE_BUSY;
   67620           goto vdbe_return;
   67621         }
   67622         db->isTransactionSavepoint = 0;
   67623         rc = p->rc;
   67624       }else{
   67625         u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
   67626         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
   67627           sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
   67628         }
   67629         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
   67630           rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
   67631           if( rc!=SQLITE_OK ){
   67632             goto abort_due_to_error;
   67633           }
   67634         }
   67635         if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   67636           sqlite3ExpirePreparedStatements(db);
   67637           sqlite3ResetInternalSchema(db, -1);
   67638           db->flags = (db->flags | SQLITE_InternChanges);
   67639         }
   67640       }
   67641 
   67642       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   67643       ** savepoints nested inside of the savepoint being operated on. */
   67644       while( db->pSavepoint!=u.ar.pSavepoint ){
   67645         u.ar.pTmp = db->pSavepoint;
   67646         db->pSavepoint = u.ar.pTmp->pNext;
   67647         sqlite3DbFree(db, u.ar.pTmp);
   67648         db->nSavepoint--;
   67649       }
   67650 
   67651       /* If it is a RELEASE, then destroy the savepoint being operated on
   67652       ** too. If it is a ROLLBACK TO, then set the number of deferred
   67653       ** constraint violations present in the database to the value stored
   67654       ** when the savepoint was created.  */
   67655       if( u.ar.p1==SAVEPOINT_RELEASE ){
   67656         assert( u.ar.pSavepoint==db->pSavepoint );
   67657         db->pSavepoint = u.ar.pSavepoint->pNext;
   67658         sqlite3DbFree(db, u.ar.pSavepoint);
   67659         if( !isTransaction ){
   67660           db->nSavepoint--;
   67661         }
   67662       }else{
   67663         db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
   67664       }
   67665 
   67666       if( !isTransaction ){
   67667         rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
   67668         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   67669       }
   67670     }
   67671   }
   67672 
   67673   break;
   67674 }
   67675 
   67676 /* Opcode: AutoCommit P1 P2 * * *
   67677 **
   67678 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   67679 ** back any currently active btree transactions. If there are any active
   67680 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   67681 ** there are active writing VMs or active VMs that use shared cache.
   67682 **
   67683 ** This instruction causes the VM to halt.
   67684 */
   67685 case OP_AutoCommit: {
   67686 #if 0  /* local variables moved into u.as */
   67687   int desiredAutoCommit;
   67688   int iRollback;
   67689   int turnOnAC;
   67690 #endif /* local variables moved into u.as */
   67691 
   67692   u.as.desiredAutoCommit = pOp->p1;
   67693   u.as.iRollback = pOp->p2;
   67694   u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
   67695   assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
   67696   assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
   67697   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
   67698 
   67699 #if 0
   67700   if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
   67701     /* If this instruction implements a ROLLBACK and other VMs are
   67702     ** still running, and a transaction is active, return an error indicating
   67703     ** that the other VMs must complete first.
   67704     */
   67705     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   67706         "SQL statements in progress");
   67707     rc = SQLITE_BUSY;
   67708   }else
   67709 #endif
   67710   if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
   67711     /* If this instruction implements a COMMIT and other VMs are writing
   67712     ** return an error indicating that the other VMs must complete first.
   67713     */
   67714     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   67715         "SQL statements in progress");
   67716     rc = SQLITE_BUSY;
   67717   }else if( u.as.desiredAutoCommit!=db->autoCommit ){
   67718     if( u.as.iRollback ){
   67719       assert( u.as.desiredAutoCommit==1 );
   67720       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   67721       db->autoCommit = 1;
   67722     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   67723       goto vdbe_return;
   67724     }else{
   67725       db->autoCommit = (u8)u.as.desiredAutoCommit;
   67726       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   67727         p->pc = pc;
   67728         db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
   67729         p->rc = rc = SQLITE_BUSY;
   67730         goto vdbe_return;
   67731       }
   67732     }
   67733     assert( db->nStatement==0 );
   67734     sqlite3CloseSavepoints(db);
   67735     if( p->rc==SQLITE_OK ){
   67736       rc = SQLITE_DONE;
   67737     }else{
   67738       rc = SQLITE_ERROR;
   67739     }
   67740     goto vdbe_return;
   67741   }else{
   67742     sqlite3SetString(&p->zErrMsg, db,
   67743         (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
   67744         (u.as.iRollback)?"cannot rollback - no transaction is active":
   67745                    "cannot commit - no transaction is active"));
   67746 
   67747     rc = SQLITE_ERROR;
   67748   }
   67749   break;
   67750 }
   67751 
   67752 /* Opcode: Transaction P1 P2 * * *
   67753 **
   67754 ** Begin a transaction.  The transaction ends when a Commit or Rollback
   67755 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
   67756 ** transaction might also be rolled back if an error is encountered.
   67757 **
   67758 ** P1 is the index of the database file on which the transaction is
   67759 ** started.  Index 0 is the main database file and index 1 is the
   67760 ** file used for temporary tables.  Indices of 2 or more are used for
   67761 ** attached databases.
   67762 **
   67763 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
   67764 ** obtained on the database file when a write-transaction is started.  No
   67765 ** other process can start another write transaction while this transaction is
   67766 ** underway.  Starting a write transaction also creates a rollback journal. A
   67767 ** write transaction must be started before any changes can be made to the
   67768 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
   67769 ** on the file.
   67770 **
   67771 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   67772 ** true (this flag is set if the Vdbe may modify more than one row and may
   67773 ** throw an ABORT exception), a statement transaction may also be opened.
   67774 ** More specifically, a statement transaction is opened iff the database
   67775 ** connection is currently not in autocommit mode, or if there are other
   67776 ** active statements. A statement transaction allows the changes made by this
   67777 ** VDBE to be rolled back after an error without having to roll back the
   67778 ** entire transaction. If no error is encountered, the statement transaction
   67779 ** will automatically commit when the VDBE halts.
   67780 **
   67781 ** If P2 is zero, then a read-lock is obtained on the database file.
   67782 */
   67783 case OP_Transaction: {
   67784 #if 0  /* local variables moved into u.at */
   67785   Btree *pBt;
   67786 #endif /* local variables moved into u.at */
   67787 
   67788   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67789   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67790   u.at.pBt = db->aDb[pOp->p1].pBt;
   67791 
   67792   if( u.at.pBt ){
   67793     rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
   67794     if( rc==SQLITE_BUSY ){
   67795       p->pc = pc;
   67796       p->rc = rc = SQLITE_BUSY;
   67797       goto vdbe_return;
   67798     }
   67799     if( rc!=SQLITE_OK ){
   67800       goto abort_due_to_error;
   67801     }
   67802 
   67803     if( pOp->p2 && p->usesStmtJournal
   67804      && (db->autoCommit==0 || db->activeVdbeCnt>1)
   67805     ){
   67806       assert( sqlite3BtreeIsInTrans(u.at.pBt) );
   67807       if( p->iStatement==0 ){
   67808         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   67809         db->nStatement++;
   67810         p->iStatement = db->nSavepoint + db->nStatement;
   67811       }
   67812 
   67813       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
   67814       if( rc==SQLITE_OK ){
   67815         rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
   67816       }
   67817 
   67818       /* Store the current value of the database handles deferred constraint
   67819       ** counter. If the statement transaction needs to be rolled back,
   67820       ** the value of this counter needs to be restored too.  */
   67821       p->nStmtDefCons = db->nDeferredCons;
   67822     }
   67823   }
   67824   break;
   67825 }
   67826 
   67827 /* Opcode: ReadCookie P1 P2 P3 * *
   67828 **
   67829 ** Read cookie number P3 from database P1 and write it into register P2.
   67830 ** P3==1 is the schema version.  P3==2 is the database format.
   67831 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   67832 ** the main database file and P1==1 is the database file used to store
   67833 ** temporary tables.
   67834 **
   67835 ** There must be a read-lock on the database (either a transaction
   67836 ** must be started or there must be an open cursor) before
   67837 ** executing this instruction.
   67838 */
   67839 case OP_ReadCookie: {               /* out2-prerelease */
   67840 #if 0  /* local variables moved into u.au */
   67841   int iMeta;
   67842   int iDb;
   67843   int iCookie;
   67844 #endif /* local variables moved into u.au */
   67845 
   67846   u.au.iDb = pOp->p1;
   67847   u.au.iCookie = pOp->p3;
   67848   assert( pOp->p3<SQLITE_N_BTREE_META );
   67849   assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
   67850   assert( db->aDb[u.au.iDb].pBt!=0 );
   67851   assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
   67852 
   67853   sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
   67854   pOut->u.i = u.au.iMeta;
   67855   break;
   67856 }
   67857 
   67858 /* Opcode: SetCookie P1 P2 P3 * *
   67859 **
   67860 ** Write the content of register P3 (interpreted as an integer)
   67861 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   67862 ** P2==2 is the database format. P2==3 is the recommended pager cache
   67863 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   67864 ** database file used to store temporary tables.
   67865 **
   67866 ** A transaction must be started before executing this opcode.
   67867 */
   67868 case OP_SetCookie: {       /* in3 */
   67869 #if 0  /* local variables moved into u.av */
   67870   Db *pDb;
   67871 #endif /* local variables moved into u.av */
   67872   assert( pOp->p2<SQLITE_N_BTREE_META );
   67873   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67874   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67875   u.av.pDb = &db->aDb[pOp->p1];
   67876   assert( u.av.pDb->pBt!=0 );
   67877   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   67878   pIn3 = &aMem[pOp->p3];
   67879   sqlite3VdbeMemIntegerify(pIn3);
   67880   /* See note about index shifting on OP_ReadCookie */
   67881   rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
   67882   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   67883     /* When the schema cookie changes, record the new cookie internally */
   67884     u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   67885     db->flags |= SQLITE_InternChanges;
   67886   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   67887     /* Record changes in the file format */
   67888     u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
   67889   }
   67890   if( pOp->p1==1 ){
   67891     /* Invalidate all prepared statements whenever the TEMP database
   67892     ** schema is changed.  Ticket #1644 */
   67893     sqlite3ExpirePreparedStatements(db);
   67894     p->expired = 0;
   67895   }
   67896   break;
   67897 }
   67898 
   67899 /* Opcode: VerifyCookie P1 P2 P3 * *
   67900 **
   67901 ** Check the value of global database parameter number 0 (the
   67902 ** schema version) and make sure it is equal to P2 and that the
   67903 ** generation counter on the local schema parse equals P3.
   67904 **
   67905 ** P1 is the database number which is 0 for the main database file
   67906 ** and 1 for the file holding temporary tables and some higher number
   67907 ** for auxiliary databases.
   67908 **
   67909 ** The cookie changes its value whenever the database schema changes.
   67910 ** This operation is used to detect when that the cookie has changed
   67911 ** and that the current process needs to reread the schema.
   67912 **
   67913 ** Either a transaction needs to have been started or an OP_Open needs
   67914 ** to be executed (to establish a read lock) before this opcode is
   67915 ** invoked.
   67916 */
   67917 case OP_VerifyCookie: {
   67918 #if 0  /* local variables moved into u.aw */
   67919   int iMeta;
   67920   int iGen;
   67921   Btree *pBt;
   67922 #endif /* local variables moved into u.aw */
   67923 
   67924   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67925   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67926   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   67927   u.aw.pBt = db->aDb[pOp->p1].pBt;
   67928   if( u.aw.pBt ){
   67929     sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
   67930     u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
   67931   }else{
   67932     u.aw.iGen = u.aw.iMeta = 0;
   67933   }
   67934   if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
   67935     sqlite3DbFree(db, p->zErrMsg);
   67936     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   67937     /* If the schema-cookie from the database file matches the cookie
   67938     ** stored with the in-memory representation of the schema, do
   67939     ** not reload the schema from the database file.
   67940     **
   67941     ** If virtual-tables are in use, this is not just an optimization.
   67942     ** Often, v-tables store their data in other SQLite tables, which
   67943     ** are queried from within xNext() and other v-table methods using
   67944     ** prepared queries. If such a query is out-of-date, we do not want to
   67945     ** discard the database schema, as the user code implementing the
   67946     ** v-table would have to be ready for the sqlite3_vtab structure itself
   67947     ** to be invalidated whenever sqlite3_step() is called from within
   67948     ** a v-table method.
   67949     */
   67950     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
   67951       sqlite3ResetInternalSchema(db, pOp->p1);
   67952     }
   67953 
   67954     p->expired = 1;
   67955     rc = SQLITE_SCHEMA;
   67956   }
   67957   break;
   67958 }
   67959 
   67960 /* Opcode: OpenRead P1 P2 P3 P4 P5
   67961 **
   67962 ** Open a read-only cursor for the database table whose root page is
   67963 ** P2 in a database file.  The database file is determined by P3.
   67964 ** P3==0 means the main database, P3==1 means the database used for
   67965 ** temporary tables, and P3>1 means used the corresponding attached
   67966 ** database.  Give the new cursor an identifier of P1.  The P1
   67967 ** values need not be contiguous but all P1 values should be small integers.
   67968 ** It is an error for P1 to be negative.
   67969 **
   67970 ** If P5!=0 then use the content of register P2 as the root page, not
   67971 ** the value of P2 itself.
   67972 **
   67973 ** There will be a read lock on the database whenever there is an
   67974 ** open cursor.  If the database was unlocked prior to this instruction
   67975 ** then a read lock is acquired as part of this instruction.  A read
   67976 ** lock allows other processes to read the database but prohibits
   67977 ** any other process from modifying the database.  The read lock is
   67978 ** released when all cursors are closed.  If this instruction attempts
   67979 ** to get a read lock but fails, the script terminates with an
   67980 ** SQLITE_BUSY error code.
   67981 **
   67982 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   67983 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   67984 ** structure, then said structure defines the content and collating
   67985 ** sequence of the index being opened. Otherwise, if P4 is an integer
   67986 ** value, it is set to the number of columns in the table.
   67987 **
   67988 ** See also OpenWrite.
   67989 */
   67990 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   67991 **
   67992 ** Open a read/write cursor named P1 on the table or index whose root
   67993 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   67994 ** root page.
   67995 **
   67996 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   67997 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   67998 ** structure, then said structure defines the content and collating
   67999 ** sequence of the index being opened. Otherwise, if P4 is an integer
   68000 ** value, it is set to the number of columns in the table, or to the
   68001 ** largest index of any column of the table that is actually used.
   68002 **
   68003 ** This instruction works just like OpenRead except that it opens the cursor
   68004 ** in read/write mode.  For a given table, there can be one or more read-only
   68005 ** cursors or a single read/write cursor but not both.
   68006 **
   68007 ** See also OpenRead.
   68008 */
   68009 case OP_OpenRead:
   68010 case OP_OpenWrite: {
   68011 #if 0  /* local variables moved into u.ax */
   68012   int nField;
   68013   KeyInfo *pKeyInfo;
   68014   int p2;
   68015   int iDb;
   68016   int wrFlag;
   68017   Btree *pX;
   68018   VdbeCursor *pCur;
   68019   Db *pDb;
   68020 #endif /* local variables moved into u.ax */
   68021 
   68022   if( p->expired ){
   68023     rc = SQLITE_ABORT;
   68024     break;
   68025   }
   68026 
   68027   u.ax.nField = 0;
   68028   u.ax.pKeyInfo = 0;
   68029   u.ax.p2 = pOp->p2;
   68030   u.ax.iDb = pOp->p3;
   68031   assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
   68032   assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
   68033   u.ax.pDb = &db->aDb[u.ax.iDb];
   68034   u.ax.pX = u.ax.pDb->pBt;
   68035   assert( u.ax.pX!=0 );
   68036   if( pOp->opcode==OP_OpenWrite ){
   68037     u.ax.wrFlag = 1;
   68038     assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
   68039     if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
   68040       p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
   68041     }
   68042   }else{
   68043     u.ax.wrFlag = 0;
   68044   }
   68045   if( pOp->p5 ){
   68046     assert( u.ax.p2>0 );
   68047     assert( u.ax.p2<=p->nMem );
   68048     pIn2 = &aMem[u.ax.p2];
   68049     assert( memIsValid(pIn2) );
   68050     assert( (pIn2->flags & MEM_Int)!=0 );
   68051     sqlite3VdbeMemIntegerify(pIn2);
   68052     u.ax.p2 = (int)pIn2->u.i;
   68053     /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
   68054     ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
   68055     ** If there were a failure, the prepared statement would have halted
   68056     ** before reaching this instruction. */
   68057     if( NEVER(u.ax.p2<2) ) {
   68058       rc = SQLITE_CORRUPT_BKPT;
   68059       goto abort_due_to_error;
   68060     }
   68061   }
   68062   if( pOp->p4type==P4_KEYINFO ){
   68063     u.ax.pKeyInfo = pOp->p4.pKeyInfo;
   68064     u.ax.pKeyInfo->enc = ENC(p->db);
   68065     u.ax.nField = u.ax.pKeyInfo->nField+1;
   68066   }else if( pOp->p4type==P4_INT32 ){
   68067     u.ax.nField = pOp->p4.i;
   68068   }
   68069   assert( pOp->p1>=0 );
   68070   u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
   68071   if( u.ax.pCur==0 ) goto no_mem;
   68072   u.ax.pCur->nullRow = 1;
   68073   u.ax.pCur->isOrdered = 1;
   68074   rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
   68075   u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
   68076 
   68077   /* Since it performs no memory allocation or IO, the only value that
   68078   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
   68079   assert( rc==SQLITE_OK );
   68080 
   68081   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
   68082   ** SQLite used to check if the root-page flags were sane at this point
   68083   ** and report database corruption if they were not, but this check has
   68084   ** since moved into the btree layer.  */
   68085   u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
   68086   u.ax.pCur->isIndex = !u.ax.pCur->isTable;
   68087   break;
   68088 }
   68089 
   68090 /* Opcode: OpenEphemeral P1 P2 * P4 P5
   68091 **
   68092 ** Open a new cursor P1 to a transient table.
   68093 ** The cursor is always opened read/write even if
   68094 ** the main database is read-only.  The ephemeral
   68095 ** table is deleted automatically when the cursor is closed.
   68096 **
   68097 ** P2 is the number of columns in the ephemeral table.
   68098 ** The cursor points to a BTree table if P4==0 and to a BTree index
   68099 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   68100 ** that defines the format of keys in the index.
   68101 **
   68102 ** This opcode was once called OpenTemp.  But that created
   68103 ** confusion because the term "temp table", might refer either
   68104 ** to a TEMP table at the SQL level, or to a table opened by
   68105 ** this opcode.  Then this opcode was call OpenVirtual.  But
   68106 ** that created confusion with the whole virtual-table idea.
   68107 **
   68108 ** The P5 parameter can be a mask of the BTREE_* flags defined
   68109 ** in btree.h.  These flags control aspects of the operation of
   68110 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
   68111 ** added automatically.
   68112 */
   68113 /* Opcode: OpenAutoindex P1 P2 * P4 *
   68114 **
   68115 ** This opcode works the same as OP_OpenEphemeral.  It has a
   68116 ** different name to distinguish its use.  Tables created using
   68117 ** by this opcode will be used for automatically created transient
   68118 ** indices in joins.
   68119 */
   68120 case OP_OpenAutoindex:
   68121 case OP_OpenEphemeral: {
   68122 #if 0  /* local variables moved into u.ay */
   68123   VdbeCursor *pCx;
   68124 #endif /* local variables moved into u.ay */
   68125   static const int vfsFlags =
   68126       SQLITE_OPEN_READWRITE |
   68127       SQLITE_OPEN_CREATE |
   68128       SQLITE_OPEN_EXCLUSIVE |
   68129       SQLITE_OPEN_DELETEONCLOSE |
   68130       SQLITE_OPEN_TRANSIENT_DB;
   68131 
   68132   assert( pOp->p1>=0 );
   68133   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   68134   if( u.ay.pCx==0 ) goto no_mem;
   68135   u.ay.pCx->nullRow = 1;
   68136   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
   68137                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   68138   if( rc==SQLITE_OK ){
   68139     rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
   68140   }
   68141   if( rc==SQLITE_OK ){
   68142     /* If a transient index is required, create it by calling
   68143     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   68144     ** opening it. If a transient table is required, just use the
   68145     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   68146     */
   68147     if( pOp->p4.pKeyInfo ){
   68148       int pgno;
   68149       assert( pOp->p4type==P4_KEYINFO );
   68150       rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
   68151       if( rc==SQLITE_OK ){
   68152         assert( pgno==MASTER_ROOT+1 );
   68153         rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
   68154                                 (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
   68155         u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   68156         u.ay.pCx->pKeyInfo->enc = ENC(p->db);
   68157       }
   68158       u.ay.pCx->isTable = 0;
   68159     }else{
   68160       rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
   68161       u.ay.pCx->isTable = 1;
   68162     }
   68163   }
   68164   u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   68165   u.ay.pCx->isIndex = !u.ay.pCx->isTable;
   68166   break;
   68167 }
   68168 
   68169 /* Opcode: OpenSorter P1 P2 * P4 *
   68170 **
   68171 ** This opcode works like OP_OpenEphemeral except that it opens
   68172 ** a transient index that is specifically designed to sort large
   68173 ** tables using an external merge-sort algorithm.
   68174 */
   68175 case OP_SorterOpen: {
   68176 #if 0  /* local variables moved into u.az */
   68177   VdbeCursor *pCx;
   68178 #endif /* local variables moved into u.az */
   68179 #ifndef SQLITE_OMIT_MERGE_SORT
   68180   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   68181   if( u.az.pCx==0 ) goto no_mem;
   68182   u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   68183   u.az.pCx->pKeyInfo->enc = ENC(p->db);
   68184   u.az.pCx->isSorter = 1;
   68185   rc = sqlite3VdbeSorterInit(db, u.az.pCx);
   68186 #else
   68187   pOp->opcode = OP_OpenEphemeral;
   68188   pc--;
   68189 #endif
   68190   break;
   68191 }
   68192 
   68193 /* Opcode: OpenPseudo P1 P2 P3 * *
   68194 **
   68195 ** Open a new cursor that points to a fake table that contains a single
   68196 ** row of data.  The content of that one row in the content of memory
   68197 ** register P2.  In other words, cursor P1 becomes an alias for the
   68198 ** MEM_Blob content contained in register P2.
   68199 **
   68200 ** A pseudo-table created by this opcode is used to hold a single
   68201 ** row output from the sorter so that the row can be decomposed into
   68202 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   68203 ** is the only cursor opcode that works with a pseudo-table.
   68204 **
   68205 ** P3 is the number of fields in the records that will be stored by
   68206 ** the pseudo-table.
   68207 */
   68208 case OP_OpenPseudo: {
   68209 #if 0  /* local variables moved into u.ba */
   68210   VdbeCursor *pCx;
   68211 #endif /* local variables moved into u.ba */
   68212 
   68213   assert( pOp->p1>=0 );
   68214   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   68215   if( u.ba.pCx==0 ) goto no_mem;
   68216   u.ba.pCx->nullRow = 1;
   68217   u.ba.pCx->pseudoTableReg = pOp->p2;
   68218   u.ba.pCx->isTable = 1;
   68219   u.ba.pCx->isIndex = 0;
   68220   break;
   68221 }
   68222 
   68223 /* Opcode: Close P1 * * * *
   68224 **
   68225 ** Close a cursor previously opened as P1.  If P1 is not
   68226 ** currently open, this instruction is a no-op.
   68227 */
   68228 case OP_Close: {
   68229   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68230   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   68231   p->apCsr[pOp->p1] = 0;
   68232   break;
   68233 }
   68234 
   68235 /* Opcode: SeekGe P1 P2 P3 P4 *
   68236 **
   68237 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68238 ** use the value in register P3 as the key.  If cursor P1 refers
   68239 ** to an SQL index, then P3 is the first in an array of P4 registers
   68240 ** that are used as an unpacked index key.
   68241 **
   68242 ** Reposition cursor P1 so that  it points to the smallest entry that
   68243 ** is greater than or equal to the key value. If there are no records
   68244 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   68245 **
   68246 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
   68247 */
   68248 /* Opcode: SeekGt P1 P2 P3 P4 *
   68249 **
   68250 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68251 ** use the value in register P3 as a key. If cursor P1 refers
   68252 ** to an SQL index, then P3 is the first in an array of P4 registers
   68253 ** that are used as an unpacked index key.
   68254 **
   68255 ** Reposition cursor P1 so that  it points to the smallest entry that
   68256 ** is greater than the key value. If there are no records greater than
   68257 ** the key and P2 is not zero, then jump to P2.
   68258 **
   68259 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
   68260 */
   68261 /* Opcode: SeekLt P1 P2 P3 P4 *
   68262 **
   68263 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68264 ** use the value in register P3 as a key. If cursor P1 refers
   68265 ** to an SQL index, then P3 is the first in an array of P4 registers
   68266 ** that are used as an unpacked index key.
   68267 **
   68268 ** Reposition cursor P1 so that  it points to the largest entry that
   68269 ** is less than the key value. If there are no records less than
   68270 ** the key and P2 is not zero, then jump to P2.
   68271 **
   68272 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
   68273 */
   68274 /* Opcode: SeekLe P1 P2 P3 P4 *
   68275 **
   68276 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68277 ** use the value in register P3 as a key. If cursor P1 refers
   68278 ** to an SQL index, then P3 is the first in an array of P4 registers
   68279 ** that are used as an unpacked index key.
   68280 **
   68281 ** Reposition cursor P1 so that it points to the largest entry that
   68282 ** is less than or equal to the key value. If there are no records
   68283 ** less than or equal to the key and P2 is not zero, then jump to P2.
   68284 **
   68285 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
   68286 */
   68287 case OP_SeekLt:         /* jump, in3 */
   68288 case OP_SeekLe:         /* jump, in3 */
   68289 case OP_SeekGe:         /* jump, in3 */
   68290 case OP_SeekGt: {       /* jump, in3 */
   68291 #if 0  /* local variables moved into u.bb */
   68292   int res;
   68293   int oc;
   68294   VdbeCursor *pC;
   68295   UnpackedRecord r;
   68296   int nField;
   68297   i64 iKey;      /* The rowid we are to seek to */
   68298 #endif /* local variables moved into u.bb */
   68299 
   68300   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68301   assert( pOp->p2!=0 );
   68302   u.bb.pC = p->apCsr[pOp->p1];
   68303   assert( u.bb.pC!=0 );
   68304   assert( u.bb.pC->pseudoTableReg==0 );
   68305   assert( OP_SeekLe == OP_SeekLt+1 );
   68306   assert( OP_SeekGe == OP_SeekLt+2 );
   68307   assert( OP_SeekGt == OP_SeekLt+3 );
   68308   assert( u.bb.pC->isOrdered );
   68309   if( ALWAYS(u.bb.pC->pCursor!=0) ){
   68310     u.bb.oc = pOp->opcode;
   68311     u.bb.pC->nullRow = 0;
   68312     if( u.bb.pC->isTable ){
   68313       /* The input value in P3 might be of any type: integer, real, string,
   68314       ** blob, or NULL.  But it needs to be an integer before we can do
   68315       ** the seek, so covert it. */
   68316       pIn3 = &aMem[pOp->p3];
   68317       applyNumericAffinity(pIn3);
   68318       u.bb.iKey = sqlite3VdbeIntValue(pIn3);
   68319       u.bb.pC->rowidIsValid = 0;
   68320 
   68321       /* If the P3 value could not be converted into an integer without
   68322       ** loss of information, then special processing is required... */
   68323       if( (pIn3->flags & MEM_Int)==0 ){
   68324         if( (pIn3->flags & MEM_Real)==0 ){
   68325           /* If the P3 value cannot be converted into any kind of a number,
   68326           ** then the seek is not possible, so jump to P2 */
   68327           pc = pOp->p2 - 1;
   68328           break;
   68329         }
   68330         /* If we reach this point, then the P3 value must be a floating
   68331         ** point number. */
   68332         assert( (pIn3->flags & MEM_Real)!=0 );
   68333 
   68334         if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
   68335           /* The P3 value is too large in magnitude to be expressed as an
   68336           ** integer. */
   68337           u.bb.res = 1;
   68338           if( pIn3->r<0 ){
   68339             if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
   68340               rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
   68341               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68342             }
   68343           }else{
   68344             if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
   68345               rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
   68346               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68347             }
   68348           }
   68349           if( u.bb.res ){
   68350             pc = pOp->p2 - 1;
   68351           }
   68352           break;
   68353         }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
   68354           /* Use the ceiling() function to convert real->int */
   68355           if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
   68356         }else{
   68357           /* Use the floor() function to convert real->int */
   68358           assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
   68359           if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
   68360         }
   68361       }
   68362       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
   68363       if( rc!=SQLITE_OK ){
   68364         goto abort_due_to_error;
   68365       }
   68366       if( u.bb.res==0 ){
   68367         u.bb.pC->rowidIsValid = 1;
   68368         u.bb.pC->lastRowid = u.bb.iKey;
   68369       }
   68370     }else{
   68371       u.bb.nField = pOp->p4.i;
   68372       assert( pOp->p4type==P4_INT32 );
   68373       assert( u.bb.nField>0 );
   68374       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
   68375       u.bb.r.nField = (u16)u.bb.nField;
   68376 
   68377       /* The next line of code computes as follows, only faster:
   68378       **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
   68379       **     u.bb.r.flags = UNPACKED_INCRKEY;
   68380       **   }else{
   68381       **     u.bb.r.flags = 0;
   68382       **   }
   68383       */
   68384       u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
   68385       assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
   68386       assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
   68387       assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
   68388       assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
   68389 
   68390       u.bb.r.aMem = &aMem[pOp->p3];
   68391 #ifdef SQLITE_DEBUG
   68392       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
   68393 #endif
   68394       ExpandBlob(u.bb.r.aMem);
   68395       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
   68396       if( rc!=SQLITE_OK ){
   68397         goto abort_due_to_error;
   68398       }
   68399       u.bb.pC->rowidIsValid = 0;
   68400     }
   68401     u.bb.pC->deferredMoveto = 0;
   68402     u.bb.pC->cacheStatus = CACHE_STALE;
   68403 #ifdef SQLITE_TEST
   68404     sqlite3_search_count++;
   68405 #endif
   68406     if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
   68407       if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
   68408         rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
   68409         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68410         u.bb.pC->rowidIsValid = 0;
   68411       }else{
   68412         u.bb.res = 0;
   68413       }
   68414     }else{
   68415       assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
   68416       if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
   68417         rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
   68418         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68419         u.bb.pC->rowidIsValid = 0;
   68420       }else{
   68421         /* u.bb.res might be negative because the table is empty.  Check to
   68422         ** see if this is the case.
   68423         */
   68424         u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
   68425       }
   68426     }
   68427     assert( pOp->p2>0 );
   68428     if( u.bb.res ){
   68429       pc = pOp->p2 - 1;
   68430     }
   68431   }else{
   68432     /* This happens when attempting to open the sqlite3_master table
   68433     ** for read access returns SQLITE_EMPTY. In this case always
   68434     ** take the jump (since there are no records in the table).
   68435     */
   68436     pc = pOp->p2 - 1;
   68437   }
   68438   break;
   68439 }
   68440 
   68441 /* Opcode: Seek P1 P2 * * *
   68442 **
   68443 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   68444 ** for P1 to move so that it points to the rowid given by P2.
   68445 **
   68446 ** This is actually a deferred seek.  Nothing actually happens until
   68447 ** the cursor is used to read a record.  That way, if no reads
   68448 ** occur, no unnecessary I/O happens.
   68449 */
   68450 case OP_Seek: {    /* in2 */
   68451 #if 0  /* local variables moved into u.bc */
   68452   VdbeCursor *pC;
   68453 #endif /* local variables moved into u.bc */
   68454 
   68455   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68456   u.bc.pC = p->apCsr[pOp->p1];
   68457   assert( u.bc.pC!=0 );
   68458   if( ALWAYS(u.bc.pC->pCursor!=0) ){
   68459     assert( u.bc.pC->isTable );
   68460     u.bc.pC->nullRow = 0;
   68461     pIn2 = &aMem[pOp->p2];
   68462     u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   68463     u.bc.pC->rowidIsValid = 0;
   68464     u.bc.pC->deferredMoveto = 1;
   68465   }
   68466   break;
   68467 }
   68468 
   68469 
   68470 /* Opcode: Found P1 P2 P3 P4 *
   68471 **
   68472 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   68473 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   68474 ** record.
   68475 **
   68476 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   68477 ** is a prefix of any entry in P1 then a jump is made to P2 and
   68478 ** P1 is left pointing at the matching entry.
   68479 */
   68480 /* Opcode: NotFound P1 P2 P3 P4 *
   68481 **
   68482 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   68483 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   68484 ** record.
   68485 **
   68486 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   68487 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   68488 ** does contain an entry whose prefix matches the P3/P4 record then control
   68489 ** falls through to the next instruction and P1 is left pointing at the
   68490 ** matching entry.
   68491 **
   68492 ** See also: Found, NotExists, IsUnique
   68493 */
   68494 case OP_NotFound:       /* jump, in3 */
   68495 case OP_Found: {        /* jump, in3 */
   68496 #if 0  /* local variables moved into u.bd */
   68497   int alreadyExists;
   68498   VdbeCursor *pC;
   68499   int res;
   68500   char *pFree;
   68501   UnpackedRecord *pIdxKey;
   68502   UnpackedRecord r;
   68503   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   68504 #endif /* local variables moved into u.bd */
   68505 
   68506 #ifdef SQLITE_TEST
   68507   sqlite3_found_count++;
   68508 #endif
   68509 
   68510   u.bd.alreadyExists = 0;
   68511   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68512   assert( pOp->p4type==P4_INT32 );
   68513   u.bd.pC = p->apCsr[pOp->p1];
   68514   assert( u.bd.pC!=0 );
   68515   pIn3 = &aMem[pOp->p3];
   68516   if( ALWAYS(u.bd.pC->pCursor!=0) ){
   68517 
   68518     assert( u.bd.pC->isTable==0 );
   68519     if( pOp->p4.i>0 ){
   68520       u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
   68521       u.bd.r.nField = (u16)pOp->p4.i;
   68522       u.bd.r.aMem = pIn3;
   68523 #ifdef SQLITE_DEBUG
   68524       { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
   68525 #endif
   68526       u.bd.r.flags = UNPACKED_PREFIX_MATCH;
   68527       u.bd.pIdxKey = &u.bd.r;
   68528     }else{
   68529       u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   68530           u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
   68531       );
   68532       if( u.bd.pIdxKey==0 ) goto no_mem;
   68533       assert( pIn3->flags & MEM_Blob );
   68534       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
   68535       sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
   68536       u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
   68537     }
   68538     rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
   68539     if( pOp->p4.i==0 ){
   68540       sqlite3DbFree(db, u.bd.pFree);
   68541     }
   68542     if( rc!=SQLITE_OK ){
   68543       break;
   68544     }
   68545     u.bd.alreadyExists = (u.bd.res==0);
   68546     u.bd.pC->deferredMoveto = 0;
   68547     u.bd.pC->cacheStatus = CACHE_STALE;
   68548   }
   68549   if( pOp->opcode==OP_Found ){
   68550     if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
   68551   }else{
   68552     if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
   68553   }
   68554   break;
   68555 }
   68556 
   68557 /* Opcode: IsUnique P1 P2 P3 P4 *
   68558 **
   68559 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
   68560 ** no data and where the key are records generated by OP_MakeRecord with
   68561 ** the list field being the integer ROWID of the entry that the index
   68562 ** entry refers to.
   68563 **
   68564 ** The P3 register contains an integer record number. Call this record
   68565 ** number R. Register P4 is the first in a set of N contiguous registers
   68566 ** that make up an unpacked index key that can be used with cursor P1.
   68567 ** The value of N can be inferred from the cursor. N includes the rowid
   68568 ** value appended to the end of the index record. This rowid value may
   68569 ** or may not be the same as R.
   68570 **
   68571 ** If any of the N registers beginning with register P4 contains a NULL
   68572 ** value, jump immediately to P2.
   68573 **
   68574 ** Otherwise, this instruction checks if cursor P1 contains an entry
   68575 ** where the first (N-1) fields match but the rowid value at the end
   68576 ** of the index entry is not R. If there is no such entry, control jumps
   68577 ** to instruction P2. Otherwise, the rowid of the conflicting index
   68578 ** entry is copied to register P3 and control falls through to the next
   68579 ** instruction.
   68580 **
   68581 ** See also: NotFound, NotExists, Found
   68582 */
   68583 case OP_IsUnique: {        /* jump, in3 */
   68584 #if 0  /* local variables moved into u.be */
   68585   u16 ii;
   68586   VdbeCursor *pCx;
   68587   BtCursor *pCrsr;
   68588   u16 nField;
   68589   Mem *aMx;
   68590   UnpackedRecord r;                  /* B-Tree index search key */
   68591   i64 R;                             /* Rowid stored in register P3 */
   68592 #endif /* local variables moved into u.be */
   68593 
   68594   pIn3 = &aMem[pOp->p3];
   68595   u.be.aMx = &aMem[pOp->p4.i];
   68596   /* Assert that the values of parameters P1 and P4 are in range. */
   68597   assert( pOp->p4type==P4_INT32 );
   68598   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
   68599   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68600 
   68601   /* Find the index cursor. */
   68602   u.be.pCx = p->apCsr[pOp->p1];
   68603   assert( u.be.pCx->deferredMoveto==0 );
   68604   u.be.pCx->seekResult = 0;
   68605   u.be.pCx->cacheStatus = CACHE_STALE;
   68606   u.be.pCrsr = u.be.pCx->pCursor;
   68607 
   68608   /* If any of the values are NULL, take the jump. */
   68609   u.be.nField = u.be.pCx->pKeyInfo->nField;
   68610   for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
   68611     if( u.be.aMx[u.be.ii].flags & MEM_Null ){
   68612       pc = pOp->p2 - 1;
   68613       u.be.pCrsr = 0;
   68614       break;
   68615     }
   68616   }
   68617   assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
   68618 
   68619   if( u.be.pCrsr!=0 ){
   68620     /* Populate the index search key. */
   68621     u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
   68622     u.be.r.nField = u.be.nField + 1;
   68623     u.be.r.flags = UNPACKED_PREFIX_SEARCH;
   68624     u.be.r.aMem = u.be.aMx;
   68625 #ifdef SQLITE_DEBUG
   68626     { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
   68627 #endif
   68628 
   68629     /* Extract the value of u.be.R from register P3. */
   68630     sqlite3VdbeMemIntegerify(pIn3);
   68631     u.be.R = pIn3->u.i;
   68632 
   68633     /* Search the B-Tree index. If no conflicting record is found, jump
   68634     ** to P2. Otherwise, copy the rowid of the conflicting record to
   68635     ** register P3 and fall through to the next instruction.  */
   68636     rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
   68637     if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
   68638       pc = pOp->p2 - 1;
   68639     }else{
   68640       pIn3->u.i = u.be.r.rowid;
   68641     }
   68642   }
   68643   break;
   68644 }
   68645 
   68646 /* Opcode: NotExists P1 P2 P3 * *
   68647 **
   68648 ** Use the content of register P3 as an integer key.  If a record
   68649 ** with that key does not exist in table of P1, then jump to P2.
   68650 ** If the record does exist, then fall through.  The cursor is left
   68651 ** pointing to the record if it exists.
   68652 **
   68653 ** The difference between this operation and NotFound is that this
   68654 ** operation assumes the key is an integer and that P1 is a table whereas
   68655 ** NotFound assumes key is a blob constructed from MakeRecord and
   68656 ** P1 is an index.
   68657 **
   68658 ** See also: Found, NotFound, IsUnique
   68659 */
   68660 case OP_NotExists: {        /* jump, in3 */
   68661 #if 0  /* local variables moved into u.bf */
   68662   VdbeCursor *pC;
   68663   BtCursor *pCrsr;
   68664   int res;
   68665   u64 iKey;
   68666 #endif /* local variables moved into u.bf */
   68667 
   68668   pIn3 = &aMem[pOp->p3];
   68669   assert( pIn3->flags & MEM_Int );
   68670   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68671   u.bf.pC = p->apCsr[pOp->p1];
   68672   assert( u.bf.pC!=0 );
   68673   assert( u.bf.pC->isTable );
   68674   assert( u.bf.pC->pseudoTableReg==0 );
   68675   u.bf.pCrsr = u.bf.pC->pCursor;
   68676   if( ALWAYS(u.bf.pCrsr!=0) ){
   68677     u.bf.res = 0;
   68678     u.bf.iKey = pIn3->u.i;
   68679     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
   68680     u.bf.pC->lastRowid = pIn3->u.i;
   68681     u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
   68682     u.bf.pC->nullRow = 0;
   68683     u.bf.pC->cacheStatus = CACHE_STALE;
   68684     u.bf.pC->deferredMoveto = 0;
   68685     if( u.bf.res!=0 ){
   68686       pc = pOp->p2 - 1;
   68687       assert( u.bf.pC->rowidIsValid==0 );
   68688     }
   68689     u.bf.pC->seekResult = u.bf.res;
   68690   }else{
   68691     /* This happens when an attempt to open a read cursor on the
   68692     ** sqlite_master table returns SQLITE_EMPTY.
   68693     */
   68694     pc = pOp->p2 - 1;
   68695     assert( u.bf.pC->rowidIsValid==0 );
   68696     u.bf.pC->seekResult = 0;
   68697   }
   68698   break;
   68699 }
   68700 
   68701 /* Opcode: Sequence P1 P2 * * *
   68702 **
   68703 ** Find the next available sequence number for cursor P1.
   68704 ** Write the sequence number into register P2.
   68705 ** The sequence number on the cursor is incremented after this
   68706 ** instruction.
   68707 */
   68708 case OP_Sequence: {           /* out2-prerelease */
   68709   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68710   assert( p->apCsr[pOp->p1]!=0 );
   68711   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   68712   break;
   68713 }
   68714 
   68715 
   68716 /* Opcode: NewRowid P1 P2 P3 * *
   68717 **
   68718 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   68719 ** The record number is not previously used as a key in the database
   68720 ** table that cursor P1 points to.  The new record number is written
   68721 ** written to register P2.
   68722 **
   68723 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   68724 ** the largest previously generated record number. No new record numbers are
   68725 ** allowed to be less than this value. When this value reaches its maximum,
   68726 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
   68727 ** generated record number. This P3 mechanism is used to help implement the
   68728 ** AUTOINCREMENT feature.
   68729 */
   68730 case OP_NewRowid: {           /* out2-prerelease */
   68731 #if 0  /* local variables moved into u.bg */
   68732   i64 v;                 /* The new rowid */
   68733   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   68734   int res;               /* Result of an sqlite3BtreeLast() */
   68735   int cnt;               /* Counter to limit the number of searches */
   68736   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   68737   VdbeFrame *pFrame;     /* Root frame of VDBE */
   68738 #endif /* local variables moved into u.bg */
   68739 
   68740   u.bg.v = 0;
   68741   u.bg.res = 0;
   68742   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68743   u.bg.pC = p->apCsr[pOp->p1];
   68744   assert( u.bg.pC!=0 );
   68745   if( NEVER(u.bg.pC->pCursor==0) ){
   68746     /* The zero initialization above is all that is needed */
   68747   }else{
   68748     /* The next rowid or record number (different terms for the same
   68749     ** thing) is obtained in a two-step algorithm.
   68750     **
   68751     ** First we attempt to find the largest existing rowid and add one
   68752     ** to that.  But if the largest existing rowid is already the maximum
   68753     ** positive integer, we have to fall through to the second
   68754     ** probabilistic algorithm
   68755     **
   68756     ** The second algorithm is to select a rowid at random and see if
   68757     ** it already exists in the table.  If it does not exist, we have
   68758     ** succeeded.  If the random rowid does exist, we select a new one
   68759     ** and try again, up to 100 times.
   68760     */
   68761     assert( u.bg.pC->isTable );
   68762 
   68763 #ifdef SQLITE_32BIT_ROWID
   68764 #   define MAX_ROWID 0x7fffffff
   68765 #else
   68766     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   68767     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   68768     ** to provide the constant while making all compilers happy.
   68769     */
   68770 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   68771 #endif
   68772 
   68773     if( !u.bg.pC->useRandomRowid ){
   68774       u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
   68775       if( u.bg.v==0 ){
   68776         rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
   68777         if( rc!=SQLITE_OK ){
   68778           goto abort_due_to_error;
   68779         }
   68780         if( u.bg.res ){
   68781           u.bg.v = 1;   /* IMP: R-61914-48074 */
   68782         }else{
   68783           assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
   68784           rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
   68785           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   68786           if( u.bg.v>=MAX_ROWID ){
   68787             u.bg.pC->useRandomRowid = 1;
   68788           }else{
   68789             u.bg.v++;   /* IMP: R-29538-34987 */
   68790           }
   68791         }
   68792       }
   68793 
   68794 #ifndef SQLITE_OMIT_AUTOINCREMENT
   68795       if( pOp->p3 ){
   68796         /* Assert that P3 is a valid memory cell. */
   68797         assert( pOp->p3>0 );
   68798         if( p->pFrame ){
   68799           for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
   68800           /* Assert that P3 is a valid memory cell. */
   68801           assert( pOp->p3<=u.bg.pFrame->nMem );
   68802           u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
   68803         }else{
   68804           /* Assert that P3 is a valid memory cell. */
   68805           assert( pOp->p3<=p->nMem );
   68806           u.bg.pMem = &aMem[pOp->p3];
   68807           memAboutToChange(p, u.bg.pMem);
   68808         }
   68809         assert( memIsValid(u.bg.pMem) );
   68810 
   68811         REGISTER_TRACE(pOp->p3, u.bg.pMem);
   68812         sqlite3VdbeMemIntegerify(u.bg.pMem);
   68813         assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   68814         if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
   68815           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   68816           goto abort_due_to_error;
   68817         }
   68818         if( u.bg.v<u.bg.pMem->u.i+1 ){
   68819           u.bg.v = u.bg.pMem->u.i + 1;
   68820         }
   68821         u.bg.pMem->u.i = u.bg.v;
   68822       }
   68823 #endif
   68824 
   68825       sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
   68826     }
   68827     if( u.bg.pC->useRandomRowid ){
   68828       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   68829       ** largest possible integer (9223372036854775807) then the database
   68830       ** engine starts picking positive candidate ROWIDs at random until
   68831       ** it finds one that is not previously used. */
   68832       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   68833                              ** an AUTOINCREMENT table. */
   68834       /* on the first attempt, simply do one more than previous */
   68835       u.bg.v = lastRowid;
   68836       u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   68837       u.bg.v++; /* ensure non-zero */
   68838       u.bg.cnt = 0;
   68839       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
   68840                                                  0, &u.bg.res))==SQLITE_OK)
   68841             && (u.bg.res==0)
   68842             && (++u.bg.cnt<100)){
   68843         /* collision - try another random rowid */
   68844         sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
   68845         if( u.bg.cnt<5 ){
   68846           /* try "small" random rowids for the initial attempts */
   68847           u.bg.v &= 0xffffff;
   68848         }else{
   68849           u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   68850         }
   68851         u.bg.v++; /* ensure non-zero */
   68852       }
   68853       if( rc==SQLITE_OK && u.bg.res==0 ){
   68854         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   68855         goto abort_due_to_error;
   68856       }
   68857       assert( u.bg.v>0 );  /* EV: R-40812-03570 */
   68858     }
   68859     u.bg.pC->rowidIsValid = 0;
   68860     u.bg.pC->deferredMoveto = 0;
   68861     u.bg.pC->cacheStatus = CACHE_STALE;
   68862   }
   68863   pOut->u.i = u.bg.v;
   68864   break;
   68865 }
   68866 
   68867 /* Opcode: Insert P1 P2 P3 P4 P5
   68868 **
   68869 ** Write an entry into the table of cursor P1.  A new entry is
   68870 ** created if it doesn't already exist or the data for an existing
   68871 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   68872 ** number P2. The key is stored in register P3. The key must
   68873 ** be a MEM_Int.
   68874 **
   68875 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   68876 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   68877 ** then rowid is stored for subsequent return by the
   68878 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   68879 **
   68880 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   68881 ** the last seek operation (OP_NotExists) was a success, then this
   68882 ** operation will not attempt to find the appropriate row before doing
   68883 ** the insert but will instead overwrite the row that the cursor is
   68884 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   68885 ** has already positioned the cursor correctly.  This is an optimization
   68886 ** that boosts performance by avoiding redundant seeks.
   68887 **
   68888 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   68889 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   68890 ** is part of an INSERT operation.  The difference is only important to
   68891 ** the update hook.
   68892 **
   68893 ** Parameter P4 may point to a string containing the table-name, or
   68894 ** may be NULL. If it is not NULL, then the update-hook
   68895 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   68896 **
   68897 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   68898 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   68899 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   68900 ** value of register P2 will then change.  Make sure this does not
   68901 ** cause any problems.)
   68902 **
   68903 ** This instruction only works on tables.  The equivalent instruction
   68904 ** for indices is OP_IdxInsert.
   68905 */
   68906 /* Opcode: InsertInt P1 P2 P3 P4 P5
   68907 **
   68908 ** This works exactly like OP_Insert except that the key is the
   68909 ** integer value P3, not the value of the integer stored in register P3.
   68910 */
   68911 case OP_Insert:
   68912 case OP_InsertInt: {
   68913 #if 0  /* local variables moved into u.bh */
   68914   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   68915   Mem *pKey;        /* MEM cell holding key  for the record */
   68916   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   68917   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   68918   int nZero;        /* Number of zero-bytes to append */
   68919   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   68920   const char *zDb;  /* database name - used by the update hook */
   68921   const char *zTbl; /* Table name - used by the opdate hook */
   68922   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   68923 #endif /* local variables moved into u.bh */
   68924 
   68925   u.bh.pData = &aMem[pOp->p2];
   68926   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68927   assert( memIsValid(u.bh.pData) );
   68928   u.bh.pC = p->apCsr[pOp->p1];
   68929   assert( u.bh.pC!=0 );
   68930   assert( u.bh.pC->pCursor!=0 );
   68931   assert( u.bh.pC->pseudoTableReg==0 );
   68932   assert( u.bh.pC->isTable );
   68933   REGISTER_TRACE(pOp->p2, u.bh.pData);
   68934 
   68935   if( pOp->opcode==OP_Insert ){
   68936     u.bh.pKey = &aMem[pOp->p3];
   68937     assert( u.bh.pKey->flags & MEM_Int );
   68938     assert( memIsValid(u.bh.pKey) );
   68939     REGISTER_TRACE(pOp->p3, u.bh.pKey);
   68940     u.bh.iKey = u.bh.pKey->u.i;
   68941   }else{
   68942     assert( pOp->opcode==OP_InsertInt );
   68943     u.bh.iKey = pOp->p3;
   68944   }
   68945 
   68946   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   68947   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
   68948   if( u.bh.pData->flags & MEM_Null ){
   68949     u.bh.pData->z = 0;
   68950     u.bh.pData->n = 0;
   68951   }else{
   68952     assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
   68953   }
   68954   u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
   68955   if( u.bh.pData->flags & MEM_Zero ){
   68956     u.bh.nZero = u.bh.pData->u.nZero;
   68957   }else{
   68958     u.bh.nZero = 0;
   68959   }
   68960   sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
   68961   rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
   68962                           u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
   68963                           pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
   68964   );
   68965   u.bh.pC->rowidIsValid = 0;
   68966   u.bh.pC->deferredMoveto = 0;
   68967   u.bh.pC->cacheStatus = CACHE_STALE;
   68968 
   68969   /* Invoke the update-hook if required. */
   68970   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   68971     u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
   68972     u.bh.zTbl = pOp->p4.z;
   68973     u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   68974     assert( u.bh.pC->isTable );
   68975     db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
   68976     assert( u.bh.pC->iDb>=0 );
   68977   }
   68978   break;
   68979 }
   68980 
   68981 /* Opcode: Delete P1 P2 * P4 *
   68982 **
   68983 ** Delete the record at which the P1 cursor is currently pointing.
   68984 **
   68985 ** The cursor will be left pointing at either the next or the previous
   68986 ** record in the table. If it is left pointing at the next record, then
   68987 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   68988 ** a record from within an Next loop.
   68989 **
   68990 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   68991 ** incremented (otherwise not).
   68992 **
   68993 ** P1 must not be pseudo-table.  It has to be a real table with
   68994 ** multiple rows.
   68995 **
   68996 ** If P4 is not NULL, then it is the name of the table that P1 is
   68997 ** pointing to.  The update hook will be invoked, if it exists.
   68998 ** If P4 is not NULL then the P1 cursor must have been positioned
   68999 ** using OP_NotFound prior to invoking this opcode.
   69000 */
   69001 case OP_Delete: {
   69002 #if 0  /* local variables moved into u.bi */
   69003   i64 iKey;
   69004   VdbeCursor *pC;
   69005 #endif /* local variables moved into u.bi */
   69006 
   69007   u.bi.iKey = 0;
   69008   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69009   u.bi.pC = p->apCsr[pOp->p1];
   69010   assert( u.bi.pC!=0 );
   69011   assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   69012 
   69013   /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
   69014   ** row being deleted.
   69015   */
   69016   if( db->xUpdateCallback && pOp->p4.z ){
   69017     assert( u.bi.pC->isTable );
   69018     assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
   69019     u.bi.iKey = u.bi.pC->lastRowid;
   69020   }
   69021 
   69022   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   69023   ** OP_Column on the same table without any intervening operations that
   69024   ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
   69025   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   69026   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   69027   ** to guard against future changes to the code generator.
   69028   **/
   69029   assert( u.bi.pC->deferredMoveto==0 );
   69030   rc = sqlite3VdbeCursorMoveto(u.bi.pC);
   69031   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   69032 
   69033   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
   69034   rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
   69035   u.bi.pC->cacheStatus = CACHE_STALE;
   69036 
   69037   /* Invoke the update-hook if required. */
   69038   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   69039     const char *zDb = db->aDb[u.bi.pC->iDb].zName;
   69040     const char *zTbl = pOp->p4.z;
   69041     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
   69042     assert( u.bi.pC->iDb>=0 );
   69043   }
   69044   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   69045   break;
   69046 }
   69047 /* Opcode: ResetCount * * * * *
   69048 **
   69049 ** The value of the change counter is copied to the database handle
   69050 ** change counter (returned by subsequent calls to sqlite3_changes()).
   69051 ** Then the VMs internal change counter resets to 0.
   69052 ** This is used by trigger programs.
   69053 */
   69054 case OP_ResetCount: {
   69055   sqlite3VdbeSetChanges(db, p->nChange);
   69056   p->nChange = 0;
   69057   break;
   69058 }
   69059 
   69060 /* Opcode: SorterCompare P1 P2 P3
   69061 **
   69062 ** P1 is a sorter cursor. This instruction compares the record blob in
   69063 ** register P3 with the entry that the sorter cursor currently points to.
   69064 ** If, excluding the rowid fields at the end, the two records are a match,
   69065 ** fall through to the next instruction. Otherwise, jump to instruction P2.
   69066 */
   69067 case OP_SorterCompare: {
   69068 #if 0  /* local variables moved into u.bj */
   69069   VdbeCursor *pC;
   69070   int res;
   69071 #endif /* local variables moved into u.bj */
   69072 
   69073   u.bj.pC = p->apCsr[pOp->p1];
   69074   assert( isSorter(u.bj.pC) );
   69075   pIn3 = &aMem[pOp->p3];
   69076   rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
   69077   if( u.bj.res ){
   69078     pc = pOp->p2-1;
   69079   }
   69080   break;
   69081 };
   69082 
   69083 /* Opcode: SorterData P1 P2 * * *
   69084 **
   69085 ** Write into register P2 the current sorter data for sorter cursor P1.
   69086 */
   69087 case OP_SorterData: {
   69088 #if 0  /* local variables moved into u.bk */
   69089   VdbeCursor *pC;
   69090 #endif /* local variables moved into u.bk */
   69091 #ifndef SQLITE_OMIT_MERGE_SORT
   69092   pOut = &aMem[pOp->p2];
   69093   u.bk.pC = p->apCsr[pOp->p1];
   69094   assert( u.bk.pC->isSorter );
   69095   rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
   69096 #else
   69097   pOp->opcode = OP_RowKey;
   69098   pc--;
   69099 #endif
   69100   break;
   69101 }
   69102 
   69103 /* Opcode: RowData P1 P2 * * *
   69104 **
   69105 ** Write into register P2 the complete row data for cursor P1.
   69106 ** There is no interpretation of the data.
   69107 ** It is just copied onto the P2 register exactly as
   69108 ** it is found in the database file.
   69109 **
   69110 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   69111 ** of a real table, not a pseudo-table.
   69112 */
   69113 /* Opcode: RowKey P1 P2 * * *
   69114 **
   69115 ** Write into register P2 the complete row key for cursor P1.
   69116 ** There is no interpretation of the data.
   69117 ** The key is copied onto the P3 register exactly as
   69118 ** it is found in the database file.
   69119 **
   69120 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   69121 ** of a real table, not a pseudo-table.
   69122 */
   69123 case OP_RowKey:
   69124 case OP_RowData: {
   69125 #if 0  /* local variables moved into u.bl */
   69126   VdbeCursor *pC;
   69127   BtCursor *pCrsr;
   69128   u32 n;
   69129   i64 n64;
   69130 #endif /* local variables moved into u.bl */
   69131 
   69132   pOut = &aMem[pOp->p2];
   69133   memAboutToChange(p, pOut);
   69134 
   69135   /* Note that RowKey and RowData are really exactly the same instruction */
   69136   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69137   u.bl.pC = p->apCsr[pOp->p1];
   69138   assert( u.bl.pC->isSorter==0 );
   69139   assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
   69140   assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
   69141   assert( u.bl.pC!=0 );
   69142   assert( u.bl.pC->nullRow==0 );
   69143   assert( u.bl.pC->pseudoTableReg==0 );
   69144   assert( !u.bl.pC->isSorter );
   69145   assert( u.bl.pC->pCursor!=0 );
   69146   u.bl.pCrsr = u.bl.pC->pCursor;
   69147   assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
   69148 
   69149   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   69150   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   69151   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   69152   ** a no-op and can never fail.  But we leave it in place as a safety.
   69153   */
   69154   assert( u.bl.pC->deferredMoveto==0 );
   69155   rc = sqlite3VdbeCursorMoveto(u.bl.pC);
   69156   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   69157 
   69158   if( u.bl.pC->isIndex ){
   69159     assert( !u.bl.pC->isTable );
   69160     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
   69161     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   69162     if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69163       goto too_big;
   69164     }
   69165     u.bl.n = (u32)u.bl.n64;
   69166   }else{
   69167     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
   69168     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   69169     if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69170       goto too_big;
   69171     }
   69172   }
   69173   if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
   69174     goto no_mem;
   69175   }
   69176   pOut->n = u.bl.n;
   69177   MemSetTypeFlag(pOut, MEM_Blob);
   69178   if( u.bl.pC->isIndex ){
   69179     rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
   69180   }else{
   69181     rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
   69182   }
   69183   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   69184   UPDATE_MAX_BLOBSIZE(pOut);
   69185   break;
   69186 }
   69187 
   69188 /* Opcode: Rowid P1 P2 * * *
   69189 **
   69190 ** Store in register P2 an integer which is the key of the table entry that
   69191 ** P1 is currently point to.
   69192 **
   69193 ** P1 can be either an ordinary table or a virtual table.  There used to
   69194 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   69195 ** one opcode now works for both table types.
   69196 */
   69197 case OP_Rowid: {                 /* out2-prerelease */
   69198 #if 0  /* local variables moved into u.bm */
   69199   VdbeCursor *pC;
   69200   i64 v;
   69201   sqlite3_vtab *pVtab;
   69202   const sqlite3_module *pModule;
   69203 #endif /* local variables moved into u.bm */
   69204 
   69205   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69206   u.bm.pC = p->apCsr[pOp->p1];
   69207   assert( u.bm.pC!=0 );
   69208   assert( u.bm.pC->pseudoTableReg==0 );
   69209   if( u.bm.pC->nullRow ){
   69210     pOut->flags = MEM_Null;
   69211     break;
   69212   }else if( u.bm.pC->deferredMoveto ){
   69213     u.bm.v = u.bm.pC->movetoTarget;
   69214 #ifndef SQLITE_OMIT_VIRTUALTABLE
   69215   }else if( u.bm.pC->pVtabCursor ){
   69216     u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
   69217     u.bm.pModule = u.bm.pVtab->pModule;
   69218     assert( u.bm.pModule->xRowid );
   69219     rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
   69220     importVtabErrMsg(p, u.bm.pVtab);
   69221 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   69222   }else{
   69223     assert( u.bm.pC->pCursor!=0 );
   69224     rc = sqlite3VdbeCursorMoveto(u.bm.pC);
   69225     if( rc ) goto abort_due_to_error;
   69226     if( u.bm.pC->rowidIsValid ){
   69227       u.bm.v = u.bm.pC->lastRowid;
   69228     }else{
   69229       rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
   69230       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   69231     }
   69232   }
   69233   pOut->u.i = u.bm.v;
   69234   break;
   69235 }
   69236 
   69237 /* Opcode: NullRow P1 * * * *
   69238 **
   69239 ** Move the cursor P1 to a null row.  Any OP_Column operations
   69240 ** that occur while the cursor is on the null row will always
   69241 ** write a NULL.
   69242 */
   69243 case OP_NullRow: {
   69244 #if 0  /* local variables moved into u.bn */
   69245   VdbeCursor *pC;
   69246 #endif /* local variables moved into u.bn */
   69247 
   69248   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69249   u.bn.pC = p->apCsr[pOp->p1];
   69250   assert( u.bn.pC!=0 );
   69251   u.bn.pC->nullRow = 1;
   69252   u.bn.pC->rowidIsValid = 0;
   69253   assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
   69254   if( u.bn.pC->pCursor ){
   69255     sqlite3BtreeClearCursor(u.bn.pC->pCursor);
   69256   }
   69257   break;
   69258 }
   69259 
   69260 /* Opcode: Last P1 P2 * * *
   69261 **
   69262 ** The next use of the Rowid or Column or Next instruction for P1
   69263 ** will refer to the last entry in the database table or index.
   69264 ** If the table or index is empty and P2>0, then jump immediately to P2.
   69265 ** If P2 is 0 or if the table or index is not empty, fall through
   69266 ** to the following instruction.
   69267 */
   69268 case OP_Last: {        /* jump */
   69269 #if 0  /* local variables moved into u.bo */
   69270   VdbeCursor *pC;
   69271   BtCursor *pCrsr;
   69272   int res;
   69273 #endif /* local variables moved into u.bo */
   69274 
   69275   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69276   u.bo.pC = p->apCsr[pOp->p1];
   69277   assert( u.bo.pC!=0 );
   69278   u.bo.pCrsr = u.bo.pC->pCursor;
   69279   u.bo.res = 0;
   69280   if( ALWAYS(u.bo.pCrsr!=0) ){
   69281     rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
   69282   }
   69283   u.bo.pC->nullRow = (u8)u.bo.res;
   69284   u.bo.pC->deferredMoveto = 0;
   69285   u.bo.pC->rowidIsValid = 0;
   69286   u.bo.pC->cacheStatus = CACHE_STALE;
   69287   if( pOp->p2>0 && u.bo.res ){
   69288     pc = pOp->p2 - 1;
   69289   }
   69290   break;
   69291 }
   69292 
   69293 
   69294 /* Opcode: Sort P1 P2 * * *
   69295 **
   69296 ** This opcode does exactly the same thing as OP_Rewind except that
   69297 ** it increments an undocumented global variable used for testing.
   69298 **
   69299 ** Sorting is accomplished by writing records into a sorting index,
   69300 ** then rewinding that index and playing it back from beginning to
   69301 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   69302 ** rewinding so that the global variable will be incremented and
   69303 ** regression tests can determine whether or not the optimizer is
   69304 ** correctly optimizing out sorts.
   69305 */
   69306 case OP_SorterSort:    /* jump */
   69307 #ifdef SQLITE_OMIT_MERGE_SORT
   69308   pOp->opcode = OP_Sort;
   69309 #endif
   69310 case OP_Sort: {        /* jump */
   69311 #ifdef SQLITE_TEST
   69312   sqlite3_sort_count++;
   69313   sqlite3_search_count--;
   69314 #endif
   69315   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
   69316   /* Fall through into OP_Rewind */
   69317 }
   69318 /* Opcode: Rewind P1 P2 * * *
   69319 **
   69320 ** The next use of the Rowid or Column or Next instruction for P1
   69321 ** will refer to the first entry in the database table or index.
   69322 ** If the table or index is empty and P2>0, then jump immediately to P2.
   69323 ** If P2 is 0 or if the table or index is not empty, fall through
   69324 ** to the following instruction.
   69325 */
   69326 case OP_Rewind: {        /* jump */
   69327 #if 0  /* local variables moved into u.bp */
   69328   VdbeCursor *pC;
   69329   BtCursor *pCrsr;
   69330   int res;
   69331 #endif /* local variables moved into u.bp */
   69332 
   69333   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69334   u.bp.pC = p->apCsr[pOp->p1];
   69335   assert( u.bp.pC!=0 );
   69336   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
   69337   u.bp.res = 1;
   69338   if( isSorter(u.bp.pC) ){
   69339     rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
   69340   }else{
   69341     u.bp.pCrsr = u.bp.pC->pCursor;
   69342     assert( u.bp.pCrsr );
   69343     rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
   69344     u.bp.pC->atFirst = u.bp.res==0 ?1:0;
   69345     u.bp.pC->deferredMoveto = 0;
   69346     u.bp.pC->cacheStatus = CACHE_STALE;
   69347     u.bp.pC->rowidIsValid = 0;
   69348   }
   69349   u.bp.pC->nullRow = (u8)u.bp.res;
   69350   assert( pOp->p2>0 && pOp->p2<p->nOp );
   69351   if( u.bp.res ){
   69352     pc = pOp->p2 - 1;
   69353   }
   69354   break;
   69355 }
   69356 
   69357 /* Opcode: Next P1 P2 * P4 P5
   69358 **
   69359 ** Advance cursor P1 so that it points to the next key/data pair in its
   69360 ** table or index.  If there are no more key/value pairs then fall through
   69361 ** to the following instruction.  But if the cursor advance was successful,
   69362 ** jump immediately to P2.
   69363 **
   69364 ** The P1 cursor must be for a real table, not a pseudo-table.
   69365 **
   69366 ** P4 is always of type P4_ADVANCE. The function pointer points to
   69367 ** sqlite3BtreeNext().
   69368 **
   69369 ** If P5 is positive and the jump is taken, then event counter
   69370 ** number P5-1 in the prepared statement is incremented.
   69371 **
   69372 ** See also: Prev
   69373 */
   69374 /* Opcode: Prev P1 P2 * * P5
   69375 **
   69376 ** Back up cursor P1 so that it points to the previous key/data pair in its
   69377 ** table or index.  If there is no previous key/value pairs then fall through
   69378 ** to the following instruction.  But if the cursor backup was successful,
   69379 ** jump immediately to P2.
   69380 **
   69381 ** The P1 cursor must be for a real table, not a pseudo-table.
   69382 **
   69383 ** P4 is always of type P4_ADVANCE. The function pointer points to
   69384 ** sqlite3BtreePrevious().
   69385 **
   69386 ** If P5 is positive and the jump is taken, then event counter
   69387 ** number P5-1 in the prepared statement is incremented.
   69388 */
   69389 case OP_SorterNext:    /* jump */
   69390 #ifdef SQLITE_OMIT_MERGE_SORT
   69391   pOp->opcode = OP_Next;
   69392 #endif
   69393 case OP_Prev:          /* jump */
   69394 case OP_Next: {        /* jump */
   69395 #if 0  /* local variables moved into u.bq */
   69396   VdbeCursor *pC;
   69397   int res;
   69398 #endif /* local variables moved into u.bq */
   69399 
   69400   CHECK_FOR_INTERRUPT;
   69401   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69402   assert( pOp->p5<=ArraySize(p->aCounter) );
   69403   u.bq.pC = p->apCsr[pOp->p1];
   69404   if( u.bq.pC==0 ){
   69405     break;  /* See ticket #2273 */
   69406   }
   69407   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
   69408   if( isSorter(u.bq.pC) ){
   69409     assert( pOp->opcode==OP_SorterNext );
   69410     rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
   69411   }else{
   69412     u.bq.res = 1;
   69413     assert( u.bq.pC->deferredMoveto==0 );
   69414     assert( u.bq.pC->pCursor );
   69415     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
   69416     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
   69417     rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
   69418   }
   69419   u.bq.pC->nullRow = (u8)u.bq.res;
   69420   u.bq.pC->cacheStatus = CACHE_STALE;
   69421   if( u.bq.res==0 ){
   69422     pc = pOp->p2 - 1;
   69423     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
   69424 #ifdef SQLITE_TEST
   69425     sqlite3_search_count++;
   69426 #endif
   69427   }
   69428   u.bq.pC->rowidIsValid = 0;
   69429   break;
   69430 }
   69431 
   69432 /* Opcode: IdxInsert P1 P2 P3 * P5
   69433 **
   69434 ** Register P2 holds an SQL index key made using the
   69435 ** MakeRecord instructions.  This opcode writes that key
   69436 ** into the index P1.  Data for the entry is nil.
   69437 **
   69438 ** P3 is a flag that provides a hint to the b-tree layer that this
   69439 ** insert is likely to be an append.
   69440 **
   69441 ** This instruction only works for indices.  The equivalent instruction
   69442 ** for tables is OP_Insert.
   69443 */
   69444 case OP_SorterInsert:       /* in2 */
   69445 #ifdef SQLITE_OMIT_MERGE_SORT
   69446   pOp->opcode = OP_IdxInsert;
   69447 #endif
   69448 case OP_IdxInsert: {        /* in2 */
   69449 #if 0  /* local variables moved into u.br */
   69450   VdbeCursor *pC;
   69451   BtCursor *pCrsr;
   69452   int nKey;
   69453   const char *zKey;
   69454 #endif /* local variables moved into u.br */
   69455 
   69456   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69457   u.br.pC = p->apCsr[pOp->p1];
   69458   assert( u.br.pC!=0 );
   69459   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
   69460   pIn2 = &aMem[pOp->p2];
   69461   assert( pIn2->flags & MEM_Blob );
   69462   u.br.pCrsr = u.br.pC->pCursor;
   69463   if( ALWAYS(u.br.pCrsr!=0) ){
   69464     assert( u.br.pC->isTable==0 );
   69465     rc = ExpandBlob(pIn2);
   69466     if( rc==SQLITE_OK ){
   69467       if( isSorter(u.br.pC) ){
   69468         rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
   69469       }else{
   69470         u.br.nKey = pIn2->n;
   69471         u.br.zKey = pIn2->z;
   69472         rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
   69473             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
   69474             );
   69475         assert( u.br.pC->deferredMoveto==0 );
   69476         u.br.pC->cacheStatus = CACHE_STALE;
   69477       }
   69478     }
   69479   }
   69480   break;
   69481 }
   69482 
   69483 /* Opcode: IdxDelete P1 P2 P3 * *
   69484 **
   69485 ** The content of P3 registers starting at register P2 form
   69486 ** an unpacked index key. This opcode removes that entry from the
   69487 ** index opened by cursor P1.
   69488 */
   69489 case OP_IdxDelete: {
   69490 #if 0  /* local variables moved into u.bs */
   69491   VdbeCursor *pC;
   69492   BtCursor *pCrsr;
   69493   int res;
   69494   UnpackedRecord r;
   69495 #endif /* local variables moved into u.bs */
   69496 
   69497   assert( pOp->p3>0 );
   69498   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
   69499   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69500   u.bs.pC = p->apCsr[pOp->p1];
   69501   assert( u.bs.pC!=0 );
   69502   u.bs.pCrsr = u.bs.pC->pCursor;
   69503   if( ALWAYS(u.bs.pCrsr!=0) ){
   69504     u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
   69505     u.bs.r.nField = (u16)pOp->p3;
   69506     u.bs.r.flags = 0;
   69507     u.bs.r.aMem = &aMem[pOp->p2];
   69508 #ifdef SQLITE_DEBUG
   69509     { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
   69510 #endif
   69511     rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
   69512     if( rc==SQLITE_OK && u.bs.res==0 ){
   69513       rc = sqlite3BtreeDelete(u.bs.pCrsr);
   69514     }
   69515     assert( u.bs.pC->deferredMoveto==0 );
   69516     u.bs.pC->cacheStatus = CACHE_STALE;
   69517   }
   69518   break;
   69519 }
   69520 
   69521 /* Opcode: IdxRowid P1 P2 * * *
   69522 **
   69523 ** Write into register P2 an integer which is the last entry in the record at
   69524 ** the end of the index key pointed to by cursor P1.  This integer should be
   69525 ** the rowid of the table entry to which this index entry points.
   69526 **
   69527 ** See also: Rowid, MakeRecord.
   69528 */
   69529 case OP_IdxRowid: {              /* out2-prerelease */
   69530 #if 0  /* local variables moved into u.bt */
   69531   BtCursor *pCrsr;
   69532   VdbeCursor *pC;
   69533   i64 rowid;
   69534 #endif /* local variables moved into u.bt */
   69535 
   69536   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69537   u.bt.pC = p->apCsr[pOp->p1];
   69538   assert( u.bt.pC!=0 );
   69539   u.bt.pCrsr = u.bt.pC->pCursor;
   69540   pOut->flags = MEM_Null;
   69541   if( ALWAYS(u.bt.pCrsr!=0) ){
   69542     rc = sqlite3VdbeCursorMoveto(u.bt.pC);
   69543     if( NEVER(rc) ) goto abort_due_to_error;
   69544     assert( u.bt.pC->deferredMoveto==0 );
   69545     assert( u.bt.pC->isTable==0 );
   69546     if( !u.bt.pC->nullRow ){
   69547       rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
   69548       if( rc!=SQLITE_OK ){
   69549         goto abort_due_to_error;
   69550       }
   69551       pOut->u.i = u.bt.rowid;
   69552       pOut->flags = MEM_Int;
   69553     }
   69554   }
   69555   break;
   69556 }
   69557 
   69558 /* Opcode: IdxGE P1 P2 P3 P4 P5
   69559 **
   69560 ** The P4 register values beginning with P3 form an unpacked index
   69561 ** key that omits the ROWID.  Compare this key value against the index
   69562 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   69563 **
   69564 ** If the P1 index entry is greater than or equal to the key value
   69565 ** then jump to P2.  Otherwise fall through to the next instruction.
   69566 **
   69567 ** If P5 is non-zero then the key value is increased by an epsilon
   69568 ** prior to the comparison.  This make the opcode work like IdxGT except
   69569 ** that if the key from register P3 is a prefix of the key in the cursor,
   69570 ** the result is false whereas it would be true with IdxGT.
   69571 */
   69572 /* Opcode: IdxLT P1 P2 P3 P4 P5
   69573 **
   69574 ** The P4 register values beginning with P3 form an unpacked index
   69575 ** key that omits the ROWID.  Compare this key value against the index
   69576 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   69577 **
   69578 ** If the P1 index entry is less than the key value then jump to P2.
   69579 ** Otherwise fall through to the next instruction.
   69580 **
   69581 ** If P5 is non-zero then the key value is increased by an epsilon prior
   69582 ** to the comparison.  This makes the opcode work like IdxLE.
   69583 */
   69584 case OP_IdxLT:          /* jump */
   69585 case OP_IdxGE: {        /* jump */
   69586 #if 0  /* local variables moved into u.bu */
   69587   VdbeCursor *pC;
   69588   int res;
   69589   UnpackedRecord r;
   69590 #endif /* local variables moved into u.bu */
   69591 
   69592   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69593   u.bu.pC = p->apCsr[pOp->p1];
   69594   assert( u.bu.pC!=0 );
   69595   assert( u.bu.pC->isOrdered );
   69596   if( ALWAYS(u.bu.pC->pCursor!=0) ){
   69597     assert( u.bu.pC->deferredMoveto==0 );
   69598     assert( pOp->p5==0 || pOp->p5==1 );
   69599     assert( pOp->p4type==P4_INT32 );
   69600     u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
   69601     u.bu.r.nField = (u16)pOp->p4.i;
   69602     if( pOp->p5 ){
   69603       u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
   69604     }else{
   69605       u.bu.r.flags = UNPACKED_PREFIX_MATCH;
   69606     }
   69607     u.bu.r.aMem = &aMem[pOp->p3];
   69608 #ifdef SQLITE_DEBUG
   69609     { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
   69610 #endif
   69611     rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
   69612     if( pOp->opcode==OP_IdxLT ){
   69613       u.bu.res = -u.bu.res;
   69614     }else{
   69615       assert( pOp->opcode==OP_IdxGE );
   69616       u.bu.res++;
   69617     }
   69618     if( u.bu.res>0 ){
   69619       pc = pOp->p2 - 1 ;
   69620     }
   69621   }
   69622   break;
   69623 }
   69624 
   69625 /* Opcode: Destroy P1 P2 P3 * *
   69626 **
   69627 ** Delete an entire database table or index whose root page in the database
   69628 ** file is given by P1.
   69629 **
   69630 ** The table being destroyed is in the main database file if P3==0.  If
   69631 ** P3==1 then the table to be clear is in the auxiliary database file
   69632 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   69633 **
   69634 ** If AUTOVACUUM is enabled then it is possible that another root page
   69635 ** might be moved into the newly deleted root page in order to keep all
   69636 ** root pages contiguous at the beginning of the database.  The former
   69637 ** value of the root page that moved - its value before the move occurred -
   69638 ** is stored in register P2.  If no page
   69639 ** movement was required (because the table being dropped was already
   69640 ** the last one in the database) then a zero is stored in register P2.
   69641 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   69642 **
   69643 ** See also: Clear
   69644 */
   69645 case OP_Destroy: {     /* out2-prerelease */
   69646 #if 0  /* local variables moved into u.bv */
   69647   int iMoved;
   69648   int iCnt;
   69649   Vdbe *pVdbe;
   69650   int iDb;
   69651 #endif /* local variables moved into u.bv */
   69652 #ifndef SQLITE_OMIT_VIRTUALTABLE
   69653   u.bv.iCnt = 0;
   69654   for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
   69655     if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
   69656       u.bv.iCnt++;
   69657     }
   69658   }
   69659 #else
   69660   u.bv.iCnt = db->activeVdbeCnt;
   69661 #endif
   69662   pOut->flags = MEM_Null;
   69663   if( u.bv.iCnt>1 ){
   69664     rc = SQLITE_LOCKED;
   69665     p->errorAction = OE_Abort;
   69666   }else{
   69667     u.bv.iDb = pOp->p3;
   69668     assert( u.bv.iCnt==1 );
   69669     assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
   69670     rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
   69671     pOut->flags = MEM_Int;
   69672     pOut->u.i = u.bv.iMoved;
   69673 #ifndef SQLITE_OMIT_AUTOVACUUM
   69674     if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
   69675       sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
   69676       /* All OP_Destroy operations occur on the same btree */
   69677       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
   69678       resetSchemaOnFault = u.bv.iDb+1;
   69679     }
   69680 #endif
   69681   }
   69682   break;
   69683 }
   69684 
   69685 /* Opcode: Clear P1 P2 P3
   69686 **
   69687 ** Delete all contents of the database table or index whose root page
   69688 ** in the database file is given by P1.  But, unlike Destroy, do not
   69689 ** remove the table or index from the database file.
   69690 **
   69691 ** The table being clear is in the main database file if P2==0.  If
   69692 ** P2==1 then the table to be clear is in the auxiliary database file
   69693 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   69694 **
   69695 ** If the P3 value is non-zero, then the table referred to must be an
   69696 ** intkey table (an SQL table, not an index). In this case the row change
   69697 ** count is incremented by the number of rows in the table being cleared.
   69698 ** If P3 is greater than zero, then the value stored in register P3 is
   69699 ** also incremented by the number of rows in the table being cleared.
   69700 **
   69701 ** See also: Destroy
   69702 */
   69703 case OP_Clear: {
   69704 #if 0  /* local variables moved into u.bw */
   69705   int nChange;
   69706 #endif /* local variables moved into u.bw */
   69707 
   69708   u.bw.nChange = 0;
   69709   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
   69710   rc = sqlite3BtreeClearTable(
   69711       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
   69712   );
   69713   if( pOp->p3 ){
   69714     p->nChange += u.bw.nChange;
   69715     if( pOp->p3>0 ){
   69716       assert( memIsValid(&aMem[pOp->p3]) );
   69717       memAboutToChange(p, &aMem[pOp->p3]);
   69718       aMem[pOp->p3].u.i += u.bw.nChange;
   69719     }
   69720   }
   69721   break;
   69722 }
   69723 
   69724 /* Opcode: CreateTable P1 P2 * * *
   69725 **
   69726 ** Allocate a new table in the main database file if P1==0 or in the
   69727 ** auxiliary database file if P1==1 or in an attached database if
   69728 ** P1>1.  Write the root page number of the new table into
   69729 ** register P2
   69730 **
   69731 ** The difference between a table and an index is this:  A table must
   69732 ** have a 4-byte integer key and can have arbitrary data.  An index
   69733 ** has an arbitrary key but no data.
   69734 **
   69735 ** See also: CreateIndex
   69736 */
   69737 /* Opcode: CreateIndex P1 P2 * * *
   69738 **
   69739 ** Allocate a new index in the main database file if P1==0 or in the
   69740 ** auxiliary database file if P1==1 or in an attached database if
   69741 ** P1>1.  Write the root page number of the new table into
   69742 ** register P2.
   69743 **
   69744 ** See documentation on OP_CreateTable for additional information.
   69745 */
   69746 case OP_CreateIndex:            /* out2-prerelease */
   69747 case OP_CreateTable: {          /* out2-prerelease */
   69748 #if 0  /* local variables moved into u.bx */
   69749   int pgno;
   69750   int flags;
   69751   Db *pDb;
   69752 #endif /* local variables moved into u.bx */
   69753 
   69754   u.bx.pgno = 0;
   69755   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   69756   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   69757   u.bx.pDb = &db->aDb[pOp->p1];
   69758   assert( u.bx.pDb->pBt!=0 );
   69759   if( pOp->opcode==OP_CreateTable ){
   69760     /* u.bx.flags = BTREE_INTKEY; */
   69761     u.bx.flags = BTREE_INTKEY;
   69762   }else{
   69763     u.bx.flags = BTREE_BLOBKEY;
   69764   }
   69765   rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
   69766   pOut->u.i = u.bx.pgno;
   69767   break;
   69768 }
   69769 
   69770 /* Opcode: ParseSchema P1 * * P4 *
   69771 **
   69772 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   69773 ** that match the WHERE clause P4.
   69774 **
   69775 ** This opcode invokes the parser to create a new virtual machine,
   69776 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   69777 */
   69778 case OP_ParseSchema: {
   69779 #if 0  /* local variables moved into u.by */
   69780   int iDb;
   69781   const char *zMaster;
   69782   char *zSql;
   69783   InitData initData;
   69784 #endif /* local variables moved into u.by */
   69785 
   69786   /* Any prepared statement that invokes this opcode will hold mutexes
   69787   ** on every btree.  This is a prerequisite for invoking
   69788   ** sqlite3InitCallback().
   69789   */
   69790 #ifdef SQLITE_DEBUG
   69791   for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
   69792     assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
   69793   }
   69794 #endif
   69795 
   69796   u.by.iDb = pOp->p1;
   69797   assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
   69798   assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
   69799   /* Used to be a conditional */ {
   69800     u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
   69801     u.by.initData.db = db;
   69802     u.by.initData.iDb = pOp->p1;
   69803     u.by.initData.pzErrMsg = &p->zErrMsg;
   69804     u.by.zSql = sqlite3MPrintf(db,
   69805        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   69806        db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
   69807     if( u.by.zSql==0 ){
   69808       rc = SQLITE_NOMEM;
   69809     }else{
   69810       assert( db->init.busy==0 );
   69811       db->init.busy = 1;
   69812       u.by.initData.rc = SQLITE_OK;
   69813       assert( !db->mallocFailed );
   69814       rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
   69815       if( rc==SQLITE_OK ) rc = u.by.initData.rc;
   69816       sqlite3DbFree(db, u.by.zSql);
   69817       db->init.busy = 0;
   69818     }
   69819   }
   69820   if( rc ) sqlite3ResetInternalSchema(db, -1);
   69821   if( rc==SQLITE_NOMEM ){
   69822     goto no_mem;
   69823   }
   69824   break;
   69825 }
   69826 
   69827 #if !defined(SQLITE_OMIT_ANALYZE)
   69828 /* Opcode: LoadAnalysis P1 * * * *
   69829 **
   69830 ** Read the sqlite_stat1 table for database P1 and load the content
   69831 ** of that table into the internal index hash table.  This will cause
   69832 ** the analysis to be used when preparing all subsequent queries.
   69833 */
   69834 case OP_LoadAnalysis: {
   69835   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   69836   rc = sqlite3AnalysisLoad(db, pOp->p1);
   69837   break;
   69838 }
   69839 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   69840 
   69841 /* Opcode: DropTable P1 * * P4 *
   69842 **
   69843 ** Remove the internal (in-memory) data structures that describe
   69844 ** the table named P4 in database P1.  This is called after a table
   69845 ** is dropped in order to keep the internal representation of the
   69846 ** schema consistent with what is on disk.
   69847 */
   69848 case OP_DropTable: {
   69849   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   69850   break;
   69851 }
   69852 
   69853 /* Opcode: DropIndex P1 * * P4 *
   69854 **
   69855 ** Remove the internal (in-memory) data structures that describe
   69856 ** the index named P4 in database P1.  This is called after an index
   69857 ** is dropped in order to keep the internal representation of the
   69858 ** schema consistent with what is on disk.
   69859 */
   69860 case OP_DropIndex: {
   69861   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   69862   break;
   69863 }
   69864 
   69865 /* Opcode: DropTrigger P1 * * P4 *
   69866 **
   69867 ** Remove the internal (in-memory) data structures that describe
   69868 ** the trigger named P4 in database P1.  This is called after a trigger
   69869 ** is dropped in order to keep the internal representation of the
   69870 ** schema consistent with what is on disk.
   69871 */
   69872 case OP_DropTrigger: {
   69873   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   69874   break;
   69875 }
   69876 
   69877 
   69878 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69879 /* Opcode: IntegrityCk P1 P2 P3 * P5
   69880 **
   69881 ** Do an analysis of the currently open database.  Store in
   69882 ** register P1 the text of an error message describing any problems.
   69883 ** If no problems are found, store a NULL in register P1.
   69884 **
   69885 ** The register P3 contains the maximum number of allowed errors.
   69886 ** At most reg(P3) errors will be reported.
   69887 ** In other words, the analysis stops as soon as reg(P1) errors are
   69888 ** seen.  Reg(P1) is updated with the number of errors remaining.
   69889 **
   69890 ** The root page numbers of all tables in the database are integer
   69891 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   69892 ** total.
   69893 **
   69894 ** If P5 is not zero, the check is done on the auxiliary database
   69895 ** file, not the main database file.
   69896 **
   69897 ** This opcode is used to implement the integrity_check pragma.
   69898 */
   69899 case OP_IntegrityCk: {
   69900 #if 0  /* local variables moved into u.bz */
   69901   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   69902   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   69903   int j;          /* Loop counter */
   69904   int nErr;       /* Number of errors reported */
   69905   char *z;        /* Text of the error report */
   69906   Mem *pnErr;     /* Register keeping track of errors remaining */
   69907 #endif /* local variables moved into u.bz */
   69908 
   69909   u.bz.nRoot = pOp->p2;
   69910   assert( u.bz.nRoot>0 );
   69911   u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
   69912   if( u.bz.aRoot==0 ) goto no_mem;
   69913   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   69914   u.bz.pnErr = &aMem[pOp->p3];
   69915   assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
   69916   assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   69917   pIn1 = &aMem[pOp->p1];
   69918   for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
   69919     u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
   69920   }
   69921   u.bz.aRoot[u.bz.j] = 0;
   69922   assert( pOp->p5<db->nDb );
   69923   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
   69924   u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
   69925                                  (int)u.bz.pnErr->u.i, &u.bz.nErr);
   69926   sqlite3DbFree(db, u.bz.aRoot);
   69927   u.bz.pnErr->u.i -= u.bz.nErr;
   69928   sqlite3VdbeMemSetNull(pIn1);
   69929   if( u.bz.nErr==0 ){
   69930     assert( u.bz.z==0 );
   69931   }else if( u.bz.z==0 ){
   69932     goto no_mem;
   69933   }else{
   69934     sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
   69935   }
   69936   UPDATE_MAX_BLOBSIZE(pIn1);
   69937   sqlite3VdbeChangeEncoding(pIn1, encoding);
   69938   break;
   69939 }
   69940 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   69941 
   69942 /* Opcode: RowSetAdd P1 P2 * * *
   69943 **
   69944 ** Insert the integer value held by register P2 into a boolean index
   69945 ** held in register P1.
   69946 **
   69947 ** An assertion fails if P2 is not an integer.
   69948 */
   69949 case OP_RowSetAdd: {       /* in1, in2 */
   69950   pIn1 = &aMem[pOp->p1];
   69951   pIn2 = &aMem[pOp->p2];
   69952   assert( (pIn2->flags & MEM_Int)!=0 );
   69953   if( (pIn1->flags & MEM_RowSet)==0 ){
   69954     sqlite3VdbeMemSetRowSet(pIn1);
   69955     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   69956   }
   69957   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   69958   break;
   69959 }
   69960 
   69961 /* Opcode: RowSetRead P1 P2 P3 * *
   69962 **
   69963 ** Extract the smallest value from boolean index P1 and put that value into
   69964 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   69965 ** unchanged and jump to instruction P2.
   69966 */
   69967 case OP_RowSetRead: {       /* jump, in1, out3 */
   69968 #if 0  /* local variables moved into u.ca */
   69969   i64 val;
   69970 #endif /* local variables moved into u.ca */
   69971   CHECK_FOR_INTERRUPT;
   69972   pIn1 = &aMem[pOp->p1];
   69973   if( (pIn1->flags & MEM_RowSet)==0
   69974    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
   69975   ){
   69976     /* The boolean index is empty */
   69977     sqlite3VdbeMemSetNull(pIn1);
   69978     pc = pOp->p2 - 1;
   69979   }else{
   69980     /* A value was pulled from the index */
   69981     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
   69982   }
   69983   break;
   69984 }
   69985 
   69986 /* Opcode: RowSetTest P1 P2 P3 P4
   69987 **
   69988 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   69989 ** contains a RowSet object and that RowSet object contains
   69990 ** the value held in P3, jump to register P2. Otherwise, insert the
   69991 ** integer in P3 into the RowSet and continue on to the
   69992 ** next opcode.
   69993 **
   69994 ** The RowSet object is optimized for the case where successive sets
   69995 ** of integers, where each set contains no duplicates. Each set
   69996 ** of values is identified by a unique P4 value. The first set
   69997 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   69998 ** non-negative.  For non-negative values of P4 only the lower 4
   69999 ** bits are significant.
   70000 **
   70001 ** This allows optimizations: (a) when P4==0 there is no need to test
   70002 ** the rowset object for P3, as it is guaranteed not to contain it,
   70003 ** (b) when P4==-1 there is no need to insert the value, as it will
   70004 ** never be tested for, and (c) when a value that is part of set X is
   70005 ** inserted, there is no need to search to see if the same value was
   70006 ** previously inserted as part of set X (only if it was previously
   70007 ** inserted as part of some other set).
   70008 */
   70009 case OP_RowSetTest: {                     /* jump, in1, in3 */
   70010 #if 0  /* local variables moved into u.cb */
   70011   int iSet;
   70012   int exists;
   70013 #endif /* local variables moved into u.cb */
   70014 
   70015   pIn1 = &aMem[pOp->p1];
   70016   pIn3 = &aMem[pOp->p3];
   70017   u.cb.iSet = pOp->p4.i;
   70018   assert( pIn3->flags&MEM_Int );
   70019 
   70020   /* If there is anything other than a rowset object in memory cell P1,
   70021   ** delete it now and initialize P1 with an empty rowset
   70022   */
   70023   if( (pIn1->flags & MEM_RowSet)==0 ){
   70024     sqlite3VdbeMemSetRowSet(pIn1);
   70025     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   70026   }
   70027 
   70028   assert( pOp->p4type==P4_INT32 );
   70029   assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
   70030   if( u.cb.iSet ){
   70031     u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
   70032                                (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
   70033                                pIn3->u.i);
   70034     if( u.cb.exists ){
   70035       pc = pOp->p2 - 1;
   70036       break;
   70037     }
   70038   }
   70039   if( u.cb.iSet>=0 ){
   70040     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   70041   }
   70042   break;
   70043 }
   70044 
   70045 
   70046 #ifndef SQLITE_OMIT_TRIGGER
   70047 
   70048 /* Opcode: Program P1 P2 P3 P4 *
   70049 **
   70050 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   70051 **
   70052 ** P1 contains the address of the memory cell that contains the first memory
   70053 ** cell in an array of values used as arguments to the sub-program. P2
   70054 ** contains the address to jump to if the sub-program throws an IGNORE
   70055 ** exception using the RAISE() function. Register P3 contains the address
   70056 ** of a memory cell in this (the parent) VM that is used to allocate the
   70057 ** memory required by the sub-vdbe at runtime.
   70058 **
   70059 ** P4 is a pointer to the VM containing the trigger program.
   70060 */
   70061 case OP_Program: {        /* jump */
   70062 #if 0  /* local variables moved into u.cc */
   70063   int nMem;               /* Number of memory registers for sub-program */
   70064   int nByte;              /* Bytes of runtime space required for sub-program */
   70065   Mem *pRt;               /* Register to allocate runtime space */
   70066   Mem *pMem;              /* Used to iterate through memory cells */
   70067   Mem *pEnd;              /* Last memory cell in new array */
   70068   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   70069   SubProgram *pProgram;   /* Sub-program to execute */
   70070   void *t;                /* Token identifying trigger */
   70071 #endif /* local variables moved into u.cc */
   70072 
   70073   u.cc.pProgram = pOp->p4.pProgram;
   70074   u.cc.pRt = &aMem[pOp->p3];
   70075   assert( u.cc.pProgram->nOp>0 );
   70076 
   70077   /* If the p5 flag is clear, then recursive invocation of triggers is
   70078   ** disabled for backwards compatibility (p5 is set if this sub-program
   70079   ** is really a trigger, not a foreign key action, and the flag set
   70080   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   70081   **
   70082   ** It is recursive invocation of triggers, at the SQL level, that is
   70083   ** disabled. In some cases a single trigger may generate more than one
   70084   ** SubProgram (if the trigger may be executed with more than one different
   70085   ** ON CONFLICT algorithm). SubProgram structures associated with a
   70086   ** single trigger all have the same value for the SubProgram.token
   70087   ** variable.  */
   70088   if( pOp->p5 ){
   70089     u.cc.t = u.cc.pProgram->token;
   70090     for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
   70091     if( u.cc.pFrame ) break;
   70092   }
   70093 
   70094   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   70095     rc = SQLITE_ERROR;
   70096     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   70097     break;
   70098   }
   70099 
   70100   /* Register u.cc.pRt is used to store the memory required to save the state
   70101   ** of the current program, and the memory required at runtime to execute
   70102   ** the trigger program. If this trigger has been fired before, then u.cc.pRt
   70103   ** is already allocated. Otherwise, it must be initialized.  */
   70104   if( (u.cc.pRt->flags&MEM_Frame)==0 ){
   70105     /* SubProgram.nMem is set to the number of memory cells used by the
   70106     ** program stored in SubProgram.aOp. As well as these, one memory
   70107     ** cell is required for each cursor used by the program. Set local
   70108     ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
   70109     */
   70110     u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
   70111     u.cc.nByte = ROUND8(sizeof(VdbeFrame))
   70112               + u.cc.nMem * sizeof(Mem)
   70113               + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
   70114               + u.cc.pProgram->nOnce * sizeof(u8);
   70115     u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
   70116     if( !u.cc.pFrame ){
   70117       goto no_mem;
   70118     }
   70119     sqlite3VdbeMemRelease(u.cc.pRt);
   70120     u.cc.pRt->flags = MEM_Frame;
   70121     u.cc.pRt->u.pFrame = u.cc.pFrame;
   70122 
   70123     u.cc.pFrame->v = p;
   70124     u.cc.pFrame->nChildMem = u.cc.nMem;
   70125     u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
   70126     u.cc.pFrame->pc = pc;
   70127     u.cc.pFrame->aMem = p->aMem;
   70128     u.cc.pFrame->nMem = p->nMem;
   70129     u.cc.pFrame->apCsr = p->apCsr;
   70130     u.cc.pFrame->nCursor = p->nCursor;
   70131     u.cc.pFrame->aOp = p->aOp;
   70132     u.cc.pFrame->nOp = p->nOp;
   70133     u.cc.pFrame->token = u.cc.pProgram->token;
   70134     u.cc.pFrame->aOnceFlag = p->aOnceFlag;
   70135     u.cc.pFrame->nOnceFlag = p->nOnceFlag;
   70136 
   70137     u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
   70138     for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
   70139       u.cc.pMem->flags = MEM_Invalid;
   70140       u.cc.pMem->db = db;
   70141     }
   70142   }else{
   70143     u.cc.pFrame = u.cc.pRt->u.pFrame;
   70144     assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
   70145     assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
   70146     assert( pc==u.cc.pFrame->pc );
   70147   }
   70148 
   70149   p->nFrame++;
   70150   u.cc.pFrame->pParent = p->pFrame;
   70151   u.cc.pFrame->lastRowid = lastRowid;
   70152   u.cc.pFrame->nChange = p->nChange;
   70153   p->nChange = 0;
   70154   p->pFrame = u.cc.pFrame;
   70155   p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
   70156   p->nMem = u.cc.pFrame->nChildMem;
   70157   p->nCursor = (u16)u.cc.pFrame->nChildCsr;
   70158   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   70159   p->aOp = aOp = u.cc.pProgram->aOp;
   70160   p->nOp = u.cc.pProgram->nOp;
   70161   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
   70162   p->nOnceFlag = u.cc.pProgram->nOnce;
   70163   pc = -1;
   70164   memset(p->aOnceFlag, 0, p->nOnceFlag);
   70165 
   70166   break;
   70167 }
   70168 
   70169 /* Opcode: Param P1 P2 * * *
   70170 **
   70171 ** This opcode is only ever present in sub-programs called via the
   70172 ** OP_Program instruction. Copy a value currently stored in a memory
   70173 ** cell of the calling (parent) frame to cell P2 in the current frames
   70174 ** address space. This is used by trigger programs to access the new.*
   70175 ** and old.* values.
   70176 **
   70177 ** The address of the cell in the parent frame is determined by adding
   70178 ** the value of the P1 argument to the value of the P1 argument to the
   70179 ** calling OP_Program instruction.
   70180 */
   70181 case OP_Param: {           /* out2-prerelease */
   70182 #if 0  /* local variables moved into u.cd */
   70183   VdbeFrame *pFrame;
   70184   Mem *pIn;
   70185 #endif /* local variables moved into u.cd */
   70186   u.cd.pFrame = p->pFrame;
   70187   u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
   70188   sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
   70189   break;
   70190 }
   70191 
   70192 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   70193 
   70194 #ifndef SQLITE_OMIT_FOREIGN_KEY
   70195 /* Opcode: FkCounter P1 P2 * * *
   70196 **
   70197 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   70198 ** If P1 is non-zero, the database constraint counter is incremented
   70199 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   70200 ** statement counter is incremented (immediate foreign key constraints).
   70201 */
   70202 case OP_FkCounter: {
   70203   if( pOp->p1 ){
   70204     db->nDeferredCons += pOp->p2;
   70205   }else{
   70206     p->nFkConstraint += pOp->p2;
   70207   }
   70208   break;
   70209 }
   70210 
   70211 /* Opcode: FkIfZero P1 P2 * * *
   70212 **
   70213 ** This opcode tests if a foreign key constraint-counter is currently zero.
   70214 ** If so, jump to instruction P2. Otherwise, fall through to the next
   70215 ** instruction.
   70216 **
   70217 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   70218 ** is zero (the one that counts deferred constraint violations). If P1 is
   70219 ** zero, the jump is taken if the statement constraint-counter is zero
   70220 ** (immediate foreign key constraint violations).
   70221 */
   70222 case OP_FkIfZero: {         /* jump */
   70223   if( pOp->p1 ){
   70224     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
   70225   }else{
   70226     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
   70227   }
   70228   break;
   70229 }
   70230 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   70231 
   70232 #ifndef SQLITE_OMIT_AUTOINCREMENT
   70233 /* Opcode: MemMax P1 P2 * * *
   70234 **
   70235 ** P1 is a register in the root frame of this VM (the root frame is
   70236 ** different from the current frame if this instruction is being executed
   70237 ** within a sub-program). Set the value of register P1 to the maximum of
   70238 ** its current value and the value in register P2.
   70239 **
   70240 ** This instruction throws an error if the memory cell is not initially
   70241 ** an integer.
   70242 */
   70243 case OP_MemMax: {        /* in2 */
   70244 #if 0  /* local variables moved into u.ce */
   70245   Mem *pIn1;
   70246   VdbeFrame *pFrame;
   70247 #endif /* local variables moved into u.ce */
   70248   if( p->pFrame ){
   70249     for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
   70250     u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
   70251   }else{
   70252     u.ce.pIn1 = &aMem[pOp->p1];
   70253   }
   70254   assert( memIsValid(u.ce.pIn1) );
   70255   sqlite3VdbeMemIntegerify(u.ce.pIn1);
   70256   pIn2 = &aMem[pOp->p2];
   70257   sqlite3VdbeMemIntegerify(pIn2);
   70258   if( u.ce.pIn1->u.i<pIn2->u.i){
   70259     u.ce.pIn1->u.i = pIn2->u.i;
   70260   }
   70261   break;
   70262 }
   70263 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   70264 
   70265 /* Opcode: IfPos P1 P2 * * *
   70266 **
   70267 ** If the value of register P1 is 1 or greater, jump to P2.
   70268 **
   70269 ** It is illegal to use this instruction on a register that does
   70270 ** not contain an integer.  An assertion fault will result if you try.
   70271 */
   70272 case OP_IfPos: {        /* jump, in1 */
   70273   pIn1 = &aMem[pOp->p1];
   70274   assert( pIn1->flags&MEM_Int );
   70275   if( pIn1->u.i>0 ){
   70276      pc = pOp->p2 - 1;
   70277   }
   70278   break;
   70279 }
   70280 
   70281 /* Opcode: IfNeg P1 P2 * * *
   70282 **
   70283 ** If the value of register P1 is less than zero, jump to P2.
   70284 **
   70285 ** It is illegal to use this instruction on a register that does
   70286 ** not contain an integer.  An assertion fault will result if you try.
   70287 */
   70288 case OP_IfNeg: {        /* jump, in1 */
   70289   pIn1 = &aMem[pOp->p1];
   70290   assert( pIn1->flags&MEM_Int );
   70291   if( pIn1->u.i<0 ){
   70292      pc = pOp->p2 - 1;
   70293   }
   70294   break;
   70295 }
   70296 
   70297 /* Opcode: IfZero P1 P2 P3 * *
   70298 **
   70299 ** The register P1 must contain an integer.  Add literal P3 to the
   70300 ** value in register P1.  If the result is exactly 0, jump to P2.
   70301 **
   70302 ** It is illegal to use this instruction on a register that does
   70303 ** not contain an integer.  An assertion fault will result if you try.
   70304 */
   70305 case OP_IfZero: {        /* jump, in1 */
   70306   pIn1 = &aMem[pOp->p1];
   70307   assert( pIn1->flags&MEM_Int );
   70308   pIn1->u.i += pOp->p3;
   70309   if( pIn1->u.i==0 ){
   70310      pc = pOp->p2 - 1;
   70311   }
   70312   break;
   70313 }
   70314 
   70315 /* Opcode: AggStep * P2 P3 P4 P5
   70316 **
   70317 ** Execute the step function for an aggregate.  The
   70318 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   70319 ** structure that specifies the function.  Use register
   70320 ** P3 as the accumulator.
   70321 **
   70322 ** The P5 arguments are taken from register P2 and its
   70323 ** successors.
   70324 */
   70325 case OP_AggStep: {
   70326 #if 0  /* local variables moved into u.cf */
   70327   int n;
   70328   int i;
   70329   Mem *pMem;
   70330   Mem *pRec;
   70331   sqlite3_context ctx;
   70332   sqlite3_value **apVal;
   70333 #endif /* local variables moved into u.cf */
   70334 
   70335   u.cf.n = pOp->p5;
   70336   assert( u.cf.n>=0 );
   70337   u.cf.pRec = &aMem[pOp->p2];
   70338   u.cf.apVal = p->apArg;
   70339   assert( u.cf.apVal || u.cf.n==0 );
   70340   for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
   70341     assert( memIsValid(u.cf.pRec) );
   70342     u.cf.apVal[u.cf.i] = u.cf.pRec;
   70343     memAboutToChange(p, u.cf.pRec);
   70344     sqlite3VdbeMemStoreType(u.cf.pRec);
   70345   }
   70346   u.cf.ctx.pFunc = pOp->p4.pFunc;
   70347   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   70348   u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
   70349   u.cf.pMem->n++;
   70350   u.cf.ctx.s.flags = MEM_Null;
   70351   u.cf.ctx.s.z = 0;
   70352   u.cf.ctx.s.zMalloc = 0;
   70353   u.cf.ctx.s.xDel = 0;
   70354   u.cf.ctx.s.db = db;
   70355   u.cf.ctx.isError = 0;
   70356   u.cf.ctx.pColl = 0;
   70357   u.cf.ctx.skipFlag = 0;
   70358   if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   70359     assert( pOp>p->aOp );
   70360     assert( pOp[-1].p4type==P4_COLLSEQ );
   70361     assert( pOp[-1].opcode==OP_CollSeq );
   70362     u.cf.ctx.pColl = pOp[-1].p4.pColl;
   70363   }
   70364   (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
   70365   if( u.cf.ctx.isError ){
   70366     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
   70367     rc = u.cf.ctx.isError;
   70368   }
   70369   if( u.cf.ctx.skipFlag ){
   70370     assert( pOp[-1].opcode==OP_CollSeq );
   70371     u.cf.i = pOp[-1].p1;
   70372     if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
   70373   }
   70374 
   70375   sqlite3VdbeMemRelease(&u.cf.ctx.s);
   70376 
   70377   break;
   70378 }
   70379 
   70380 /* Opcode: AggFinal P1 P2 * P4 *
   70381 **
   70382 ** Execute the finalizer function for an aggregate.  P1 is
   70383 ** the memory location that is the accumulator for the aggregate.
   70384 **
   70385 ** P2 is the number of arguments that the step function takes and
   70386 ** P4 is a pointer to the FuncDef for this function.  The P2
   70387 ** argument is not used by this opcode.  It is only there to disambiguate
   70388 ** functions that can take varying numbers of arguments.  The
   70389 ** P4 argument is only needed for the degenerate case where
   70390 ** the step function was not previously called.
   70391 */
   70392 case OP_AggFinal: {
   70393 #if 0  /* local variables moved into u.cg */
   70394   Mem *pMem;
   70395 #endif /* local variables moved into u.cg */
   70396   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   70397   u.cg.pMem = &aMem[pOp->p1];
   70398   assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   70399   rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
   70400   if( rc ){
   70401     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
   70402   }
   70403   sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
   70404   UPDATE_MAX_BLOBSIZE(u.cg.pMem);
   70405   if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
   70406     goto too_big;
   70407   }
   70408   break;
   70409 }
   70410 
   70411 #ifndef SQLITE_OMIT_WAL
   70412 /* Opcode: Checkpoint P1 P2 P3 * *
   70413 **
   70414 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   70415 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
   70416 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
   70417 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
   70418 ** WAL after the checkpoint into mem[P3+1] and the number of pages
   70419 ** in the WAL that have been checkpointed after the checkpoint
   70420 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
   70421 ** mem[P3+2] are initialized to -1.
   70422 */
   70423 case OP_Checkpoint: {
   70424 #if 0  /* local variables moved into u.ch */
   70425   int i;                          /* Loop counter */
   70426   int aRes[3];                    /* Results */
   70427   Mem *pMem;                      /* Write results here */
   70428 #endif /* local variables moved into u.ch */
   70429 
   70430   u.ch.aRes[0] = 0;
   70431   u.ch.aRes[1] = u.ch.aRes[2] = -1;
   70432   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
   70433        || pOp->p2==SQLITE_CHECKPOINT_FULL
   70434        || pOp->p2==SQLITE_CHECKPOINT_RESTART
   70435   );
   70436   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
   70437   if( rc==SQLITE_BUSY ){
   70438     rc = SQLITE_OK;
   70439     u.ch.aRes[0] = 1;
   70440   }
   70441   for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
   70442     sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
   70443   }
   70444   break;
   70445 };
   70446 #endif
   70447 
   70448 #ifndef SQLITE_OMIT_PRAGMA
   70449 /* Opcode: JournalMode P1 P2 P3 * P5
   70450 **
   70451 ** Change the journal mode of database P1 to P3. P3 must be one of the
   70452 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   70453 ** modes (delete, truncate, persist, off and memory), this is a simple
   70454 ** operation. No IO is required.
   70455 **
   70456 ** If changing into or out of WAL mode the procedure is more complicated.
   70457 **
   70458 ** Write a string containing the final journal-mode to register P2.
   70459 */
   70460 case OP_JournalMode: {    /* out2-prerelease */
   70461 #if 0  /* local variables moved into u.ci */
   70462   Btree *pBt;                     /* Btree to change journal mode of */
   70463   Pager *pPager;                  /* Pager associated with pBt */
   70464   int eNew;                       /* New journal mode */
   70465   int eOld;                       /* The old journal mode */
   70466   const char *zFilename;          /* Name of database file for pPager */
   70467 #endif /* local variables moved into u.ci */
   70468 
   70469   u.ci.eNew = pOp->p3;
   70470   assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
   70471        || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
   70472        || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
   70473        || u.ci.eNew==PAGER_JOURNALMODE_OFF
   70474        || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
   70475        || u.ci.eNew==PAGER_JOURNALMODE_WAL
   70476        || u.ci.eNew==PAGER_JOURNALMODE_QUERY
   70477   );
   70478   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   70479 
   70480   u.ci.pBt = db->aDb[pOp->p1].pBt;
   70481   u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
   70482   u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
   70483   if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
   70484   if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
   70485 
   70486 #ifndef SQLITE_OMIT_WAL
   70487   u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager);
   70488 
   70489   /* Do not allow a transition to journal_mode=WAL for a database
   70490   ** in temporary storage or if the VFS does not support shared memory
   70491   */
   70492   if( u.ci.eNew==PAGER_JOURNALMODE_WAL
   70493    && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
   70494        || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
   70495   ){
   70496     u.ci.eNew = u.ci.eOld;
   70497   }
   70498 
   70499   if( (u.ci.eNew!=u.ci.eOld)
   70500    && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
   70501   ){
   70502     if( !db->autoCommit || db->activeVdbeCnt>1 ){
   70503       rc = SQLITE_ERROR;
   70504       sqlite3SetString(&p->zErrMsg, db,
   70505           "cannot change %s wal mode from within a transaction",
   70506           (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   70507       );
   70508       break;
   70509     }else{
   70510 
   70511       if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
   70512         /* If leaving WAL mode, close the log file. If successful, the call
   70513         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   70514         ** file. An EXCLUSIVE lock may still be held on the database file
   70515         ** after a successful return.
   70516         */
   70517         rc = sqlite3PagerCloseWal(u.ci.pPager);
   70518         if( rc==SQLITE_OK ){
   70519           sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
   70520         }
   70521       }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
   70522         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   70523         ** as an intermediate */
   70524         sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
   70525       }
   70526 
   70527       /* Open a transaction on the database file. Regardless of the journal
   70528       ** mode, this transaction always uses a rollback journal.
   70529       */
   70530       assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
   70531       if( rc==SQLITE_OK ){
   70532         rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   70533       }
   70534     }
   70535   }
   70536 #endif /* ifndef SQLITE_OMIT_WAL */
   70537 
   70538   if( rc ){
   70539     u.ci.eNew = u.ci.eOld;
   70540   }
   70541   u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
   70542 
   70543   pOut = &aMem[pOp->p2];
   70544   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   70545   pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
   70546   pOut->n = sqlite3Strlen30(pOut->z);
   70547   pOut->enc = SQLITE_UTF8;
   70548   sqlite3VdbeChangeEncoding(pOut, encoding);
   70549   break;
   70550 };
   70551 #endif /* SQLITE_OMIT_PRAGMA */
   70552 
   70553 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   70554 /* Opcode: Vacuum * * * * *
   70555 **
   70556 ** Vacuum the entire database.  This opcode will cause other virtual
   70557 ** machines to be created and run.  It may not be called from within
   70558 ** a transaction.
   70559 */
   70560 case OP_Vacuum: {
   70561   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   70562   break;
   70563 }
   70564 #endif
   70565 
   70566 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   70567 /* Opcode: IncrVacuum P1 P2 * * *
   70568 **
   70569 ** Perform a single step of the incremental vacuum procedure on
   70570 ** the P1 database. If the vacuum has finished, jump to instruction
   70571 ** P2. Otherwise, fall through to the next instruction.
   70572 */
   70573 case OP_IncrVacuum: {        /* jump */
   70574 #if 0  /* local variables moved into u.cj */
   70575   Btree *pBt;
   70576 #endif /* local variables moved into u.cj */
   70577 
   70578   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   70579   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   70580   u.cj.pBt = db->aDb[pOp->p1].pBt;
   70581   rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
   70582   if( rc==SQLITE_DONE ){
   70583     pc = pOp->p2 - 1;
   70584     rc = SQLITE_OK;
   70585   }
   70586   break;
   70587 }
   70588 #endif
   70589 
   70590 /* Opcode: Expire P1 * * * *
   70591 **
   70592 ** Cause precompiled statements to become expired. An expired statement
   70593 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
   70594 ** (via sqlite3_step()).
   70595 **
   70596 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   70597 ** then only the currently executing statement is affected.
   70598 */
   70599 case OP_Expire: {
   70600   if( !pOp->p1 ){
   70601     sqlite3ExpirePreparedStatements(db);
   70602   }else{
   70603     p->expired = 1;
   70604   }
   70605   break;
   70606 }
   70607 
   70608 #ifndef SQLITE_OMIT_SHARED_CACHE
   70609 /* Opcode: TableLock P1 P2 P3 P4 *
   70610 **
   70611 ** Obtain a lock on a particular table. This instruction is only used when
   70612 ** the shared-cache feature is enabled.
   70613 **
   70614 ** P1 is the index of the database in sqlite3.aDb[] of the database
   70615 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   70616 ** a write lock if P3==1.
   70617 **
   70618 ** P2 contains the root-page of the table to lock.
   70619 **
   70620 ** P4 contains a pointer to the name of the table being locked. This is only
   70621 ** used to generate an error message if the lock cannot be obtained.
   70622 */
   70623 case OP_TableLock: {
   70624   u8 isWriteLock = (u8)pOp->p3;
   70625   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   70626     int p1 = pOp->p1;
   70627     assert( p1>=0 && p1<db->nDb );
   70628     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
   70629     assert( isWriteLock==0 || isWriteLock==1 );
   70630     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   70631     if( (rc&0xFF)==SQLITE_LOCKED ){
   70632       const char *z = pOp->p4.z;
   70633       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   70634     }
   70635   }
   70636   break;
   70637 }
   70638 #endif /* SQLITE_OMIT_SHARED_CACHE */
   70639 
   70640 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70641 /* Opcode: VBegin * * * P4 *
   70642 **
   70643 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   70644 ** xBegin method for that table.
   70645 **
   70646 ** Also, whether or not P4 is set, check that this is not being called from
   70647 ** within a callback to a virtual table xSync() method. If it is, the error
   70648 ** code will be set to SQLITE_LOCKED.
   70649 */
   70650 case OP_VBegin: {
   70651 #if 0  /* local variables moved into u.ck */
   70652   VTable *pVTab;
   70653 #endif /* local variables moved into u.ck */
   70654   u.ck.pVTab = pOp->p4.pVtab;
   70655   rc = sqlite3VtabBegin(db, u.ck.pVTab);
   70656   if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
   70657   break;
   70658 }
   70659 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70660 
   70661 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70662 /* Opcode: VCreate P1 * * P4 *
   70663 **
   70664 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   70665 ** for that table.
   70666 */
   70667 case OP_VCreate: {
   70668   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   70669   break;
   70670 }
   70671 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70672 
   70673 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70674 /* Opcode: VDestroy P1 * * P4 *
   70675 **
   70676 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   70677 ** of that table.
   70678 */
   70679 case OP_VDestroy: {
   70680   p->inVtabMethod = 2;
   70681   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   70682   p->inVtabMethod = 0;
   70683   break;
   70684 }
   70685 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70686 
   70687 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70688 /* Opcode: VOpen P1 * * P4 *
   70689 **
   70690 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70691 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   70692 ** table and stores that cursor in P1.
   70693 */
   70694 case OP_VOpen: {
   70695 #if 0  /* local variables moved into u.cl */
   70696   VdbeCursor *pCur;
   70697   sqlite3_vtab_cursor *pVtabCursor;
   70698   sqlite3_vtab *pVtab;
   70699   sqlite3_module *pModule;
   70700 #endif /* local variables moved into u.cl */
   70701 
   70702   u.cl.pCur = 0;
   70703   u.cl.pVtabCursor = 0;
   70704   u.cl.pVtab = pOp->p4.pVtab->pVtab;
   70705   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
   70706   assert(u.cl.pVtab && u.cl.pModule);
   70707   rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
   70708   importVtabErrMsg(p, u.cl.pVtab);
   70709   if( SQLITE_OK==rc ){
   70710     /* Initialize sqlite3_vtab_cursor base class */
   70711     u.cl.pVtabCursor->pVtab = u.cl.pVtab;
   70712 
   70713     /* Initialise vdbe cursor object */
   70714     u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   70715     if( u.cl.pCur ){
   70716       u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
   70717       u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
   70718     }else{
   70719       db->mallocFailed = 1;
   70720       u.cl.pModule->xClose(u.cl.pVtabCursor);
   70721     }
   70722   }
   70723   break;
   70724 }
   70725 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70726 
   70727 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70728 /* Opcode: VFilter P1 P2 P3 P4 *
   70729 **
   70730 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   70731 ** the filtered result set is empty.
   70732 **
   70733 ** P4 is either NULL or a string that was generated by the xBestIndex
   70734 ** method of the module.  The interpretation of the P4 string is left
   70735 ** to the module implementation.
   70736 **
   70737 ** This opcode invokes the xFilter method on the virtual table specified
   70738 ** by P1.  The integer query plan parameter to xFilter is stored in register
   70739 ** P3. Register P3+1 stores the argc parameter to be passed to the
   70740 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   70741 ** additional parameters which are passed to
   70742 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   70743 **
   70744 ** A jump is made to P2 if the result set after filtering would be empty.
   70745 */
   70746 case OP_VFilter: {   /* jump */
   70747 #if 0  /* local variables moved into u.cm */
   70748   int nArg;
   70749   int iQuery;
   70750   const sqlite3_module *pModule;
   70751   Mem *pQuery;
   70752   Mem *pArgc;
   70753   sqlite3_vtab_cursor *pVtabCursor;
   70754   sqlite3_vtab *pVtab;
   70755   VdbeCursor *pCur;
   70756   int res;
   70757   int i;
   70758   Mem **apArg;
   70759 #endif /* local variables moved into u.cm */
   70760 
   70761   u.cm.pQuery = &aMem[pOp->p3];
   70762   u.cm.pArgc = &u.cm.pQuery[1];
   70763   u.cm.pCur = p->apCsr[pOp->p1];
   70764   assert( memIsValid(u.cm.pQuery) );
   70765   REGISTER_TRACE(pOp->p3, u.cm.pQuery);
   70766   assert( u.cm.pCur->pVtabCursor );
   70767   u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
   70768   u.cm.pVtab = u.cm.pVtabCursor->pVtab;
   70769   u.cm.pModule = u.cm.pVtab->pModule;
   70770 
   70771   /* Grab the index number and argc parameters */
   70772   assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
   70773   u.cm.nArg = (int)u.cm.pArgc->u.i;
   70774   u.cm.iQuery = (int)u.cm.pQuery->u.i;
   70775 
   70776   /* Invoke the xFilter method */
   70777   {
   70778     u.cm.res = 0;
   70779     u.cm.apArg = p->apArg;
   70780     for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
   70781       u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
   70782       sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
   70783     }
   70784 
   70785     p->inVtabMethod = 1;
   70786     rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
   70787     p->inVtabMethod = 0;
   70788     importVtabErrMsg(p, u.cm.pVtab);
   70789     if( rc==SQLITE_OK ){
   70790       u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
   70791     }
   70792 
   70793     if( u.cm.res ){
   70794       pc = pOp->p2 - 1;
   70795     }
   70796   }
   70797   u.cm.pCur->nullRow = 0;
   70798 
   70799   break;
   70800 }
   70801 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70802 
   70803 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70804 /* Opcode: VColumn P1 P2 P3 * *
   70805 **
   70806 ** Store the value of the P2-th column of
   70807 ** the row of the virtual-table that the
   70808 ** P1 cursor is pointing to into register P3.
   70809 */
   70810 case OP_VColumn: {
   70811 #if 0  /* local variables moved into u.cn */
   70812   sqlite3_vtab *pVtab;
   70813   const sqlite3_module *pModule;
   70814   Mem *pDest;
   70815   sqlite3_context sContext;
   70816 #endif /* local variables moved into u.cn */
   70817 
   70818   VdbeCursor *pCur = p->apCsr[pOp->p1];
   70819   assert( pCur->pVtabCursor );
   70820   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   70821   u.cn.pDest = &aMem[pOp->p3];
   70822   memAboutToChange(p, u.cn.pDest);
   70823   if( pCur->nullRow ){
   70824     sqlite3VdbeMemSetNull(u.cn.pDest);
   70825     break;
   70826   }
   70827   u.cn.pVtab = pCur->pVtabCursor->pVtab;
   70828   u.cn.pModule = u.cn.pVtab->pModule;
   70829   assert( u.cn.pModule->xColumn );
   70830   memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
   70831 
   70832   /* The output cell may already have a buffer allocated. Move
   70833   ** the current contents to u.cn.sContext.s so in case the user-function
   70834   ** can use the already allocated buffer instead of allocating a
   70835   ** new one.
   70836   */
   70837   sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
   70838   MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
   70839 
   70840   rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
   70841   importVtabErrMsg(p, u.cn.pVtab);
   70842   if( u.cn.sContext.isError ){
   70843     rc = u.cn.sContext.isError;
   70844   }
   70845 
   70846   /* Copy the result of the function to the P3 register. We
   70847   ** do this regardless of whether or not an error occurred to ensure any
   70848   ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
   70849   */
   70850   sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
   70851   sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
   70852   REGISTER_TRACE(pOp->p3, u.cn.pDest);
   70853   UPDATE_MAX_BLOBSIZE(u.cn.pDest);
   70854 
   70855   if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
   70856     goto too_big;
   70857   }
   70858   break;
   70859 }
   70860 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70861 
   70862 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70863 /* Opcode: VNext P1 P2 * * *
   70864 **
   70865 ** Advance virtual table P1 to the next row in its result set and
   70866 ** jump to instruction P2.  Or, if the virtual table has reached
   70867 ** the end of its result set, then fall through to the next instruction.
   70868 */
   70869 case OP_VNext: {   /* jump */
   70870 #if 0  /* local variables moved into u.co */
   70871   sqlite3_vtab *pVtab;
   70872   const sqlite3_module *pModule;
   70873   int res;
   70874   VdbeCursor *pCur;
   70875 #endif /* local variables moved into u.co */
   70876 
   70877   u.co.res = 0;
   70878   u.co.pCur = p->apCsr[pOp->p1];
   70879   assert( u.co.pCur->pVtabCursor );
   70880   if( u.co.pCur->nullRow ){
   70881     break;
   70882   }
   70883   u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
   70884   u.co.pModule = u.co.pVtab->pModule;
   70885   assert( u.co.pModule->xNext );
   70886 
   70887   /* Invoke the xNext() method of the module. There is no way for the
   70888   ** underlying implementation to return an error if one occurs during
   70889   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   70890   ** data is available) and the error code returned when xColumn or
   70891   ** some other method is next invoked on the save virtual table cursor.
   70892   */
   70893   p->inVtabMethod = 1;
   70894   rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
   70895   p->inVtabMethod = 0;
   70896   importVtabErrMsg(p, u.co.pVtab);
   70897   if( rc==SQLITE_OK ){
   70898     u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
   70899   }
   70900 
   70901   if( !u.co.res ){
   70902     /* If there is data, jump to P2 */
   70903     pc = pOp->p2 - 1;
   70904   }
   70905   break;
   70906 }
   70907 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70908 
   70909 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70910 /* Opcode: VRename P1 * * P4 *
   70911 **
   70912 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70913 ** This opcode invokes the corresponding xRename method. The value
   70914 ** in register P1 is passed as the zName argument to the xRename method.
   70915 */
   70916 case OP_VRename: {
   70917 #if 0  /* local variables moved into u.cp */
   70918   sqlite3_vtab *pVtab;
   70919   Mem *pName;
   70920 #endif /* local variables moved into u.cp */
   70921 
   70922   u.cp.pVtab = pOp->p4.pVtab->pVtab;
   70923   u.cp.pName = &aMem[pOp->p1];
   70924   assert( u.cp.pVtab->pModule->xRename );
   70925   assert( memIsValid(u.cp.pName) );
   70926   REGISTER_TRACE(pOp->p1, u.cp.pName);
   70927   assert( u.cp.pName->flags & MEM_Str );
   70928   testcase( u.cp.pName->enc==SQLITE_UTF8 );
   70929   testcase( u.cp.pName->enc==SQLITE_UTF16BE );
   70930   testcase( u.cp.pName->enc==SQLITE_UTF16LE );
   70931   rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
   70932   if( rc==SQLITE_OK ){
   70933     rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
   70934     importVtabErrMsg(p, u.cp.pVtab);
   70935     p->expired = 0;
   70936   }
   70937   break;
   70938 }
   70939 #endif
   70940 
   70941 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70942 /* Opcode: VUpdate P1 P2 P3 P4 *
   70943 **
   70944 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70945 ** This opcode invokes the corresponding xUpdate method. P2 values
   70946 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   70947 ** invocation. The value in register (P3+P2-1) corresponds to the
   70948 ** p2th element of the argv array passed to xUpdate.
   70949 **
   70950 ** The xUpdate method will do a DELETE or an INSERT or both.
   70951 ** The argv[0] element (which corresponds to memory cell P3)
   70952 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   70953 ** deletion occurs.  The argv[1] element is the rowid of the new
   70954 ** row.  This can be NULL to have the virtual table select the new
   70955 ** rowid for itself.  The subsequent elements in the array are
   70956 ** the values of columns in the new row.
   70957 **
   70958 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   70959 ** a row to delete.
   70960 **
   70961 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   70962 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   70963 ** is set to the value of the rowid for the row just inserted.
   70964 */
   70965 case OP_VUpdate: {
   70966 #if 0  /* local variables moved into u.cq */
   70967   sqlite3_vtab *pVtab;
   70968   sqlite3_module *pModule;
   70969   int nArg;
   70970   int i;
   70971   sqlite_int64 rowid;
   70972   Mem **apArg;
   70973   Mem *pX;
   70974 #endif /* local variables moved into u.cq */
   70975 
   70976   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
   70977        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   70978   );
   70979   u.cq.pVtab = pOp->p4.pVtab->pVtab;
   70980   u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
   70981   u.cq.nArg = pOp->p2;
   70982   assert( pOp->p4type==P4_VTAB );
   70983   if( ALWAYS(u.cq.pModule->xUpdate) ){
   70984     u8 vtabOnConflict = db->vtabOnConflict;
   70985     u.cq.apArg = p->apArg;
   70986     u.cq.pX = &aMem[pOp->p3];
   70987     for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
   70988       assert( memIsValid(u.cq.pX) );
   70989       memAboutToChange(p, u.cq.pX);
   70990       sqlite3VdbeMemStoreType(u.cq.pX);
   70991       u.cq.apArg[u.cq.i] = u.cq.pX;
   70992       u.cq.pX++;
   70993     }
   70994     db->vtabOnConflict = pOp->p5;
   70995     rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
   70996     db->vtabOnConflict = vtabOnConflict;
   70997     importVtabErrMsg(p, u.cq.pVtab);
   70998     if( rc==SQLITE_OK && pOp->p1 ){
   70999       assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
   71000       db->lastRowid = lastRowid = u.cq.rowid;
   71001     }
   71002     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
   71003       if( pOp->p5==OE_Ignore ){
   71004         rc = SQLITE_OK;
   71005       }else{
   71006         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
   71007       }
   71008     }else{
   71009       p->nChange++;
   71010     }
   71011   }
   71012   break;
   71013 }
   71014 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   71015 
   71016 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   71017 /* Opcode: Pagecount P1 P2 * * *
   71018 **
   71019 ** Write the current number of pages in database P1 to memory cell P2.
   71020 */
   71021 case OP_Pagecount: {            /* out2-prerelease */
   71022   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   71023   break;
   71024 }
   71025 #endif
   71026 
   71027 
   71028 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   71029 /* Opcode: MaxPgcnt P1 P2 P3 * *
   71030 **
   71031 ** Try to set the maximum page count for database P1 to the value in P3.
   71032 ** Do not let the maximum page count fall below the current page count and
   71033 ** do not change the maximum page count value if P3==0.
   71034 **
   71035 ** Store the maximum page count after the change in register P2.
   71036 */
   71037 case OP_MaxPgcnt: {            /* out2-prerelease */
   71038   unsigned int newMax;
   71039   Btree *pBt;
   71040 
   71041   pBt = db->aDb[pOp->p1].pBt;
   71042   newMax = 0;
   71043   if( pOp->p3 ){
   71044     newMax = sqlite3BtreeLastPage(pBt);
   71045     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   71046   }
   71047   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   71048   break;
   71049 }
   71050 #endif
   71051 
   71052 
   71053 #ifndef SQLITE_OMIT_TRACE
   71054 /* Opcode: Trace * * * P4 *
   71055 **
   71056 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   71057 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   71058 */
   71059 case OP_Trace: {
   71060 #if 0  /* local variables moved into u.cr */
   71061   char *zTrace;
   71062   char *z;
   71063 #endif /* local variables moved into u.cr */
   71064 
   71065   if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
   71066     u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
   71067     db->xTrace(db->pTraceArg, u.cr.z);
   71068     sqlite3DbFree(db, u.cr.z);
   71069   }
   71070 #ifdef SQLITE_DEBUG
   71071   if( (db->flags & SQLITE_SqlTrace)!=0
   71072    && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   71073   ){
   71074     sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
   71075   }
   71076 #endif /* SQLITE_DEBUG */
   71077   break;
   71078 }
   71079 #endif
   71080 
   71081 
   71082 /* Opcode: Noop * * * * *
   71083 **
   71084 ** Do nothing.  This instruction is often useful as a jump
   71085 ** destination.
   71086 */
   71087 /*
   71088 ** The magic Explain opcode are only inserted when explain==2 (which
   71089 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   71090 ** This opcode records information from the optimizer.  It is the
   71091 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   71092 */
   71093 default: {          /* This is really OP_Noop and OP_Explain */
   71094   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   71095   break;
   71096 }
   71097 
   71098 /*****************************************************************************
   71099 ** The cases of the switch statement above this line should all be indented
   71100 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   71101 ** readability.  From this point on down, the normal indentation rules are
   71102 ** restored.
   71103 *****************************************************************************/
   71104     }
   71105 
   71106 #ifdef VDBE_PROFILE
   71107     {
   71108       u64 elapsed = sqlite3Hwtime() - start;
   71109       pOp->cycles += elapsed;
   71110       pOp->cnt++;
   71111 #if 0
   71112         fprintf(stdout, "%10llu ", elapsed);
   71113         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
   71114 #endif
   71115     }
   71116 #endif
   71117 
   71118     /* The following code adds nothing to the actual functionality
   71119     ** of the program.  It is only here for testing and debugging.
   71120     ** On the other hand, it does burn CPU cycles every time through
   71121     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   71122     */
   71123 #ifndef NDEBUG
   71124     assert( pc>=-1 && pc<p->nOp );
   71125 
   71126 #ifdef SQLITE_DEBUG
   71127     if( p->trace ){
   71128       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
   71129       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   71130         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
   71131       }
   71132       if( pOp->opflags & OPFLG_OUT3 ){
   71133         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
   71134       }
   71135     }
   71136 #endif  /* SQLITE_DEBUG */
   71137 #endif  /* NDEBUG */
   71138   }  /* The end of the for(;;) loop the loops through opcodes */
   71139 
   71140   /* If we reach this point, it means that execution is finished with
   71141   ** an error of some kind.
   71142   */
   71143 vdbe_error_halt:
   71144   assert( rc );
   71145   p->rc = rc;
   71146   testcase( sqlite3GlobalConfig.xLog!=0 );
   71147   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   71148                    pc, p->zSql, p->zErrMsg);
   71149   sqlite3VdbeHalt(p);
   71150   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   71151   rc = SQLITE_ERROR;
   71152   if( resetSchemaOnFault>0 ){
   71153     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
   71154   }
   71155 
   71156   /* This is the only way out of this procedure.  We have to
   71157   ** release the mutexes on btrees that were acquired at the
   71158   ** top. */
   71159 vdbe_return:
   71160   db->lastRowid = lastRowid;
   71161   sqlite3VdbeLeave(p);
   71162   return rc;
   71163 
   71164   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   71165   ** is encountered.
   71166   */
   71167 too_big:
   71168   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   71169   rc = SQLITE_TOOBIG;
   71170   goto vdbe_error_halt;
   71171 
   71172   /* Jump to here if a malloc() fails.
   71173   */
   71174 no_mem:
   71175   db->mallocFailed = 1;
   71176   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   71177   rc = SQLITE_NOMEM;
   71178   goto vdbe_error_halt;
   71179 
   71180   /* Jump to here for any other kind of fatal error.  The "rc" variable
   71181   ** should hold the error number.
   71182   */
   71183 abort_due_to_error:
   71184   assert( p->zErrMsg==0 );
   71185   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   71186   if( rc!=SQLITE_IOERR_NOMEM ){
   71187     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   71188   }
   71189   goto vdbe_error_halt;
   71190 
   71191   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   71192   ** flag.
   71193   */
   71194 abort_due_to_interrupt:
   71195   assert( db->u1.isInterrupted );
   71196   rc = SQLITE_INTERRUPT;
   71197   p->rc = rc;
   71198   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   71199   goto vdbe_error_halt;
   71200 }
   71201 
   71202 /************** End of vdbe.c ************************************************/
   71203 /************** Begin file vdbeblob.c ****************************************/
   71204 /*
   71205 ** 2007 May 1
   71206 **
   71207 ** The author disclaims copyright to this source code.  In place of
   71208 ** a legal notice, here is a blessing:
   71209 **
   71210 **    May you do good and not evil.
   71211 **    May you find forgiveness for yourself and forgive others.
   71212 **    May you share freely, never taking more than you give.
   71213 **
   71214 *************************************************************************
   71215 **
   71216 ** This file contains code used to implement incremental BLOB I/O.
   71217 */
   71218 
   71219 
   71220 #ifndef SQLITE_OMIT_INCRBLOB
   71221 
   71222 /*
   71223 ** Valid sqlite3_blob* handles point to Incrblob structures.
   71224 */
   71225 typedef struct Incrblob Incrblob;
   71226 struct Incrblob {
   71227   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   71228   int nByte;              /* Size of open blob, in bytes */
   71229   int iOffset;            /* Byte offset of blob in cursor data */
   71230   int iCol;               /* Table column this handle is open on */
   71231   BtCursor *pCsr;         /* Cursor pointing at blob row */
   71232   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   71233   sqlite3 *db;            /* The associated database */
   71234 };
   71235 
   71236 
   71237 /*
   71238 ** This function is used by both blob_open() and blob_reopen(). It seeks
   71239 ** the b-tree cursor associated with blob handle p to point to row iRow.
   71240 ** If successful, SQLITE_OK is returned and subsequent calls to
   71241 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   71242 **
   71243 ** If an error occurs, or if the specified row does not exist or does not
   71244 ** contain a value of type TEXT or BLOB in the column nominated when the
   71245 ** blob handle was opened, then an error code is returned and *pzErr may
   71246 ** be set to point to a buffer containing an error message. It is the
   71247 ** responsibility of the caller to free the error message buffer using
   71248 ** sqlite3DbFree().
   71249 **
   71250 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   71251 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   71252 ** immediately return SQLITE_ABORT.
   71253 */
   71254 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   71255   int rc;                         /* Error code */
   71256   char *zErr = 0;                 /* Error message */
   71257   Vdbe *v = (Vdbe *)p->pStmt;
   71258 
   71259   /* Set the value of the SQL statements only variable to integer iRow.
   71260   ** This is done directly instead of using sqlite3_bind_int64() to avoid
   71261   ** triggering asserts related to mutexes.
   71262   */
   71263   assert( v->aVar[0].flags&MEM_Int );
   71264   v->aVar[0].u.i = iRow;
   71265 
   71266   rc = sqlite3_step(p->pStmt);
   71267   if( rc==SQLITE_ROW ){
   71268     u32 type = v->apCsr[0]->aType[p->iCol];
   71269     if( type<12 ){
   71270       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   71271           type==0?"null": type==7?"real": "integer"
   71272       );
   71273       rc = SQLITE_ERROR;
   71274       sqlite3_finalize(p->pStmt);
   71275       p->pStmt = 0;
   71276     }else{
   71277       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
   71278       p->nByte = sqlite3VdbeSerialTypeLen(type);
   71279       p->pCsr =  v->apCsr[0]->pCursor;
   71280       sqlite3BtreeEnterCursor(p->pCsr);
   71281       sqlite3BtreeCacheOverflow(p->pCsr);
   71282       sqlite3BtreeLeaveCursor(p->pCsr);
   71283     }
   71284   }
   71285 
   71286   if( rc==SQLITE_ROW ){
   71287     rc = SQLITE_OK;
   71288   }else if( p->pStmt ){
   71289     rc = sqlite3_finalize(p->pStmt);
   71290     p->pStmt = 0;
   71291     if( rc==SQLITE_OK ){
   71292       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   71293       rc = SQLITE_ERROR;
   71294     }else{
   71295       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   71296     }
   71297   }
   71298 
   71299   assert( rc!=SQLITE_OK || zErr==0 );
   71300   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   71301 
   71302   *pzErr = zErr;
   71303   return rc;
   71304 }
   71305 
   71306 /*
   71307 ** Open a blob handle.
   71308 */
   71309 SQLITE_API int sqlite3_blob_open(
   71310   sqlite3* db,            /* The database connection */
   71311   const char *zDb,        /* The attached database containing the blob */
   71312   const char *zTable,     /* The table containing the blob */
   71313   const char *zColumn,    /* The column containing the blob */
   71314   sqlite_int64 iRow,      /* The row containing the glob */
   71315   int flags,              /* True -> read/write access, false -> read-only */
   71316   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   71317 ){
   71318   int nAttempt = 0;
   71319   int iCol;               /* Index of zColumn in row-record */
   71320 
   71321   /* This VDBE program seeks a btree cursor to the identified
   71322   ** db/table/row entry. The reason for using a vdbe program instead
   71323   ** of writing code to use the b-tree layer directly is that the
   71324   ** vdbe program will take advantage of the various transaction,
   71325   ** locking and error handling infrastructure built into the vdbe.
   71326   **
   71327   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   71328   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   71329   ** uses it to implement the blob_read(), blob_write() and
   71330   ** blob_bytes() functions.
   71331   **
   71332   ** The sqlite3_blob_close() function finalizes the vdbe program,
   71333   ** which closes the b-tree cursor and (possibly) commits the
   71334   ** transaction.
   71335   */
   71336   static const VdbeOpList openBlob[] = {
   71337     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
   71338     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
   71339     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
   71340 
   71341     /* One of the following two instructions is replaced by an OP_Noop. */
   71342     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
   71343     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
   71344 
   71345     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
   71346     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
   71347     {OP_Column, 0, 0, 1},          /* 7  */
   71348     {OP_ResultRow, 1, 0, 0},       /* 8  */
   71349     {OP_Goto, 0, 5, 0},            /* 9  */
   71350     {OP_Close, 0, 0, 0},           /* 10 */
   71351     {OP_Halt, 0, 0, 0},            /* 11 */
   71352   };
   71353 
   71354   int rc = SQLITE_OK;
   71355   char *zErr = 0;
   71356   Table *pTab;
   71357   Parse *pParse = 0;
   71358   Incrblob *pBlob = 0;
   71359 
   71360   flags = !!flags;                /* flags = (flags ? 1 : 0); */
   71361   *ppBlob = 0;
   71362 
   71363   sqlite3_mutex_enter(db->mutex);
   71364 
   71365   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   71366   if( !pBlob ) goto blob_open_out;
   71367   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   71368   if( !pParse ) goto blob_open_out;
   71369 
   71370   do {
   71371     memset(pParse, 0, sizeof(Parse));
   71372     pParse->db = db;
   71373     sqlite3DbFree(db, zErr);
   71374     zErr = 0;
   71375 
   71376     sqlite3BtreeEnterAll(db);
   71377     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   71378     if( pTab && IsVirtual(pTab) ){
   71379       pTab = 0;
   71380       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   71381     }
   71382 #ifndef SQLITE_OMIT_VIEW
   71383     if( pTab && pTab->pSelect ){
   71384       pTab = 0;
   71385       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   71386     }
   71387 #endif
   71388     if( !pTab ){
   71389       if( pParse->zErrMsg ){
   71390         sqlite3DbFree(db, zErr);
   71391         zErr = pParse->zErrMsg;
   71392         pParse->zErrMsg = 0;
   71393       }
   71394       rc = SQLITE_ERROR;
   71395       sqlite3BtreeLeaveAll(db);
   71396       goto blob_open_out;
   71397     }
   71398 
   71399     /* Now search pTab for the exact column. */
   71400     for(iCol=0; iCol<pTab->nCol; iCol++) {
   71401       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   71402         break;
   71403       }
   71404     }
   71405     if( iCol==pTab->nCol ){
   71406       sqlite3DbFree(db, zErr);
   71407       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   71408       rc = SQLITE_ERROR;
   71409       sqlite3BtreeLeaveAll(db);
   71410       goto blob_open_out;
   71411     }
   71412 
   71413     /* If the value is being opened for writing, check that the
   71414     ** column is not indexed, and that it is not part of a foreign key.
   71415     ** It is against the rules to open a column to which either of these
   71416     ** descriptions applies for writing.  */
   71417     if( flags ){
   71418       const char *zFault = 0;
   71419       Index *pIdx;
   71420 #ifndef SQLITE_OMIT_FOREIGN_KEY
   71421       if( db->flags&SQLITE_ForeignKeys ){
   71422         /* Check that the column is not part of an FK child key definition. It
   71423         ** is not necessary to check if it is part of a parent key, as parent
   71424         ** key columns must be indexed. The check below will pick up this
   71425         ** case.  */
   71426         FKey *pFKey;
   71427         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   71428           int j;
   71429           for(j=0; j<pFKey->nCol; j++){
   71430             if( pFKey->aCol[j].iFrom==iCol ){
   71431               zFault = "foreign key";
   71432             }
   71433           }
   71434         }
   71435       }
   71436 #endif
   71437       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   71438         int j;
   71439         for(j=0; j<pIdx->nColumn; j++){
   71440           if( pIdx->aiColumn[j]==iCol ){
   71441             zFault = "indexed";
   71442           }
   71443         }
   71444       }
   71445       if( zFault ){
   71446         sqlite3DbFree(db, zErr);
   71447         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   71448         rc = SQLITE_ERROR;
   71449         sqlite3BtreeLeaveAll(db);
   71450         goto blob_open_out;
   71451       }
   71452     }
   71453 
   71454     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
   71455     assert( pBlob->pStmt || db->mallocFailed );
   71456     if( pBlob->pStmt ){
   71457       Vdbe *v = (Vdbe *)pBlob->pStmt;
   71458       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   71459 
   71460       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
   71461 
   71462 
   71463       /* Configure the OP_Transaction */
   71464       sqlite3VdbeChangeP1(v, 0, iDb);
   71465       sqlite3VdbeChangeP2(v, 0, flags);
   71466 
   71467       /* Configure the OP_VerifyCookie */
   71468       sqlite3VdbeChangeP1(v, 1, iDb);
   71469       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
   71470       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
   71471 
   71472       /* Make sure a mutex is held on the table to be accessed */
   71473       sqlite3VdbeUsesBtree(v, iDb);
   71474 
   71475       /* Configure the OP_TableLock instruction */
   71476 #ifdef SQLITE_OMIT_SHARED_CACHE
   71477       sqlite3VdbeChangeToNoop(v, 2);
   71478 #else
   71479       sqlite3VdbeChangeP1(v, 2, iDb);
   71480       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
   71481       sqlite3VdbeChangeP3(v, 2, flags);
   71482       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
   71483 #endif
   71484 
   71485       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   71486       ** parameter of the other to pTab->tnum.  */
   71487       sqlite3VdbeChangeToNoop(v, 4 - flags);
   71488       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
   71489       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
   71490 
   71491       /* Configure the number of columns. Configure the cursor to
   71492       ** think that the table has one more column than it really
   71493       ** does. An OP_Column to retrieve this imaginary column will
   71494       ** always return an SQL NULL. This is useful because it means
   71495       ** we can invoke OP_Column to fill in the vdbe cursors type
   71496       ** and offset cache without causing any IO.
   71497       */
   71498       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   71499       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
   71500       if( !db->mallocFailed ){
   71501         pParse->nVar = 1;
   71502         pParse->nMem = 1;
   71503         pParse->nTab = 1;
   71504         sqlite3VdbeMakeReady(v, pParse);
   71505       }
   71506     }
   71507 
   71508     pBlob->flags = flags;
   71509     pBlob->iCol = iCol;
   71510     pBlob->db = db;
   71511     sqlite3BtreeLeaveAll(db);
   71512     if( db->mallocFailed ){
   71513       goto blob_open_out;
   71514     }
   71515     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
   71516     rc = blobSeekToRow(pBlob, iRow, &zErr);
   71517   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
   71518 
   71519 blob_open_out:
   71520   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   71521     *ppBlob = (sqlite3_blob *)pBlob;
   71522   }else{
   71523     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   71524     sqlite3DbFree(db, pBlob);
   71525   }
   71526   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   71527   sqlite3DbFree(db, zErr);
   71528   sqlite3StackFree(db, pParse);
   71529   rc = sqlite3ApiExit(db, rc);
   71530   sqlite3_mutex_leave(db->mutex);
   71531   return rc;
   71532 }
   71533 
   71534 /*
   71535 ** Close a blob handle that was previously created using
   71536 ** sqlite3_blob_open().
   71537 */
   71538 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   71539   Incrblob *p = (Incrblob *)pBlob;
   71540   int rc;
   71541   sqlite3 *db;
   71542 
   71543   if( p ){
   71544     db = p->db;
   71545     sqlite3_mutex_enter(db->mutex);
   71546     rc = sqlite3_finalize(p->pStmt);
   71547     sqlite3DbFree(db, p);
   71548     sqlite3_mutex_leave(db->mutex);
   71549   }else{
   71550     rc = SQLITE_OK;
   71551   }
   71552   return rc;
   71553 }
   71554 
   71555 /*
   71556 ** Perform a read or write operation on a blob
   71557 */
   71558 static int blobReadWrite(
   71559   sqlite3_blob *pBlob,
   71560   void *z,
   71561   int n,
   71562   int iOffset,
   71563   int (*xCall)(BtCursor*, u32, u32, void*)
   71564 ){
   71565   int rc;
   71566   Incrblob *p = (Incrblob *)pBlob;
   71567   Vdbe *v;
   71568   sqlite3 *db;
   71569 
   71570   if( p==0 ) return SQLITE_MISUSE_BKPT;
   71571   db = p->db;
   71572   sqlite3_mutex_enter(db->mutex);
   71573   v = (Vdbe*)p->pStmt;
   71574 
   71575   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   71576     /* Request is out of range. Return a transient error. */
   71577     rc = SQLITE_ERROR;
   71578     sqlite3Error(db, SQLITE_ERROR, 0);
   71579   }else if( v==0 ){
   71580     /* If there is no statement handle, then the blob-handle has
   71581     ** already been invalidated. Return SQLITE_ABORT in this case.
   71582     */
   71583     rc = SQLITE_ABORT;
   71584   }else{
   71585     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   71586     ** returned, clean-up the statement handle.
   71587     */
   71588     assert( db == v->db );
   71589     sqlite3BtreeEnterCursor(p->pCsr);
   71590     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   71591     sqlite3BtreeLeaveCursor(p->pCsr);
   71592     if( rc==SQLITE_ABORT ){
   71593       sqlite3VdbeFinalize(v);
   71594       p->pStmt = 0;
   71595     }else{
   71596       db->errCode = rc;
   71597       v->rc = rc;
   71598     }
   71599   }
   71600   rc = sqlite3ApiExit(db, rc);
   71601   sqlite3_mutex_leave(db->mutex);
   71602   return rc;
   71603 }
   71604 
   71605 /*
   71606 ** Read data from a blob handle.
   71607 */
   71608 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   71609   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   71610 }
   71611 
   71612 /*
   71613 ** Write data to a blob handle.
   71614 */
   71615 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   71616   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   71617 }
   71618 
   71619 /*
   71620 ** Query a blob handle for the size of the data.
   71621 **
   71622 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   71623 ** so no mutex is required for access.
   71624 */
   71625 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   71626   Incrblob *p = (Incrblob *)pBlob;
   71627   return (p && p->pStmt) ? p->nByte : 0;
   71628 }
   71629 
   71630 /*
   71631 ** Move an existing blob handle to point to a different row of the same
   71632 ** database table.
   71633 **
   71634 ** If an error occurs, or if the specified row does not exist or does not
   71635 ** contain a blob or text value, then an error code is returned and the
   71636 ** database handle error code and message set. If this happens, then all
   71637 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   71638 ** immediately return SQLITE_ABORT.
   71639 */
   71640 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   71641   int rc;
   71642   Incrblob *p = (Incrblob *)pBlob;
   71643   sqlite3 *db;
   71644 
   71645   if( p==0 ) return SQLITE_MISUSE_BKPT;
   71646   db = p->db;
   71647   sqlite3_mutex_enter(db->mutex);
   71648 
   71649   if( p->pStmt==0 ){
   71650     /* If there is no statement handle, then the blob-handle has
   71651     ** already been invalidated. Return SQLITE_ABORT in this case.
   71652     */
   71653     rc = SQLITE_ABORT;
   71654   }else{
   71655     char *zErr;
   71656     rc = blobSeekToRow(p, iRow, &zErr);
   71657     if( rc!=SQLITE_OK ){
   71658       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   71659       sqlite3DbFree(db, zErr);
   71660     }
   71661     assert( rc!=SQLITE_SCHEMA );
   71662   }
   71663 
   71664   rc = sqlite3ApiExit(db, rc);
   71665   assert( rc==SQLITE_OK || p->pStmt==0 );
   71666   sqlite3_mutex_leave(db->mutex);
   71667   return rc;
   71668 }
   71669 
   71670 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   71671 
   71672 /************** End of vdbeblob.c ********************************************/
   71673 /************** Begin file vdbesort.c ****************************************/
   71674 /*
   71675 ** 2011 July 9
   71676 **
   71677 ** The author disclaims copyright to this source code.  In place of
   71678 ** a legal notice, here is a blessing:
   71679 **
   71680 **    May you do good and not evil.
   71681 **    May you find forgiveness for yourself and forgive others.
   71682 **    May you share freely, never taking more than you give.
   71683 **
   71684 *************************************************************************
   71685 ** This file contains code for the VdbeSorter object, used in concert with
   71686 ** a VdbeCursor to sort large numbers of keys (as may be required, for
   71687 ** example, by CREATE INDEX statements on tables too large to fit in main
   71688 ** memory).
   71689 */
   71690 
   71691 
   71692 #ifndef SQLITE_OMIT_MERGE_SORT
   71693 
   71694 typedef struct VdbeSorterIter VdbeSorterIter;
   71695 typedef struct SorterRecord SorterRecord;
   71696 
   71697 /*
   71698 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
   71699 **
   71700 ** As keys are added to the sorter, they are written to disk in a series
   71701 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
   71702 ** the same as the cache-size allowed for temporary databases. In order
   71703 ** to allow the caller to extract keys from the sorter in sorted order,
   71704 ** all PMAs currently stored on disk must be merged together. This comment
   71705 ** describes the data structure used to do so. The structure supports
   71706 ** merging any number of arrays in a single pass with no redundant comparison
   71707 ** operations.
   71708 **
   71709 ** The aIter[] array contains an iterator for each of the PMAs being merged.
   71710 ** An aIter[] iterator either points to a valid key or else is at EOF. For
   71711 ** the purposes of the paragraphs below, we assume that the array is actually
   71712 ** N elements in size, where N is the smallest power of 2 greater to or equal
   71713 ** to the number of iterators being merged. The extra aIter[] elements are
   71714 ** treated as if they are empty (always at EOF).
   71715 **
   71716 ** The aTree[] array is also N elements in size. The value of N is stored in
   71717 ** the VdbeSorter.nTree variable.
   71718 **
   71719 ** The final (N/2) elements of aTree[] contain the results of comparing
   71720 ** pairs of iterator keys together. Element i contains the result of
   71721 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
   71722 ** aTree element is set to the index of it.
   71723 **
   71724 ** For the purposes of this comparison, EOF is considered greater than any
   71725 ** other key value. If the keys are equal (only possible with two EOF
   71726 ** values), it doesn't matter which index is stored.
   71727 **
   71728 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
   71729 ** above contains the index of the smallest of each block of 4 iterators.
   71730 ** And so on. So that aTree[1] contains the index of the iterator that
   71731 ** currently points to the smallest key value. aTree[0] is unused.
   71732 **
   71733 ** Example:
   71734 **
   71735 **     aIter[0] -> Banana
   71736 **     aIter[1] -> Feijoa
   71737 **     aIter[2] -> Elderberry
   71738 **     aIter[3] -> Currant
   71739 **     aIter[4] -> Grapefruit
   71740 **     aIter[5] -> Apple
   71741 **     aIter[6] -> Durian
   71742 **     aIter[7] -> EOF
   71743 **
   71744 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
   71745 **
   71746 ** The current element is "Apple" (the value of the key indicated by
   71747 ** iterator 5). When the Next() operation is invoked, iterator 5 will
   71748 ** be advanced to the next key in its segment. Say the next key is
   71749 ** "Eggplant":
   71750 **
   71751 **     aIter[5] -> Eggplant
   71752 **
   71753 ** The contents of aTree[] are updated first by comparing the new iterator
   71754 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
   71755 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
   71756 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
   71757 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
   71758 ** so the value written into element 1 of the array is 0. As follows:
   71759 **
   71760 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
   71761 **
   71762 ** In other words, each time we advance to the next sorter element, log2(N)
   71763 ** key comparison operations are required, where N is the number of segments
   71764 ** being merged (rounded up to the next power of 2).
   71765 */
   71766 struct VdbeSorter {
   71767   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
   71768   i64 iReadOff;                   /* Current read offset within file pTemp1 */
   71769   int nInMemory;                  /* Current size of pRecord list as PMA */
   71770   int nTree;                      /* Used size of aTree/aIter (power of 2) */
   71771   int nPMA;                       /* Number of PMAs stored in pTemp1 */
   71772   int mnPmaSize;                  /* Minimum PMA size, in bytes */
   71773   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
   71774   VdbeSorterIter *aIter;          /* Array of iterators to merge */
   71775   int *aTree;                     /* Current state of incremental merge */
   71776   sqlite3_file *pTemp1;           /* PMA file 1 */
   71777   SorterRecord *pRecord;          /* Head of in-memory record list */
   71778   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
   71779 };
   71780 
   71781 /*
   71782 ** The following type is an iterator for a PMA. It caches the current key in
   71783 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
   71784 */
   71785 struct VdbeSorterIter {
   71786   i64 iReadOff;                   /* Current read offset */
   71787   i64 iEof;                       /* 1 byte past EOF for this iterator */
   71788   int nAlloc;                     /* Bytes of space at aAlloc */
   71789   int nKey;                       /* Number of bytes in key */
   71790   sqlite3_file *pFile;            /* File iterator is reading from */
   71791   u8 *aAlloc;                     /* Allocated space */
   71792   u8 *aKey;                       /* Pointer to current key */
   71793 };
   71794 
   71795 /*
   71796 ** A structure to store a single record. All in-memory records are connected
   71797 ** together into a linked list headed at VdbeSorter.pRecord using the
   71798 ** SorterRecord.pNext pointer.
   71799 */
   71800 struct SorterRecord {
   71801   void *pVal;
   71802   int nVal;
   71803   SorterRecord *pNext;
   71804 };
   71805 
   71806 /* Minimum allowable value for the VdbeSorter.nWorking variable */
   71807 #define SORTER_MIN_WORKING 10
   71808 
   71809 /* Maximum number of segments to merge in a single pass. */
   71810 #define SORTER_MAX_MERGE_COUNT 16
   71811 
   71812 /*
   71813 ** Free all memory belonging to the VdbeSorterIter object passed as the second
   71814 ** argument. All structure fields are set to zero before returning.
   71815 */
   71816 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
   71817   sqlite3DbFree(db, pIter->aAlloc);
   71818   memset(pIter, 0, sizeof(VdbeSorterIter));
   71819 }
   71820 
   71821 /*
   71822 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
   71823 ** no error occurs, or an SQLite error code if one does.
   71824 */
   71825 static int vdbeSorterIterNext(
   71826   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
   71827   VdbeSorterIter *pIter           /* Iterator to advance */
   71828 ){
   71829   int rc;                         /* Return Code */
   71830   int nRead;                      /* Number of bytes read */
   71831   int nRec = 0;                   /* Size of record in bytes */
   71832   int iOff = 0;                   /* Size of serialized size varint in bytes */
   71833 
   71834   assert( pIter->iEof>=pIter->iReadOff );
   71835   if( pIter->iEof-pIter->iReadOff>5 ){
   71836     nRead = 5;
   71837   }else{
   71838     nRead = (int)(pIter->iEof - pIter->iReadOff);
   71839   }
   71840   if( nRead<=0 ){
   71841     /* This is an EOF condition */
   71842     vdbeSorterIterZero(db, pIter);
   71843     return SQLITE_OK;
   71844   }
   71845 
   71846   rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
   71847   if( rc==SQLITE_OK ){
   71848     iOff = getVarint32(pIter->aAlloc, nRec);
   71849     if( (iOff+nRec)>nRead ){
   71850       int nRead2;                   /* Number of extra bytes to read */
   71851       if( (iOff+nRec)>pIter->nAlloc ){
   71852         int nNew = pIter->nAlloc*2;
   71853         while( (iOff+nRec)>nNew ) nNew = nNew*2;
   71854         pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
   71855         if( !pIter->aAlloc ) return SQLITE_NOMEM;
   71856         pIter->nAlloc = nNew;
   71857       }
   71858 
   71859       nRead2 = iOff + nRec - nRead;
   71860       rc = sqlite3OsRead(
   71861           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
   71862       );
   71863     }
   71864   }
   71865 
   71866   assert( rc!=SQLITE_OK || nRec>0 );
   71867   pIter->iReadOff += iOff+nRec;
   71868   pIter->nKey = nRec;
   71869   pIter->aKey = &pIter->aAlloc[iOff];
   71870   return rc;
   71871 }
   71872 
   71873 /*
   71874 ** Write a single varint, value iVal, to file-descriptor pFile. Return
   71875 ** SQLITE_OK if successful, or an SQLite error code if some error occurs.
   71876 **
   71877 ** The value of *piOffset when this function is called is used as the byte
   71878 ** offset in file pFile to write to. Before returning, *piOffset is
   71879 ** incremented by the number of bytes written.
   71880 */
   71881 static int vdbeSorterWriteVarint(
   71882   sqlite3_file *pFile,            /* File to write to */
   71883   i64 iVal,                       /* Value to write as a varint */
   71884   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
   71885 ){
   71886   u8 aVarint[9];                  /* Buffer large enough for a varint */
   71887   int nVarint;                    /* Number of used bytes in varint */
   71888   int rc;                         /* Result of write() call */
   71889 
   71890   nVarint = sqlite3PutVarint(aVarint, iVal);
   71891   rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
   71892   *piOffset += nVarint;
   71893 
   71894   return rc;
   71895 }
   71896 
   71897 /*
   71898 ** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
   71899 ** successful, or an SQLite error code if some error occurs.
   71900 **
   71901 ** The value of *piOffset when this function is called is used as the
   71902 ** byte offset in file pFile from whence to read the varint. If successful
   71903 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
   71904 ** the first byte past the end of the varint before returning. *piVal is
   71905 ** set to the integer value read. If an error occurs, the final values of
   71906 ** both *piOffset and *piVal are undefined.
   71907 */
   71908 static int vdbeSorterReadVarint(
   71909   sqlite3_file *pFile,            /* File to read from */
   71910   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
   71911   i64 *piVal                      /* OUT: Value read from file */
   71912 ){
   71913   u8 aVarint[9];                  /* Buffer large enough for a varint */
   71914   i64 iOff = *piOffset;           /* Offset in file to read from */
   71915   int rc;                         /* Return code */
   71916 
   71917   rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
   71918   if( rc==SQLITE_OK ){
   71919     *piOffset += getVarint(aVarint, (u64 *)piVal);
   71920   }
   71921 
   71922   return rc;
   71923 }
   71924 
   71925 /*
   71926 ** Initialize iterator pIter to scan through the PMA stored in file pFile
   71927 ** starting at offset iStart and ending at offset iEof-1. This function
   71928 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
   71929 ** PMA is empty).
   71930 */
   71931 static int vdbeSorterIterInit(
   71932   sqlite3 *db,                    /* Database handle */
   71933   VdbeSorter *pSorter,            /* Sorter object */
   71934   i64 iStart,                     /* Start offset in pFile */
   71935   VdbeSorterIter *pIter,          /* Iterator to populate */
   71936   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
   71937 ){
   71938   int rc;
   71939 
   71940   assert( pSorter->iWriteOff>iStart );
   71941   assert( pIter->aAlloc==0 );
   71942   pIter->pFile = pSorter->pTemp1;
   71943   pIter->iReadOff = iStart;
   71944   pIter->nAlloc = 128;
   71945   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
   71946   if( !pIter->aAlloc ){
   71947     rc = SQLITE_NOMEM;
   71948   }else{
   71949     i64 nByte;                         /* Total size of PMA in bytes */
   71950     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
   71951     *pnByte += nByte;
   71952     pIter->iEof = pIter->iReadOff + nByte;
   71953   }
   71954   if( rc==SQLITE_OK ){
   71955     rc = vdbeSorterIterNext(db, pIter);
   71956   }
   71957   return rc;
   71958 }
   71959 
   71960 
   71961 /*
   71962 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
   71963 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
   71964 ** used by the comparison. If an error occurs, return an SQLite error code.
   71965 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
   71966 ** value, depending on whether key1 is smaller, equal to or larger than key2.
   71967 **
   71968 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
   71969 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
   71970 ** is true and key1 contains even a single NULL value, it is considered to
   71971 ** be less than key2. Even if key2 also contains NULL values.
   71972 **
   71973 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
   71974 ** has been allocated and contains an unpacked record that is used as key2.
   71975 */
   71976 static void vdbeSorterCompare(
   71977   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
   71978   int bOmitRowid,                 /* Ignore rowid field at end of keys */
   71979   void *pKey1, int nKey1,         /* Left side of comparison */
   71980   void *pKey2, int nKey2,         /* Right side of comparison */
   71981   int *pRes                       /* OUT: Result of comparison */
   71982 ){
   71983   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
   71984   VdbeSorter *pSorter = pCsr->pSorter;
   71985   UnpackedRecord *r2 = pSorter->pUnpacked;
   71986   int i;
   71987 
   71988   if( pKey2 ){
   71989     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
   71990   }
   71991 
   71992   if( bOmitRowid ){
   71993     r2->nField = pKeyInfo->nField;
   71994     assert( r2->nField>0 );
   71995     for(i=0; i<r2->nField; i++){
   71996       if( r2->aMem[i].flags & MEM_Null ){
   71997         *pRes = -1;
   71998         return;
   71999       }
   72000     }
   72001     r2->flags |= UNPACKED_PREFIX_MATCH;
   72002   }
   72003 
   72004   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
   72005 }
   72006 
   72007 /*
   72008 ** This function is called to compare two iterator keys when merging
   72009 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
   72010 ** value to recalculate.
   72011 */
   72012 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
   72013   VdbeSorter *pSorter = pCsr->pSorter;
   72014   int i1;
   72015   int i2;
   72016   int iRes;
   72017   VdbeSorterIter *p1;
   72018   VdbeSorterIter *p2;
   72019 
   72020   assert( iOut<pSorter->nTree && iOut>0 );
   72021 
   72022   if( iOut>=(pSorter->nTree/2) ){
   72023     i1 = (iOut - pSorter->nTree/2) * 2;
   72024     i2 = i1 + 1;
   72025   }else{
   72026     i1 = pSorter->aTree[iOut*2];
   72027     i2 = pSorter->aTree[iOut*2+1];
   72028   }
   72029 
   72030   p1 = &pSorter->aIter[i1];
   72031   p2 = &pSorter->aIter[i2];
   72032 
   72033   if( p1->pFile==0 ){
   72034     iRes = i2;
   72035   }else if( p2->pFile==0 ){
   72036     iRes = i1;
   72037   }else{
   72038     int res;
   72039     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
   72040     vdbeSorterCompare(
   72041         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
   72042     );
   72043     if( res<=0 ){
   72044       iRes = i1;
   72045     }else{
   72046       iRes = i2;
   72047     }
   72048   }
   72049 
   72050   pSorter->aTree[iOut] = iRes;
   72051   return SQLITE_OK;
   72052 }
   72053 
   72054 /*
   72055 ** Initialize the temporary index cursor just opened as a sorter cursor.
   72056 */
   72057 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
   72058   int pgsz;                       /* Page size of main database */
   72059   int mxCache;                    /* Cache size */
   72060   VdbeSorter *pSorter;            /* The new sorter */
   72061   char *d;                        /* Dummy */
   72062 
   72063   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
   72064   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
   72065   if( pSorter==0 ){
   72066     return SQLITE_NOMEM;
   72067   }
   72068 
   72069   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
   72070   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
   72071   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
   72072 
   72073   if( !sqlite3TempInMemory(db) ){
   72074     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   72075     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
   72076     mxCache = db->aDb[0].pSchema->cache_size;
   72077     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
   72078     pSorter->mxPmaSize = mxCache * pgsz;
   72079   }
   72080 
   72081   return SQLITE_OK;
   72082 }
   72083 
   72084 /*
   72085 ** Free the list of sorted records starting at pRecord.
   72086 */
   72087 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
   72088   SorterRecord *p;
   72089   SorterRecord *pNext;
   72090   for(p=pRecord; p; p=pNext){
   72091     pNext = p->pNext;
   72092     sqlite3DbFree(db, p);
   72093   }
   72094 }
   72095 
   72096 /*
   72097 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
   72098 */
   72099 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
   72100   VdbeSorter *pSorter = pCsr->pSorter;
   72101   if( pSorter ){
   72102     if( pSorter->aIter ){
   72103       int i;
   72104       for(i=0; i<pSorter->nTree; i++){
   72105         vdbeSorterIterZero(db, &pSorter->aIter[i]);
   72106       }
   72107       sqlite3DbFree(db, pSorter->aIter);
   72108     }
   72109     if( pSorter->pTemp1 ){
   72110       sqlite3OsCloseFree(pSorter->pTemp1);
   72111     }
   72112     vdbeSorterRecordFree(db, pSorter->pRecord);
   72113     sqlite3DbFree(db, pSorter->pUnpacked);
   72114     sqlite3DbFree(db, pSorter);
   72115     pCsr->pSorter = 0;
   72116   }
   72117 }
   72118 
   72119 /*
   72120 ** Allocate space for a file-handle and open a temporary file. If successful,
   72121 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
   72122 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
   72123 */
   72124 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
   72125   int dummy;
   72126   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
   72127       SQLITE_OPEN_TEMP_JOURNAL |
   72128       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
   72129       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
   72130   );
   72131 }
   72132 
   72133 /*
   72134 ** Merge the two sorted lists p1 and p2 into a single list.
   72135 ** Set *ppOut to the head of the new list.
   72136 */
   72137 static void vdbeSorterMerge(
   72138   VdbeCursor *pCsr,               /* For pKeyInfo */
   72139   SorterRecord *p1,               /* First list to merge */
   72140   SorterRecord *p2,               /* Second list to merge */
   72141   SorterRecord **ppOut            /* OUT: Head of merged list */
   72142 ){
   72143   SorterRecord *pFinal = 0;
   72144   SorterRecord **pp = &pFinal;
   72145   void *pVal2 = p2 ? p2->pVal : 0;
   72146 
   72147   while( p1 && p2 ){
   72148     int res;
   72149     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
   72150     if( res<=0 ){
   72151       *pp = p1;
   72152       pp = &p1->pNext;
   72153       p1 = p1->pNext;
   72154       pVal2 = 0;
   72155     }else{
   72156       *pp = p2;
   72157        pp = &p2->pNext;
   72158       p2 = p2->pNext;
   72159       if( p2==0 ) break;
   72160       pVal2 = p2->pVal;
   72161     }
   72162   }
   72163   *pp = p1 ? p1 : p2;
   72164   *ppOut = pFinal;
   72165 }
   72166 
   72167 /*
   72168 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
   72169 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
   72170 ** occurs.
   72171 */
   72172 static int vdbeSorterSort(VdbeCursor *pCsr){
   72173   int i;
   72174   SorterRecord **aSlot;
   72175   SorterRecord *p;
   72176   VdbeSorter *pSorter = pCsr->pSorter;
   72177 
   72178   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
   72179   if( !aSlot ){
   72180     return SQLITE_NOMEM;
   72181   }
   72182 
   72183   p = pSorter->pRecord;
   72184   while( p ){
   72185     SorterRecord *pNext = p->pNext;
   72186     p->pNext = 0;
   72187     for(i=0; aSlot[i]; i++){
   72188       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   72189       aSlot[i] = 0;
   72190     }
   72191     aSlot[i] = p;
   72192     p = pNext;
   72193   }
   72194 
   72195   p = 0;
   72196   for(i=0; i<64; i++){
   72197     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   72198   }
   72199   pSorter->pRecord = p;
   72200 
   72201   sqlite3_free(aSlot);
   72202   return SQLITE_OK;
   72203 }
   72204 
   72205 
   72206 /*
   72207 ** Write the current contents of the in-memory linked-list to a PMA. Return
   72208 ** SQLITE_OK if successful, or an SQLite error code otherwise.
   72209 **
   72210 ** The format of a PMA is:
   72211 **
   72212 **     * A varint. This varint contains the total number of bytes of content
   72213 **       in the PMA (not including the varint itself).
   72214 **
   72215 **     * One or more records packed end-to-end in order of ascending keys.
   72216 **       Each record consists of a varint followed by a blob of data (the
   72217 **       key). The varint is the number of bytes in the blob of data.
   72218 */
   72219 static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
   72220   int rc = SQLITE_OK;             /* Return code */
   72221   VdbeSorter *pSorter = pCsr->pSorter;
   72222 
   72223   if( pSorter->nInMemory==0 ){
   72224     assert( pSorter->pRecord==0 );
   72225     return rc;
   72226   }
   72227 
   72228   rc = vdbeSorterSort(pCsr);
   72229 
   72230   /* If the first temporary PMA file has not been opened, open it now. */
   72231   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
   72232     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
   72233     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
   72234     assert( pSorter->iWriteOff==0 );
   72235     assert( pSorter->nPMA==0 );
   72236   }
   72237 
   72238   if( rc==SQLITE_OK ){
   72239     i64 iOff = pSorter->iWriteOff;
   72240     SorterRecord *p;
   72241     SorterRecord *pNext = 0;
   72242     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
   72243 
   72244     pSorter->nPMA++;
   72245     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
   72246     for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
   72247       pNext = p->pNext;
   72248       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
   72249 
   72250       if( rc==SQLITE_OK ){
   72251         rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
   72252         iOff += p->nVal;
   72253       }
   72254 
   72255       sqlite3DbFree(db, p);
   72256     }
   72257 
   72258     /* This assert verifies that unless an error has occurred, the size of
   72259     ** the PMA on disk is the same as the expected size stored in
   72260     ** pSorter->nInMemory. */
   72261     assert( rc!=SQLITE_OK || pSorter->nInMemory==(
   72262           iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
   72263     ));
   72264 
   72265     pSorter->iWriteOff = iOff;
   72266     if( rc==SQLITE_OK ){
   72267       /* Terminate each file with 8 extra bytes so that from any offset
   72268       ** in the file we can always read 9 bytes without a SHORT_READ error */
   72269       rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
   72270     }
   72271     pSorter->pRecord = p;
   72272   }
   72273 
   72274   return rc;
   72275 }
   72276 
   72277 /*
   72278 ** Add a record to the sorter.
   72279 */
   72280 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   72281   sqlite3 *db,                    /* Database handle */
   72282   VdbeCursor *pCsr,               /* Sorter cursor */
   72283   Mem *pVal                       /* Memory cell containing record */
   72284 ){
   72285   VdbeSorter *pSorter = pCsr->pSorter;
   72286   int rc = SQLITE_OK;             /* Return Code */
   72287   SorterRecord *pNew;             /* New list element */
   72288 
   72289   assert( pSorter );
   72290   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
   72291 
   72292   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
   72293   if( pNew==0 ){
   72294     rc = SQLITE_NOMEM;
   72295   }else{
   72296     pNew->pVal = (void *)&pNew[1];
   72297     memcpy(pNew->pVal, pVal->z, pVal->n);
   72298     pNew->nVal = pVal->n;
   72299     pNew->pNext = pSorter->pRecord;
   72300     pSorter->pRecord = pNew;
   72301   }
   72302 
   72303   /* See if the contents of the sorter should now be written out. They
   72304   ** are written out when either of the following are true:
   72305   **
   72306   **   * The total memory allocated for the in-memory list is greater
   72307   **     than (page-size * cache-size), or
   72308   **
   72309   **   * The total memory allocated for the in-memory list is greater
   72310   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   72311   */
   72312   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
   72313         (pSorter->nInMemory>pSorter->mxPmaSize)
   72314      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
   72315   )){
   72316     rc = vdbeSorterListToPMA(db, pCsr);
   72317     pSorter->nInMemory = 0;
   72318   }
   72319 
   72320   return rc;
   72321 }
   72322 
   72323 /*
   72324 ** Helper function for sqlite3VdbeSorterRewind().
   72325 */
   72326 static int vdbeSorterInitMerge(
   72327   sqlite3 *db,                    /* Database handle */
   72328   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
   72329   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
   72330 ){
   72331   VdbeSorter *pSorter = pCsr->pSorter;
   72332   int rc = SQLITE_OK;             /* Return code */
   72333   int i;                          /* Used to iterator through aIter[] */
   72334   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
   72335 
   72336   /* Initialize the iterators. */
   72337   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
   72338     VdbeSorterIter *pIter = &pSorter->aIter[i];
   72339     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
   72340     pSorter->iReadOff = pIter->iEof;
   72341     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
   72342     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
   72343   }
   72344 
   72345   /* Initialize the aTree[] array. */
   72346   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
   72347     rc = vdbeSorterDoCompare(pCsr, i);
   72348   }
   72349 
   72350   *pnByte = nByte;
   72351   return rc;
   72352 }
   72353 
   72354 /*
   72355 ** Once the sorter has been populated, this function is called to prepare
   72356 ** for iterating through its contents in sorted order.
   72357 */
   72358 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
   72359   VdbeSorter *pSorter = pCsr->pSorter;
   72360   int rc;                         /* Return code */
   72361   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
   72362   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
   72363   int nIter;                      /* Number of iterators used */
   72364   int nByte;                      /* Bytes of space required for aIter/aTree */
   72365   int N = 2;                      /* Power of 2 >= nIter */
   72366 
   72367   assert( pSorter );
   72368 
   72369   /* If no data has been written to disk, then do not do so now. Instead,
   72370   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
   72371   ** from the in-memory list.  */
   72372   if( pSorter->nPMA==0 ){
   72373     *pbEof = !pSorter->pRecord;
   72374     assert( pSorter->aTree==0 );
   72375     return vdbeSorterSort(pCsr);
   72376   }
   72377 
   72378   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
   72379   rc = vdbeSorterListToPMA(db, pCsr);
   72380   if( rc!=SQLITE_OK ) return rc;
   72381 
   72382   /* Allocate space for aIter[] and aTree[]. */
   72383   nIter = pSorter->nPMA;
   72384   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
   72385   assert( nIter>0 );
   72386   while( N<nIter ) N += N;
   72387   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
   72388   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
   72389   if( !pSorter->aIter ) return SQLITE_NOMEM;
   72390   pSorter->aTree = (int *)&pSorter->aIter[N];
   72391   pSorter->nTree = N;
   72392 
   72393   do {
   72394     int iNew;                     /* Index of new, merged, PMA */
   72395 
   72396     for(iNew=0;
   72397         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
   72398         iNew++
   72399     ){
   72400       i64 nWrite;                 /* Number of bytes in new PMA */
   72401 
   72402       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
   72403       ** initialize an iterator for each of them and break out of the loop.
   72404       ** These iterators will be incrementally merged as the VDBE layer calls
   72405       ** sqlite3VdbeSorterNext().
   72406       **
   72407       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
   72408       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
   72409       ** are merged into a single PMA that is written to file pTemp2.
   72410       */
   72411       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
   72412       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
   72413       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   72414         break;
   72415       }
   72416 
   72417       /* Open the second temp file, if it is not already open. */
   72418       if( pTemp2==0 ){
   72419         assert( iWrite2==0 );
   72420         rc = vdbeSorterOpenTempFile(db, &pTemp2);
   72421       }
   72422 
   72423       if( rc==SQLITE_OK ){
   72424         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
   72425       }
   72426 
   72427       if( rc==SQLITE_OK ){
   72428         int bEof = 0;
   72429         while( rc==SQLITE_OK && bEof==0 ){
   72430           int nToWrite;
   72431           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   72432           assert( pIter->pFile );
   72433           nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
   72434           rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
   72435           iWrite2 += nToWrite;
   72436           if( rc==SQLITE_OK ){
   72437             rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
   72438           }
   72439         }
   72440       }
   72441     }
   72442 
   72443     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   72444       break;
   72445     }else{
   72446       sqlite3_file *pTmp = pSorter->pTemp1;
   72447       pSorter->nPMA = iNew;
   72448       pSorter->pTemp1 = pTemp2;
   72449       pTemp2 = pTmp;
   72450       pSorter->iWriteOff = iWrite2;
   72451       pSorter->iReadOff = 0;
   72452       iWrite2 = 0;
   72453     }
   72454   }while( rc==SQLITE_OK );
   72455 
   72456   if( pTemp2 ){
   72457     sqlite3OsCloseFree(pTemp2);
   72458   }
   72459   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   72460   return rc;
   72461 }
   72462 
   72463 /*
   72464 ** Advance to the next element in the sorter.
   72465 */
   72466 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
   72467   VdbeSorter *pSorter = pCsr->pSorter;
   72468   int rc;                         /* Return code */
   72469 
   72470   if( pSorter->aTree ){
   72471     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
   72472     int i;                        /* Index of aTree[] to recalculate */
   72473 
   72474     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
   72475     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
   72476       rc = vdbeSorterDoCompare(pCsr, i);
   72477     }
   72478 
   72479     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   72480   }else{
   72481     SorterRecord *pFree = pSorter->pRecord;
   72482     pSorter->pRecord = pFree->pNext;
   72483     pFree->pNext = 0;
   72484     vdbeSorterRecordFree(db, pFree);
   72485     *pbEof = !pSorter->pRecord;
   72486     rc = SQLITE_OK;
   72487   }
   72488   return rc;
   72489 }
   72490 
   72491 /*
   72492 ** Return a pointer to a buffer owned by the sorter that contains the
   72493 ** current key.
   72494 */
   72495 static void *vdbeSorterRowkey(
   72496   VdbeSorter *pSorter,            /* Sorter object */
   72497   int *pnKey                      /* OUT: Size of current key in bytes */
   72498 ){
   72499   void *pKey;
   72500   if( pSorter->aTree ){
   72501     VdbeSorterIter *pIter;
   72502     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   72503     *pnKey = pIter->nKey;
   72504     pKey = pIter->aKey;
   72505   }else{
   72506     *pnKey = pSorter->pRecord->nVal;
   72507     pKey = pSorter->pRecord->pVal;
   72508   }
   72509   return pKey;
   72510 }
   72511 
   72512 /*
   72513 ** Copy the current sorter key into the memory cell pOut.
   72514 */
   72515 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
   72516   VdbeSorter *pSorter = pCsr->pSorter;
   72517   void *pKey; int nKey;           /* Sorter key to copy into pOut */
   72518 
   72519   pKey = vdbeSorterRowkey(pSorter, &nKey);
   72520   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
   72521     return SQLITE_NOMEM;
   72522   }
   72523   pOut->n = nKey;
   72524   MemSetTypeFlag(pOut, MEM_Blob);
   72525   memcpy(pOut->z, pKey, nKey);
   72526 
   72527   return SQLITE_OK;
   72528 }
   72529 
   72530 /*
   72531 ** Compare the key in memory cell pVal with the key that the sorter cursor
   72532 ** passed as the first argument currently points to. For the purposes of
   72533 ** the comparison, ignore the rowid field at the end of each record.
   72534 **
   72535 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
   72536 ** Otherwise, set *pRes to a negative, zero or positive value if the
   72537 ** key in pVal is smaller than, equal to or larger than the current sorter
   72538 ** key.
   72539 */
   72540 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
   72541   VdbeCursor *pCsr,               /* Sorter cursor */
   72542   Mem *pVal,                      /* Value to compare to current sorter key */
   72543   int *pRes                       /* OUT: Result of comparison */
   72544 ){
   72545   VdbeSorter *pSorter = pCsr->pSorter;
   72546   void *pKey; int nKey;           /* Sorter key to compare pVal with */
   72547 
   72548   pKey = vdbeSorterRowkey(pSorter, &nKey);
   72549   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
   72550   return SQLITE_OK;
   72551 }
   72552 
   72553 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
   72554 
   72555 /************** End of vdbesort.c ********************************************/
   72556 /************** Begin file journal.c *****************************************/
   72557 /*
   72558 ** 2007 August 22
   72559 **
   72560 ** The author disclaims copyright to this source code.  In place of
   72561 ** a legal notice, here is a blessing:
   72562 **
   72563 **    May you do good and not evil.
   72564 **    May you find forgiveness for yourself and forgive others.
   72565 **    May you share freely, never taking more than you give.
   72566 **
   72567 *************************************************************************
   72568 **
   72569 ** This file implements a special kind of sqlite3_file object used
   72570 ** by SQLite to create journal files if the atomic-write optimization
   72571 ** is enabled.
   72572 **
   72573 ** The distinctive characteristic of this sqlite3_file is that the
   72574 ** actual on disk file is created lazily. When the file is created,
   72575 ** the caller specifies a buffer size for an in-memory buffer to
   72576 ** be used to service read() and write() requests. The actual file
   72577 ** on disk is not created or populated until either:
   72578 **
   72579 **   1) The in-memory representation grows too large for the allocated
   72580 **      buffer, or
   72581 **   2) The sqlite3JournalCreate() function is called.
   72582 */
   72583 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   72584 
   72585 
   72586 /*
   72587 ** A JournalFile object is a subclass of sqlite3_file used by
   72588 ** as an open file handle for journal files.
   72589 */
   72590 struct JournalFile {
   72591   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   72592   int nBuf;                       /* Size of zBuf[] in bytes */
   72593   char *zBuf;                     /* Space to buffer journal writes */
   72594   int iSize;                      /* Amount of zBuf[] currently used */
   72595   int flags;                      /* xOpen flags */
   72596   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   72597   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   72598   const char *zJournal;           /* Name of the journal file */
   72599 };
   72600 typedef struct JournalFile JournalFile;
   72601 
   72602 /*
   72603 ** If it does not already exists, create and populate the on-disk file
   72604 ** for JournalFile p.
   72605 */
   72606 static int createFile(JournalFile *p){
   72607   int rc = SQLITE_OK;
   72608   if( !p->pReal ){
   72609     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   72610     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   72611     if( rc==SQLITE_OK ){
   72612       p->pReal = pReal;
   72613       if( p->iSize>0 ){
   72614         assert(p->iSize<=p->nBuf);
   72615         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   72616       }
   72617       if( rc!=SQLITE_OK ){
   72618         /* If an error occurred while writing to the file, close it before
   72619         ** returning. This way, SQLite uses the in-memory journal data to
   72620         ** roll back changes made to the internal page-cache before this
   72621         ** function was called.  */
   72622         sqlite3OsClose(pReal);
   72623         p->pReal = 0;
   72624       }
   72625     }
   72626   }
   72627   return rc;
   72628 }
   72629 
   72630 /*
   72631 ** Close the file.
   72632 */
   72633 static int jrnlClose(sqlite3_file *pJfd){
   72634   JournalFile *p = (JournalFile *)pJfd;
   72635   if( p->pReal ){
   72636     sqlite3OsClose(p->pReal);
   72637   }
   72638   sqlite3_free(p->zBuf);
   72639   return SQLITE_OK;
   72640 }
   72641 
   72642 /*
   72643 ** Read data from the file.
   72644 */
   72645 static int jrnlRead(
   72646   sqlite3_file *pJfd,    /* The journal file from which to read */
   72647   void *zBuf,            /* Put the results here */
   72648   int iAmt,              /* Number of bytes to read */
   72649   sqlite_int64 iOfst     /* Begin reading at this offset */
   72650 ){
   72651   int rc = SQLITE_OK;
   72652   JournalFile *p = (JournalFile *)pJfd;
   72653   if( p->pReal ){
   72654     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   72655   }else if( (iAmt+iOfst)>p->iSize ){
   72656     rc = SQLITE_IOERR_SHORT_READ;
   72657   }else{
   72658     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   72659   }
   72660   return rc;
   72661 }
   72662 
   72663 /*
   72664 ** Write data to the file.
   72665 */
   72666 static int jrnlWrite(
   72667   sqlite3_file *pJfd,    /* The journal file into which to write */
   72668   const void *zBuf,      /* Take data to be written from here */
   72669   int iAmt,              /* Number of bytes to write */
   72670   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   72671 ){
   72672   int rc = SQLITE_OK;
   72673   JournalFile *p = (JournalFile *)pJfd;
   72674   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   72675     rc = createFile(p);
   72676   }
   72677   if( rc==SQLITE_OK ){
   72678     if( p->pReal ){
   72679       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   72680     }else{
   72681       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   72682       if( p->iSize<(iOfst+iAmt) ){
   72683         p->iSize = (iOfst+iAmt);
   72684       }
   72685     }
   72686   }
   72687   return rc;
   72688 }
   72689 
   72690 /*
   72691 ** Truncate the file.
   72692 */
   72693 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   72694   int rc = SQLITE_OK;
   72695   JournalFile *p = (JournalFile *)pJfd;
   72696   if( p->pReal ){
   72697     rc = sqlite3OsTruncate(p->pReal, size);
   72698   }else if( size<p->iSize ){
   72699     p->iSize = size;
   72700   }
   72701   return rc;
   72702 }
   72703 
   72704 /*
   72705 ** Sync the file.
   72706 */
   72707 static int jrnlSync(sqlite3_file *pJfd, int flags){
   72708   int rc;
   72709   JournalFile *p = (JournalFile *)pJfd;
   72710   if( p->pReal ){
   72711     rc = sqlite3OsSync(p->pReal, flags);
   72712   }else{
   72713     rc = SQLITE_OK;
   72714   }
   72715   return rc;
   72716 }
   72717 
   72718 /*
   72719 ** Query the size of the file in bytes.
   72720 */
   72721 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   72722   int rc = SQLITE_OK;
   72723   JournalFile *p = (JournalFile *)pJfd;
   72724   if( p->pReal ){
   72725     rc = sqlite3OsFileSize(p->pReal, pSize);
   72726   }else{
   72727     *pSize = (sqlite_int64) p->iSize;
   72728   }
   72729   return rc;
   72730 }
   72731 
   72732 /*
   72733 ** Table of methods for JournalFile sqlite3_file object.
   72734 */
   72735 static struct sqlite3_io_methods JournalFileMethods = {
   72736   1,             /* iVersion */
   72737   jrnlClose,     /* xClose */
   72738   jrnlRead,      /* xRead */
   72739   jrnlWrite,     /* xWrite */
   72740   jrnlTruncate,  /* xTruncate */
   72741   jrnlSync,      /* xSync */
   72742   jrnlFileSize,  /* xFileSize */
   72743   0,             /* xLock */
   72744   0,             /* xUnlock */
   72745   0,             /* xCheckReservedLock */
   72746   0,             /* xFileControl */
   72747   0,             /* xSectorSize */
   72748   0,             /* xDeviceCharacteristics */
   72749   0,             /* xShmMap */
   72750   0,             /* xShmLock */
   72751   0,             /* xShmBarrier */
   72752   0              /* xShmUnmap */
   72753 };
   72754 
   72755 /*
   72756 ** Open a journal file.
   72757 */
   72758 SQLITE_PRIVATE int sqlite3JournalOpen(
   72759   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   72760   const char *zName,         /* Name of the journal file */
   72761   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   72762   int flags,                 /* Opening flags */
   72763   int nBuf                   /* Bytes buffered before opening the file */
   72764 ){
   72765   JournalFile *p = (JournalFile *)pJfd;
   72766   memset(p, 0, sqlite3JournalSize(pVfs));
   72767   if( nBuf>0 ){
   72768     p->zBuf = sqlite3MallocZero(nBuf);
   72769     if( !p->zBuf ){
   72770       return SQLITE_NOMEM;
   72771     }
   72772   }else{
   72773     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   72774   }
   72775   p->pMethod = &JournalFileMethods;
   72776   p->nBuf = nBuf;
   72777   p->flags = flags;
   72778   p->zJournal = zName;
   72779   p->pVfs = pVfs;
   72780   return SQLITE_OK;
   72781 }
   72782 
   72783 /*
   72784 ** If the argument p points to a JournalFile structure, and the underlying
   72785 ** file has not yet been created, create it now.
   72786 */
   72787 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   72788   if( p->pMethods!=&JournalFileMethods ){
   72789     return SQLITE_OK;
   72790   }
   72791   return createFile((JournalFile *)p);
   72792 }
   72793 
   72794 /*
   72795 ** Return the number of bytes required to store a JournalFile that uses vfs
   72796 ** pVfs to create the underlying on-disk files.
   72797 */
   72798 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   72799   return (pVfs->szOsFile+sizeof(JournalFile));
   72800 }
   72801 #endif
   72802 
   72803 /************** End of journal.c *********************************************/
   72804 /************** Begin file memjournal.c **************************************/
   72805 /*
   72806 ** 2008 October 7
   72807 **
   72808 ** The author disclaims copyright to this source code.  In place of
   72809 ** a legal notice, here is a blessing:
   72810 **
   72811 **    May you do good and not evil.
   72812 **    May you find forgiveness for yourself and forgive others.
   72813 **    May you share freely, never taking more than you give.
   72814 **
   72815 *************************************************************************
   72816 **
   72817 ** This file contains code use to implement an in-memory rollback journal.
   72818 ** The in-memory rollback journal is used to journal transactions for
   72819 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   72820 */
   72821 
   72822 /* Forward references to internal structures */
   72823 typedef struct MemJournal MemJournal;
   72824 typedef struct FilePoint FilePoint;
   72825 typedef struct FileChunk FileChunk;
   72826 
   72827 /* Space to hold the rollback journal is allocated in increments of
   72828 ** this many bytes.
   72829 **
   72830 ** The size chosen is a little less than a power of two.  That way,
   72831 ** the FileChunk object will have a size that almost exactly fills
   72832 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   72833 ** memory allocators.
   72834 */
   72835 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   72836 
   72837 /* Macro to find the minimum of two numeric values.
   72838 */
   72839 #ifndef MIN
   72840 # define MIN(x,y) ((x)<(y)?(x):(y))
   72841 #endif
   72842 
   72843 /*
   72844 ** The rollback journal is composed of a linked list of these structures.
   72845 */
   72846 struct FileChunk {
   72847   FileChunk *pNext;               /* Next chunk in the journal */
   72848   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   72849 };
   72850 
   72851 /*
   72852 ** An instance of this object serves as a cursor into the rollback journal.
   72853 ** The cursor can be either for reading or writing.
   72854 */
   72855 struct FilePoint {
   72856   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   72857   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   72858 };
   72859 
   72860 /*
   72861 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   72862 ** is an instance of this class.
   72863 */
   72864 struct MemJournal {
   72865   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   72866   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   72867   FilePoint endpoint;             /* Pointer to the end of the file */
   72868   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   72869 };
   72870 
   72871 /*
   72872 ** Read data from the in-memory journal file.  This is the implementation
   72873 ** of the sqlite3_vfs.xRead method.
   72874 */
   72875 static int memjrnlRead(
   72876   sqlite3_file *pJfd,    /* The journal file from which to read */
   72877   void *zBuf,            /* Put the results here */
   72878   int iAmt,              /* Number of bytes to read */
   72879   sqlite_int64 iOfst     /* Begin reading at this offset */
   72880 ){
   72881   MemJournal *p = (MemJournal *)pJfd;
   72882   u8 *zOut = zBuf;
   72883   int nRead = iAmt;
   72884   int iChunkOffset;
   72885   FileChunk *pChunk;
   72886 
   72887   /* SQLite never tries to read past the end of a rollback journal file */
   72888   assert( iOfst+iAmt<=p->endpoint.iOffset );
   72889 
   72890   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   72891     sqlite3_int64 iOff = 0;
   72892     for(pChunk=p->pFirst;
   72893         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   72894         pChunk=pChunk->pNext
   72895     ){
   72896       iOff += JOURNAL_CHUNKSIZE;
   72897     }
   72898   }else{
   72899     pChunk = p->readpoint.pChunk;
   72900   }
   72901 
   72902   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   72903   do {
   72904     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   72905     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   72906     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   72907     zOut += nCopy;
   72908     nRead -= iSpace;
   72909     iChunkOffset = 0;
   72910   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   72911   p->readpoint.iOffset = iOfst+iAmt;
   72912   p->readpoint.pChunk = pChunk;
   72913 
   72914   return SQLITE_OK;
   72915 }
   72916 
   72917 /*
   72918 ** Write data to the file.
   72919 */
   72920 static int memjrnlWrite(
   72921   sqlite3_file *pJfd,    /* The journal file into which to write */
   72922   const void *zBuf,      /* Take data to be written from here */
   72923   int iAmt,              /* Number of bytes to write */
   72924   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   72925 ){
   72926   MemJournal *p = (MemJournal *)pJfd;
   72927   int nWrite = iAmt;
   72928   u8 *zWrite = (u8 *)zBuf;
   72929 
   72930   /* An in-memory journal file should only ever be appended to. Random
   72931   ** access writes are not required by sqlite.
   72932   */
   72933   assert( iOfst==p->endpoint.iOffset );
   72934   UNUSED_PARAMETER(iOfst);
   72935 
   72936   while( nWrite>0 ){
   72937     FileChunk *pChunk = p->endpoint.pChunk;
   72938     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   72939     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   72940 
   72941     if( iChunkOffset==0 ){
   72942       /* New chunk is required to extend the file. */
   72943       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   72944       if( !pNew ){
   72945         return SQLITE_IOERR_NOMEM;
   72946       }
   72947       pNew->pNext = 0;
   72948       if( pChunk ){
   72949         assert( p->pFirst );
   72950         pChunk->pNext = pNew;
   72951       }else{
   72952         assert( !p->pFirst );
   72953         p->pFirst = pNew;
   72954       }
   72955       p->endpoint.pChunk = pNew;
   72956     }
   72957 
   72958     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   72959     zWrite += iSpace;
   72960     nWrite -= iSpace;
   72961     p->endpoint.iOffset += iSpace;
   72962   }
   72963 
   72964   return SQLITE_OK;
   72965 }
   72966 
   72967 /*
   72968 ** Truncate the file.
   72969 */
   72970 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   72971   MemJournal *p = (MemJournal *)pJfd;
   72972   FileChunk *pChunk;
   72973   assert(size==0);
   72974   UNUSED_PARAMETER(size);
   72975   pChunk = p->pFirst;
   72976   while( pChunk ){
   72977     FileChunk *pTmp = pChunk;
   72978     pChunk = pChunk->pNext;
   72979     sqlite3_free(pTmp);
   72980   }
   72981   sqlite3MemJournalOpen(pJfd);
   72982   return SQLITE_OK;
   72983 }
   72984 
   72985 /*
   72986 ** Close the file.
   72987 */
   72988 static int memjrnlClose(sqlite3_file *pJfd){
   72989   memjrnlTruncate(pJfd, 0);
   72990   return SQLITE_OK;
   72991 }
   72992 
   72993 
   72994 /*
   72995 ** Sync the file.
   72996 **
   72997 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   72998 ** is never called in a working implementation.  This implementation
   72999 ** exists purely as a contingency, in case some malfunction in some other
   73000 ** part of SQLite causes Sync to be called by mistake.
   73001 */
   73002 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
   73003   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   73004   return SQLITE_OK;
   73005 }
   73006 
   73007 /*
   73008 ** Query the size of the file in bytes.
   73009 */
   73010 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   73011   MemJournal *p = (MemJournal *)pJfd;
   73012   *pSize = (sqlite_int64) p->endpoint.iOffset;
   73013   return SQLITE_OK;
   73014 }
   73015 
   73016 /*
   73017 ** Table of methods for MemJournal sqlite3_file object.
   73018 */
   73019 static const struct sqlite3_io_methods MemJournalMethods = {
   73020   1,                /* iVersion */
   73021   memjrnlClose,     /* xClose */
   73022   memjrnlRead,      /* xRead */
   73023   memjrnlWrite,     /* xWrite */
   73024   memjrnlTruncate,  /* xTruncate */
   73025   memjrnlSync,      /* xSync */
   73026   memjrnlFileSize,  /* xFileSize */
   73027   0,                /* xLock */
   73028   0,                /* xUnlock */
   73029   0,                /* xCheckReservedLock */
   73030   0,                /* xFileControl */
   73031   0,                /* xSectorSize */
   73032   0,                /* xDeviceCharacteristics */
   73033   0,                /* xShmMap */
   73034   0,                /* xShmLock */
   73035   0,                /* xShmBarrier */
   73036   0                 /* xShmUnlock */
   73037 };
   73038 
   73039 /*
   73040 ** Open a journal file.
   73041 */
   73042 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   73043   MemJournal *p = (MemJournal *)pJfd;
   73044   assert( EIGHT_BYTE_ALIGNMENT(p) );
   73045   memset(p, 0, sqlite3MemJournalSize());
   73046   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
   73047 }
   73048 
   73049 /*
   73050 ** Return true if the file-handle passed as an argument is
   73051 ** an in-memory journal
   73052 */
   73053 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   73054   return pJfd->pMethods==&MemJournalMethods;
   73055 }
   73056 
   73057 /*
   73058 ** Return the number of bytes required to store a MemJournal file descriptor.
   73059 */
   73060 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   73061   return sizeof(MemJournal);
   73062 }
   73063 
   73064 /************** End of memjournal.c ******************************************/
   73065 /************** Begin file walker.c ******************************************/
   73066 /*
   73067 ** 2008 August 16
   73068 **
   73069 ** The author disclaims copyright to this source code.  In place of
   73070 ** a legal notice, here is a blessing:
   73071 **
   73072 **    May you do good and not evil.
   73073 **    May you find forgiveness for yourself and forgive others.
   73074 **    May you share freely, never taking more than you give.
   73075 **
   73076 *************************************************************************
   73077 ** This file contains routines used for walking the parser tree for
   73078 ** an SQL statement.
   73079 */
   73080 /* #include <stdlib.h> */
   73081 /* #include <string.h> */
   73082 
   73083 
   73084 /*
   73085 ** Walk an expression tree.  Invoke the callback once for each node
   73086 ** of the expression, while decending.  (In other words, the callback
   73087 ** is invoked before visiting children.)
   73088 **
   73089 ** The return value from the callback should be one of the WRC_*
   73090 ** constants to specify how to proceed with the walk.
   73091 **
   73092 **    WRC_Continue      Continue descending down the tree.
   73093 **
   73094 **    WRC_Prune         Do not descend into child nodes.  But allow
   73095 **                      the walk to continue with sibling nodes.
   73096 **
   73097 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   73098 **                      return the top-level walk call.
   73099 **
   73100 ** The return value from this routine is WRC_Abort to abandon the tree walk
   73101 ** and WRC_Continue to continue.
   73102 */
   73103 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   73104   int rc;
   73105   if( pExpr==0 ) return WRC_Continue;
   73106   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   73107   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   73108   rc = pWalker->xExprCallback(pWalker, pExpr);
   73109   if( rc==WRC_Continue
   73110               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
   73111     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   73112     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   73113     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   73114       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   73115     }else{
   73116       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   73117     }
   73118   }
   73119   return rc & WRC_Abort;
   73120 }
   73121 
   73122 /*
   73123 ** Call sqlite3WalkExpr() for every expression in list p or until
   73124 ** an abort request is seen.
   73125 */
   73126 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   73127   int i;
   73128   struct ExprList_item *pItem;
   73129   if( p ){
   73130     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   73131       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   73132     }
   73133   }
   73134   return WRC_Continue;
   73135 }
   73136 
   73137 /*
   73138 ** Walk all expressions associated with SELECT statement p.  Do
   73139 ** not invoke the SELECT callback on p, but do (of course) invoke
   73140 ** any expr callbacks and SELECT callbacks that come from subqueries.
   73141 ** Return WRC_Abort or WRC_Continue.
   73142 */
   73143 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   73144   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   73145   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   73146   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   73147   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   73148   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   73149   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   73150   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   73151   return WRC_Continue;
   73152 }
   73153 
   73154 /*
   73155 ** Walk the parse trees associated with all subqueries in the
   73156 ** FROM clause of SELECT statement p.  Do not invoke the select
   73157 ** callback on p, but do invoke it on each FROM clause subquery
   73158 ** and on any subqueries further down in the tree.  Return
   73159 ** WRC_Abort or WRC_Continue;
   73160 */
   73161 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   73162   SrcList *pSrc;
   73163   int i;
   73164   struct SrcList_item *pItem;
   73165 
   73166   pSrc = p->pSrc;
   73167   if( ALWAYS(pSrc) ){
   73168     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   73169       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   73170         return WRC_Abort;
   73171       }
   73172     }
   73173   }
   73174   return WRC_Continue;
   73175 }
   73176 
   73177 /*
   73178 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   73179 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   73180 ** on the compound select chain, p->pPrior.
   73181 **
   73182 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   73183 ** there is an abort request.
   73184 **
   73185 ** If the Walker does not have an xSelectCallback() then this routine
   73186 ** is a no-op returning WRC_Continue.
   73187 */
   73188 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   73189   int rc;
   73190   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
   73191   rc = WRC_Continue;
   73192   while( p  ){
   73193     rc = pWalker->xSelectCallback(pWalker, p);
   73194     if( rc ) break;
   73195     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
   73196     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
   73197     p = p->pPrior;
   73198   }
   73199   return rc & WRC_Abort;
   73200 }
   73201 
   73202 /************** End of walker.c **********************************************/
   73203 /************** Begin file resolve.c *****************************************/
   73204 /*
   73205 ** 2008 August 18
   73206 **
   73207 ** The author disclaims copyright to this source code.  In place of
   73208 ** a legal notice, here is a blessing:
   73209 **
   73210 **    May you do good and not evil.
   73211 **    May you find forgiveness for yourself and forgive others.
   73212 **    May you share freely, never taking more than you give.
   73213 **
   73214 *************************************************************************
   73215 **
   73216 ** This file contains routines used for walking the parser tree and
   73217 ** resolve all identifiers by associating them with a particular
   73218 ** table and column.
   73219 */
   73220 /* #include <stdlib.h> */
   73221 /* #include <string.h> */
   73222 
   73223 /*
   73224 ** Turn the pExpr expression into an alias for the iCol-th column of the
   73225 ** result set in pEList.
   73226 **
   73227 ** If the result set column is a simple column reference, then this routine
   73228 ** makes an exact copy.  But for any other kind of expression, this
   73229 ** routine make a copy of the result set column as the argument to the
   73230 ** TK_AS operator.  The TK_AS operator causes the expression to be
   73231 ** evaluated just once and then reused for each alias.
   73232 **
   73233 ** The reason for suppressing the TK_AS term when the expression is a simple
   73234 ** column reference is so that the column reference will be recognized as
   73235 ** usable by indices within the WHERE clause processing logic.
   73236 **
   73237 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
   73238 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   73239 **
   73240 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   73241 **
   73242 ** Is equivalent to:
   73243 **
   73244 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   73245 **
   73246 ** The result of random()%5 in the GROUP BY clause is probably different
   73247 ** from the result in the result-set.  We might fix this someday.  Or
   73248 ** then again, we might not...
   73249 */
   73250 static void resolveAlias(
   73251   Parse *pParse,         /* Parsing context */
   73252   ExprList *pEList,      /* A result set */
   73253   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   73254   Expr *pExpr,           /* Transform this into an alias to the result set */
   73255   const char *zType      /* "GROUP" or "ORDER" or "" */
   73256 ){
   73257   Expr *pOrig;           /* The iCol-th column of the result set */
   73258   Expr *pDup;            /* Copy of pOrig */
   73259   sqlite3 *db;           /* The database connection */
   73260 
   73261   assert( iCol>=0 && iCol<pEList->nExpr );
   73262   pOrig = pEList->a[iCol].pExpr;
   73263   assert( pOrig!=0 );
   73264   assert( pOrig->flags & EP_Resolved );
   73265   db = pParse->db;
   73266   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   73267     pDup = sqlite3ExprDup(db, pOrig, 0);
   73268     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   73269     if( pDup==0 ) return;
   73270     if( pEList->a[iCol].iAlias==0 ){
   73271       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
   73272     }
   73273     pDup->iTable = pEList->a[iCol].iAlias;
   73274   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
   73275     pDup = sqlite3ExprDup(db, pOrig, 0);
   73276     if( pDup==0 ) return;
   73277   }else{
   73278     char *zToken = pOrig->u.zToken;
   73279     assert( zToken!=0 );
   73280     pOrig->u.zToken = 0;
   73281     pDup = sqlite3ExprDup(db, pOrig, 0);
   73282     pOrig->u.zToken = zToken;
   73283     if( pDup==0 ) return;
   73284     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
   73285     pDup->flags2 |= EP2_MallocedToken;
   73286     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
   73287   }
   73288   if( pExpr->flags & EP_ExpCollate ){
   73289     pDup->pColl = pExpr->pColl;
   73290     pDup->flags |= EP_ExpCollate;
   73291   }
   73292 
   73293   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   73294   ** prevents ExprDelete() from deleting the Expr structure itself,
   73295   ** allowing it to be repopulated by the memcpy() on the following line.
   73296   */
   73297   ExprSetProperty(pExpr, EP_Static);
   73298   sqlite3ExprDelete(db, pExpr);
   73299   memcpy(pExpr, pDup, sizeof(*pExpr));
   73300   sqlite3DbFree(db, pDup);
   73301 }
   73302 
   73303 
   73304 /*
   73305 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
   73306 **
   73307 ** Return FALSE if the USING clause is NULL or if it does not contain
   73308 ** zCol.
   73309 */
   73310 static int nameInUsingClause(IdList *pUsing, const char *zCol){
   73311   if( pUsing ){
   73312     int k;
   73313     for(k=0; k<pUsing->nId; k++){
   73314       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
   73315     }
   73316   }
   73317   return 0;
   73318 }
   73319 
   73320 
   73321 /*
   73322 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   73323 ** that name in the set of source tables in pSrcList and make the pExpr
   73324 ** expression node refer back to that source column.  The following changes
   73325 ** are made to pExpr:
   73326 **
   73327 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   73328 **                         (even if X is implied).
   73329 **    pExpr->iTable        Set to the cursor number for the table obtained
   73330 **                         from pSrcList.
   73331 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   73332 **                         X and/or Y are implied.)
   73333 **    pExpr->iColumn       Set to the column number within the table.
   73334 **    pExpr->op            Set to TK_COLUMN.
   73335 **    pExpr->pLeft         Any expression this points to is deleted
   73336 **    pExpr->pRight        Any expression this points to is deleted.
   73337 **
   73338 ** The zDb variable is the name of the database (the "X").  This value may be
   73339 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   73340 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   73341 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   73342 ** means that the form of the name is Z and that columns from any table
   73343 ** can be used.
   73344 **
   73345 ** If the name cannot be resolved unambiguously, leave an error message
   73346 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   73347 */
   73348 static int lookupName(
   73349   Parse *pParse,       /* The parsing context */
   73350   const char *zDb,     /* Name of the database containing table, or NULL */
   73351   const char *zTab,    /* Name of table containing column, or NULL */
   73352   const char *zCol,    /* Name of the column. */
   73353   NameContext *pNC,    /* The name context used to resolve the name */
   73354   Expr *pExpr          /* Make this EXPR node point to the selected column */
   73355 ){
   73356   int i, j;            /* Loop counters */
   73357   int cnt = 0;                      /* Number of matching column names */
   73358   int cntTab = 0;                   /* Number of matching table names */
   73359   sqlite3 *db = pParse->db;         /* The database connection */
   73360   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   73361   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   73362   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   73363   Schema *pSchema = 0;              /* Schema of the expression */
   73364   int isTrigger = 0;
   73365 
   73366   assert( pNC );     /* the name context cannot be NULL. */
   73367   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   73368   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   73369 
   73370   /* Initialize the node to no-match */
   73371   pExpr->iTable = -1;
   73372   pExpr->pTab = 0;
   73373   ExprSetIrreducible(pExpr);
   73374 
   73375   /* Start at the inner-most context and move outward until a match is found */
   73376   while( pNC && cnt==0 ){
   73377     ExprList *pEList;
   73378     SrcList *pSrcList = pNC->pSrcList;
   73379 
   73380     if( pSrcList ){
   73381       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   73382         Table *pTab;
   73383         int iDb;
   73384         Column *pCol;
   73385 
   73386         pTab = pItem->pTab;
   73387         assert( pTab!=0 && pTab->zName!=0 );
   73388         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   73389         assert( pTab->nCol>0 );
   73390         if( zTab ){
   73391           if( pItem->zAlias ){
   73392             char *zTabName = pItem->zAlias;
   73393             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   73394           }else{
   73395             char *zTabName = pTab->zName;
   73396             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
   73397               continue;
   73398             }
   73399             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
   73400               continue;
   73401             }
   73402           }
   73403         }
   73404         if( 0==(cntTab++) ){
   73405           pExpr->iTable = pItem->iCursor;
   73406           pExpr->pTab = pTab;
   73407           pSchema = pTab->pSchema;
   73408           pMatch = pItem;
   73409         }
   73410         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   73411           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   73412             /* If there has been exactly one prior match and this match
   73413             ** is for the right-hand table of a NATURAL JOIN or is in a
   73414             ** USING clause, then skip this match.
   73415             */
   73416             if( cnt==1 ){
   73417               if( pItem->jointype & JT_NATURAL ) continue;
   73418               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
   73419             }
   73420             cnt++;
   73421             pExpr->iTable = pItem->iCursor;
   73422             pExpr->pTab = pTab;
   73423             pMatch = pItem;
   73424             pSchema = pTab->pSchema;
   73425             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   73426             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   73427             break;
   73428           }
   73429         }
   73430       }
   73431     }
   73432 
   73433 #ifndef SQLITE_OMIT_TRIGGER
   73434     /* If we have not already resolved the name, then maybe
   73435     ** it is a new.* or old.* trigger argument reference
   73436     */
   73437     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
   73438       int op = pParse->eTriggerOp;
   73439       Table *pTab = 0;
   73440       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   73441       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   73442         pExpr->iTable = 1;
   73443         pTab = pParse->pTriggerTab;
   73444       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   73445         pExpr->iTable = 0;
   73446         pTab = pParse->pTriggerTab;
   73447       }
   73448 
   73449       if( pTab ){
   73450         int iCol;
   73451         pSchema = pTab->pSchema;
   73452         cntTab++;
   73453         for(iCol=0; iCol<pTab->nCol; iCol++){
   73454           Column *pCol = &pTab->aCol[iCol];
   73455           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   73456             if( iCol==pTab->iPKey ){
   73457               iCol = -1;
   73458             }
   73459             break;
   73460           }
   73461         }
   73462         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
   73463           iCol = -1;        /* IMP: R-44911-55124 */
   73464         }
   73465         if( iCol<pTab->nCol ){
   73466           cnt++;
   73467           if( iCol<0 ){
   73468             pExpr->affinity = SQLITE_AFF_INTEGER;
   73469           }else if( pExpr->iTable==0 ){
   73470             testcase( iCol==31 );
   73471             testcase( iCol==32 );
   73472             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   73473           }else{
   73474             testcase( iCol==31 );
   73475             testcase( iCol==32 );
   73476             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   73477           }
   73478           pExpr->iColumn = (i16)iCol;
   73479           pExpr->pTab = pTab;
   73480           isTrigger = 1;
   73481         }
   73482       }
   73483     }
   73484 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   73485 
   73486     /*
   73487     ** Perhaps the name is a reference to the ROWID
   73488     */
   73489     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
   73490       cnt = 1;
   73491       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   73492       pExpr->affinity = SQLITE_AFF_INTEGER;
   73493     }
   73494 
   73495     /*
   73496     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   73497     ** might refer to an result-set alias.  This happens, for example, when
   73498     ** we are resolving names in the WHERE clause of the following command:
   73499     **
   73500     **     SELECT a+b AS x FROM table WHERE x<10;
   73501     **
   73502     ** In cases like this, replace pExpr with a copy of the expression that
   73503     ** forms the result set entry ("a+b" in the example) and return immediately.
   73504     ** Note that the expression in the result set should have already been
   73505     ** resolved by the time the WHERE clause is resolved.
   73506     */
   73507     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
   73508       for(j=0; j<pEList->nExpr; j++){
   73509         char *zAs = pEList->a[j].zName;
   73510         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   73511           Expr *pOrig;
   73512           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   73513           assert( pExpr->x.pList==0 );
   73514           assert( pExpr->x.pSelect==0 );
   73515           pOrig = pEList->a[j].pExpr;
   73516           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
   73517             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   73518             return WRC_Abort;
   73519           }
   73520           resolveAlias(pParse, pEList, j, pExpr, "");
   73521           cnt = 1;
   73522           pMatch = 0;
   73523           assert( zTab==0 && zDb==0 );
   73524           goto lookupname_end;
   73525         }
   73526       }
   73527     }
   73528 
   73529     /* Advance to the next name context.  The loop will exit when either
   73530     ** we have a match (cnt>0) or when we run out of name contexts.
   73531     */
   73532     if( cnt==0 ){
   73533       pNC = pNC->pNext;
   73534     }
   73535   }
   73536 
   73537   /*
   73538   ** If X and Y are NULL (in other words if only the column name Z is
   73539   ** supplied) and the value of Z is enclosed in double-quotes, then
   73540   ** Z is a string literal if it doesn't match any column names.  In that
   73541   ** case, we need to return right away and not make any changes to
   73542   ** pExpr.
   73543   **
   73544   ** Because no reference was made to outer contexts, the pNC->nRef
   73545   ** fields are not changed in any context.
   73546   */
   73547   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   73548     pExpr->op = TK_STRING;
   73549     pExpr->pTab = 0;
   73550     return WRC_Prune;
   73551   }
   73552 
   73553   /*
   73554   ** cnt==0 means there was not match.  cnt>1 means there were two or
   73555   ** more matches.  Either way, we have an error.
   73556   */
   73557   if( cnt!=1 ){
   73558     const char *zErr;
   73559     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   73560     if( zDb ){
   73561       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   73562     }else if( zTab ){
   73563       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   73564     }else{
   73565       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   73566     }
   73567     pParse->checkSchema = 1;
   73568     pTopNC->nErr++;
   73569   }
   73570 
   73571   /* If a column from a table in pSrcList is referenced, then record
   73572   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   73573   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   73574   ** column number is greater than the number of bits in the bitmask
   73575   ** then set the high-order bit of the bitmask.
   73576   */
   73577   if( pExpr->iColumn>=0 && pMatch!=0 ){
   73578     int n = pExpr->iColumn;
   73579     testcase( n==BMS-1 );
   73580     if( n>=BMS ){
   73581       n = BMS-1;
   73582     }
   73583     assert( pMatch->iCursor==pExpr->iTable );
   73584     pMatch->colUsed |= ((Bitmask)1)<<n;
   73585   }
   73586 
   73587   /* Clean up and return
   73588   */
   73589   sqlite3ExprDelete(db, pExpr->pLeft);
   73590   pExpr->pLeft = 0;
   73591   sqlite3ExprDelete(db, pExpr->pRight);
   73592   pExpr->pRight = 0;
   73593   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   73594 lookupname_end:
   73595   if( cnt==1 ){
   73596     assert( pNC!=0 );
   73597     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   73598     /* Increment the nRef value on all name contexts from TopNC up to
   73599     ** the point where the name matched. */
   73600     for(;;){
   73601       assert( pTopNC!=0 );
   73602       pTopNC->nRef++;
   73603       if( pTopNC==pNC ) break;
   73604       pTopNC = pTopNC->pNext;
   73605     }
   73606     return WRC_Prune;
   73607   } else {
   73608     return WRC_Abort;
   73609   }
   73610 }
   73611 
   73612 /*
   73613 ** Allocate and return a pointer to an expression to load the column iCol
   73614 ** from datasource iSrc in SrcList pSrc.
   73615 */
   73616 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   73617   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   73618   if( p ){
   73619     struct SrcList_item *pItem = &pSrc->a[iSrc];
   73620     p->pTab = pItem->pTab;
   73621     p->iTable = pItem->iCursor;
   73622     if( p->pTab->iPKey==iCol ){
   73623       p->iColumn = -1;
   73624     }else{
   73625       p->iColumn = (ynVar)iCol;
   73626       testcase( iCol==BMS );
   73627       testcase( iCol==BMS-1 );
   73628       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   73629     }
   73630     ExprSetProperty(p, EP_Resolved);
   73631   }
   73632   return p;
   73633 }
   73634 
   73635 /*
   73636 ** This routine is callback for sqlite3WalkExpr().
   73637 **
   73638 ** Resolve symbolic names into TK_COLUMN operators for the current
   73639 ** node in the expression tree.  Return 0 to continue the search down
   73640 ** the tree or 2 to abort the tree walk.
   73641 **
   73642 ** This routine also does error checking and name resolution for
   73643 ** function names.  The operator for aggregate functions is changed
   73644 ** to TK_AGG_FUNCTION.
   73645 */
   73646 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   73647   NameContext *pNC;
   73648   Parse *pParse;
   73649 
   73650   pNC = pWalker->u.pNC;
   73651   assert( pNC!=0 );
   73652   pParse = pNC->pParse;
   73653   assert( pParse==pWalker->pParse );
   73654 
   73655   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   73656   ExprSetProperty(pExpr, EP_Resolved);
   73657 #ifndef NDEBUG
   73658   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   73659     SrcList *pSrcList = pNC->pSrcList;
   73660     int i;
   73661     for(i=0; i<pNC->pSrcList->nSrc; i++){
   73662       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   73663     }
   73664   }
   73665 #endif
   73666   switch( pExpr->op ){
   73667 
   73668 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   73669     /* The special operator TK_ROW means use the rowid for the first
   73670     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   73671     ** clause processing on UPDATE and DELETE statements.
   73672     */
   73673     case TK_ROW: {
   73674       SrcList *pSrcList = pNC->pSrcList;
   73675       struct SrcList_item *pItem;
   73676       assert( pSrcList && pSrcList->nSrc==1 );
   73677       pItem = pSrcList->a;
   73678       pExpr->op = TK_COLUMN;
   73679       pExpr->pTab = pItem->pTab;
   73680       pExpr->iTable = pItem->iCursor;
   73681       pExpr->iColumn = -1;
   73682       pExpr->affinity = SQLITE_AFF_INTEGER;
   73683       break;
   73684     }
   73685 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   73686 
   73687     /* A lone identifier is the name of a column.
   73688     */
   73689     case TK_ID: {
   73690       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   73691     }
   73692 
   73693     /* A table name and column name:     ID.ID
   73694     ** Or a database, table and column:  ID.ID.ID
   73695     */
   73696     case TK_DOT: {
   73697       const char *zColumn;
   73698       const char *zTable;
   73699       const char *zDb;
   73700       Expr *pRight;
   73701 
   73702       /* if( pSrcList==0 ) break; */
   73703       pRight = pExpr->pRight;
   73704       if( pRight->op==TK_ID ){
   73705         zDb = 0;
   73706         zTable = pExpr->pLeft->u.zToken;
   73707         zColumn = pRight->u.zToken;
   73708       }else{
   73709         assert( pRight->op==TK_DOT );
   73710         zDb = pExpr->pLeft->u.zToken;
   73711         zTable = pRight->pLeft->u.zToken;
   73712         zColumn = pRight->pRight->u.zToken;
   73713       }
   73714       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   73715     }
   73716 
   73717     /* Resolve function names
   73718     */
   73719     case TK_CONST_FUNC:
   73720     case TK_FUNCTION: {
   73721       ExprList *pList = pExpr->x.pList;    /* The argument list */
   73722       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   73723       int no_such_func = 0;       /* True if no such function exists */
   73724       int wrong_num_args = 0;     /* True if wrong number of arguments */
   73725       int is_agg = 0;             /* True if is an aggregate function */
   73726       int auth;                   /* Authorization to use the function */
   73727       int nId;                    /* Number of characters in function name */
   73728       const char *zId;            /* The function name. */
   73729       FuncDef *pDef;              /* Information about the function */
   73730       u8 enc = ENC(pParse->db);   /* The database encoding */
   73731 
   73732       testcase( pExpr->op==TK_CONST_FUNC );
   73733       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   73734       zId = pExpr->u.zToken;
   73735       nId = sqlite3Strlen30(zId);
   73736       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   73737       if( pDef==0 ){
   73738         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
   73739         if( pDef==0 ){
   73740           no_such_func = 1;
   73741         }else{
   73742           wrong_num_args = 1;
   73743         }
   73744       }else{
   73745         is_agg = pDef->xFunc==0;
   73746       }
   73747 #ifndef SQLITE_OMIT_AUTHORIZATION
   73748       if( pDef ){
   73749         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   73750         if( auth!=SQLITE_OK ){
   73751           if( auth==SQLITE_DENY ){
   73752             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   73753                                     pDef->zName);
   73754             pNC->nErr++;
   73755           }
   73756           pExpr->op = TK_NULL;
   73757           return WRC_Prune;
   73758         }
   73759       }
   73760 #endif
   73761       if( is_agg && !pNC->allowAgg ){
   73762         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   73763         pNC->nErr++;
   73764         is_agg = 0;
   73765       }else if( no_such_func ){
   73766         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   73767         pNC->nErr++;
   73768       }else if( wrong_num_args ){
   73769         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   73770              nId, zId);
   73771         pNC->nErr++;
   73772       }
   73773       if( is_agg ){
   73774         pExpr->op = TK_AGG_FUNCTION;
   73775         pNC->hasAgg = 1;
   73776       }
   73777       if( is_agg ) pNC->allowAgg = 0;
   73778       sqlite3WalkExprList(pWalker, pList);
   73779       if( is_agg ) pNC->allowAgg = 1;
   73780       /* FIX ME:  Compute pExpr->affinity based on the expected return
   73781       ** type of the function
   73782       */
   73783       return WRC_Prune;
   73784     }
   73785 #ifndef SQLITE_OMIT_SUBQUERY
   73786     case TK_SELECT:
   73787     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   73788 #endif
   73789     case TK_IN: {
   73790       testcase( pExpr->op==TK_IN );
   73791       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   73792         int nRef = pNC->nRef;
   73793 #ifndef SQLITE_OMIT_CHECK
   73794         if( pNC->isCheck ){
   73795           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
   73796         }
   73797 #endif
   73798         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   73799         assert( pNC->nRef>=nRef );
   73800         if( nRef!=pNC->nRef ){
   73801           ExprSetProperty(pExpr, EP_VarSelect);
   73802         }
   73803       }
   73804       break;
   73805     }
   73806 #ifndef SQLITE_OMIT_CHECK
   73807     case TK_VARIABLE: {
   73808       if( pNC->isCheck ){
   73809         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
   73810       }
   73811       break;
   73812     }
   73813 #endif
   73814   }
   73815   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   73816 }
   73817 
   73818 /*
   73819 ** pEList is a list of expressions which are really the result set of the
   73820 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   73821 ** This routine checks to see if pE is a simple identifier which corresponds
   73822 ** to the AS-name of one of the terms of the expression list.  If it is,
   73823 ** this routine return an integer between 1 and N where N is the number of
   73824 ** elements in pEList, corresponding to the matching entry.  If there is
   73825 ** no match, or if pE is not a simple identifier, then this routine
   73826 ** return 0.
   73827 **
   73828 ** pEList has been resolved.  pE has not.
   73829 */
   73830 static int resolveAsName(
   73831   Parse *pParse,     /* Parsing context for error messages */
   73832   ExprList *pEList,  /* List of expressions to scan */
   73833   Expr *pE           /* Expression we are trying to match */
   73834 ){
   73835   int i;             /* Loop counter */
   73836 
   73837   UNUSED_PARAMETER(pParse);
   73838 
   73839   if( pE->op==TK_ID ){
   73840     char *zCol = pE->u.zToken;
   73841     for(i=0; i<pEList->nExpr; i++){
   73842       char *zAs = pEList->a[i].zName;
   73843       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   73844         return i+1;
   73845       }
   73846     }
   73847   }
   73848   return 0;
   73849 }
   73850 
   73851 /*
   73852 ** pE is a pointer to an expression which is a single term in the
   73853 ** ORDER BY of a compound SELECT.  The expression has not been
   73854 ** name resolved.
   73855 **
   73856 ** At the point this routine is called, we already know that the
   73857 ** ORDER BY term is not an integer index into the result set.  That
   73858 ** case is handled by the calling routine.
   73859 **
   73860 ** Attempt to match pE against result set columns in the left-most
   73861 ** SELECT statement.  Return the index i of the matching column,
   73862 ** as an indication to the caller that it should sort by the i-th column.
   73863 ** The left-most column is 1.  In other words, the value returned is the
   73864 ** same integer value that would be used in the SQL statement to indicate
   73865 ** the column.
   73866 **
   73867 ** If there is no match, return 0.  Return -1 if an error occurs.
   73868 */
   73869 static int resolveOrderByTermToExprList(
   73870   Parse *pParse,     /* Parsing context for error messages */
   73871   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   73872   Expr *pE           /* The specific ORDER BY term */
   73873 ){
   73874   int i;             /* Loop counter */
   73875   ExprList *pEList;  /* The columns of the result set */
   73876   NameContext nc;    /* Name context for resolving pE */
   73877   sqlite3 *db;       /* Database connection */
   73878   int rc;            /* Return code from subprocedures */
   73879   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   73880 
   73881   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   73882   pEList = pSelect->pEList;
   73883 
   73884   /* Resolve all names in the ORDER BY term expression
   73885   */
   73886   memset(&nc, 0, sizeof(nc));
   73887   nc.pParse = pParse;
   73888   nc.pSrcList = pSelect->pSrc;
   73889   nc.pEList = pEList;
   73890   nc.allowAgg = 1;
   73891   nc.nErr = 0;
   73892   db = pParse->db;
   73893   savedSuppErr = db->suppressErr;
   73894   db->suppressErr = 1;
   73895   rc = sqlite3ResolveExprNames(&nc, pE);
   73896   db->suppressErr = savedSuppErr;
   73897   if( rc ) return 0;
   73898 
   73899   /* Try to match the ORDER BY expression against an expression
   73900   ** in the result set.  Return an 1-based index of the matching
   73901   ** result-set entry.
   73902   */
   73903   for(i=0; i<pEList->nExpr; i++){
   73904     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
   73905       return i+1;
   73906     }
   73907   }
   73908 
   73909   /* If no match, return 0. */
   73910   return 0;
   73911 }
   73912 
   73913 /*
   73914 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   73915 */
   73916 static void resolveOutOfRangeError(
   73917   Parse *pParse,         /* The error context into which to write the error */
   73918   const char *zType,     /* "ORDER" or "GROUP" */
   73919   int i,                 /* The index (1-based) of the term out of range */
   73920   int mx                 /* Largest permissible value of i */
   73921 ){
   73922   sqlite3ErrorMsg(pParse,
   73923     "%r %s BY term out of range - should be "
   73924     "between 1 and %d", i, zType, mx);
   73925 }
   73926 
   73927 /*
   73928 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   73929 ** each term of the ORDER BY clause is a constant integer between 1
   73930 ** and N where N is the number of columns in the compound SELECT.
   73931 **
   73932 ** ORDER BY terms that are already an integer between 1 and N are
   73933 ** unmodified.  ORDER BY terms that are integers outside the range of
   73934 ** 1 through N generate an error.  ORDER BY terms that are expressions
   73935 ** are matched against result set expressions of compound SELECT
   73936 ** beginning with the left-most SELECT and working toward the right.
   73937 ** At the first match, the ORDER BY expression is transformed into
   73938 ** the integer column number.
   73939 **
   73940 ** Return the number of errors seen.
   73941 */
   73942 static int resolveCompoundOrderBy(
   73943   Parse *pParse,        /* Parsing context.  Leave error messages here */
   73944   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   73945 ){
   73946   int i;
   73947   ExprList *pOrderBy;
   73948   ExprList *pEList;
   73949   sqlite3 *db;
   73950   int moreToDo = 1;
   73951 
   73952   pOrderBy = pSelect->pOrderBy;
   73953   if( pOrderBy==0 ) return 0;
   73954   db = pParse->db;
   73955 #if SQLITE_MAX_COLUMN
   73956   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   73957     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   73958     return 1;
   73959   }
   73960 #endif
   73961   for(i=0; i<pOrderBy->nExpr; i++){
   73962     pOrderBy->a[i].done = 0;
   73963   }
   73964   pSelect->pNext = 0;
   73965   while( pSelect->pPrior ){
   73966     pSelect->pPrior->pNext = pSelect;
   73967     pSelect = pSelect->pPrior;
   73968   }
   73969   while( pSelect && moreToDo ){
   73970     struct ExprList_item *pItem;
   73971     moreToDo = 0;
   73972     pEList = pSelect->pEList;
   73973     assert( pEList!=0 );
   73974     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   73975       int iCol = -1;
   73976       Expr *pE, *pDup;
   73977       if( pItem->done ) continue;
   73978       pE = pItem->pExpr;
   73979       if( sqlite3ExprIsInteger(pE, &iCol) ){
   73980         if( iCol<=0 || iCol>pEList->nExpr ){
   73981           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   73982           return 1;
   73983         }
   73984       }else{
   73985         iCol = resolveAsName(pParse, pEList, pE);
   73986         if( iCol==0 ){
   73987           pDup = sqlite3ExprDup(db, pE, 0);
   73988           if( !db->mallocFailed ){
   73989             assert(pDup);
   73990             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   73991           }
   73992           sqlite3ExprDelete(db, pDup);
   73993         }
   73994       }
   73995       if( iCol>0 ){
   73996         CollSeq *pColl = pE->pColl;
   73997         int flags = pE->flags & EP_ExpCollate;
   73998         sqlite3ExprDelete(db, pE);
   73999         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
   74000         if( pE==0 ) return 1;
   74001         pE->pColl = pColl;
   74002         pE->flags |= EP_IntValue | flags;
   74003         pE->u.iValue = iCol;
   74004         pItem->iOrderByCol = (u16)iCol;
   74005         pItem->done = 1;
   74006       }else{
   74007         moreToDo = 1;
   74008       }
   74009     }
   74010     pSelect = pSelect->pNext;
   74011   }
   74012   for(i=0; i<pOrderBy->nExpr; i++){
   74013     if( pOrderBy->a[i].done==0 ){
   74014       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   74015             "column in the result set", i+1);
   74016       return 1;
   74017     }
   74018   }
   74019   return 0;
   74020 }
   74021 
   74022 /*
   74023 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   74024 ** the SELECT statement pSelect.  If any term is reference to a
   74025 ** result set expression (as determined by the ExprList.a.iCol field)
   74026 ** then convert that term into a copy of the corresponding result set
   74027 ** column.
   74028 **
   74029 ** If any errors are detected, add an error message to pParse and
   74030 ** return non-zero.  Return zero if no errors are seen.
   74031 */
   74032 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   74033   Parse *pParse,        /* Parsing context.  Leave error messages here */
   74034   Select *pSelect,      /* The SELECT statement containing the clause */
   74035   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   74036   const char *zType     /* "ORDER" or "GROUP" */
   74037 ){
   74038   int i;
   74039   sqlite3 *db = pParse->db;
   74040   ExprList *pEList;
   74041   struct ExprList_item *pItem;
   74042 
   74043   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   74044 #if SQLITE_MAX_COLUMN
   74045   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   74046     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   74047     return 1;
   74048   }
   74049 #endif
   74050   pEList = pSelect->pEList;
   74051   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   74052   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   74053     if( pItem->iOrderByCol ){
   74054       if( pItem->iOrderByCol>pEList->nExpr ){
   74055         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   74056         return 1;
   74057       }
   74058       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
   74059     }
   74060   }
   74061   return 0;
   74062 }
   74063 
   74064 /*
   74065 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   74066 ** The Name context of the SELECT statement is pNC.  zType is either
   74067 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   74068 **
   74069 ** This routine resolves each term of the clause into an expression.
   74070 ** If the order-by term is an integer I between 1 and N (where N is the
   74071 ** number of columns in the result set of the SELECT) then the expression
   74072 ** in the resolution is a copy of the I-th result-set expression.  If
   74073 ** the order-by term is an identify that corresponds to the AS-name of
   74074 ** a result-set expression, then the term resolves to a copy of the
   74075 ** result-set expression.  Otherwise, the expression is resolved in
   74076 ** the usual way - using sqlite3ResolveExprNames().
   74077 **
   74078 ** This routine returns the number of errors.  If errors occur, then
   74079 ** an appropriate error message might be left in pParse.  (OOM errors
   74080 ** excepted.)
   74081 */
   74082 static int resolveOrderGroupBy(
   74083   NameContext *pNC,     /* The name context of the SELECT statement */
   74084   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   74085   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   74086   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   74087 ){
   74088   int i;                         /* Loop counter */
   74089   int iCol;                      /* Column number */
   74090   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   74091   Parse *pParse;                 /* Parsing context */
   74092   int nResult;                   /* Number of terms in the result set */
   74093 
   74094   if( pOrderBy==0 ) return 0;
   74095   nResult = pSelect->pEList->nExpr;
   74096   pParse = pNC->pParse;
   74097   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   74098     Expr *pE = pItem->pExpr;
   74099     iCol = resolveAsName(pParse, pSelect->pEList, pE);
   74100     if( iCol>0 ){
   74101       /* If an AS-name match is found, mark this ORDER BY column as being
   74102       ** a copy of the iCol-th result-set column.  The subsequent call to
   74103       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   74104       ** copy of the iCol-th result-set expression. */
   74105       pItem->iOrderByCol = (u16)iCol;
   74106       continue;
   74107     }
   74108     if( sqlite3ExprIsInteger(pE, &iCol) ){
   74109       /* The ORDER BY term is an integer constant.  Again, set the column
   74110       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   74111       ** order-by term to a copy of the result-set expression */
   74112       if( iCol<1 ){
   74113         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   74114         return 1;
   74115       }
   74116       pItem->iOrderByCol = (u16)iCol;
   74117       continue;
   74118     }
   74119 
   74120     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   74121     pItem->iOrderByCol = 0;
   74122     if( sqlite3ResolveExprNames(pNC, pE) ){
   74123       return 1;
   74124     }
   74125   }
   74126   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   74127 }
   74128 
   74129 /*
   74130 ** Resolve names in the SELECT statement p and all of its descendents.
   74131 */
   74132 static int resolveSelectStep(Walker *pWalker, Select *p){
   74133   NameContext *pOuterNC;  /* Context that contains this SELECT */
   74134   NameContext sNC;        /* Name context of this SELECT */
   74135   int isCompound;         /* True if p is a compound select */
   74136   int nCompound;          /* Number of compound terms processed so far */
   74137   Parse *pParse;          /* Parsing context */
   74138   ExprList *pEList;       /* Result set expression list */
   74139   int i;                  /* Loop counter */
   74140   ExprList *pGroupBy;     /* The GROUP BY clause */
   74141   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   74142   sqlite3 *db;            /* Database connection */
   74143 
   74144 
   74145   assert( p!=0 );
   74146   if( p->selFlags & SF_Resolved ){
   74147     return WRC_Prune;
   74148   }
   74149   pOuterNC = pWalker->u.pNC;
   74150   pParse = pWalker->pParse;
   74151   db = pParse->db;
   74152 
   74153   /* Normally sqlite3SelectExpand() will be called first and will have
   74154   ** already expanded this SELECT.  However, if this is a subquery within
   74155   ** an expression, sqlite3ResolveExprNames() will be called without a
   74156   ** prior call to sqlite3SelectExpand().  When that happens, let
   74157   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   74158   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   74159   ** this routine in the correct order.
   74160   */
   74161   if( (p->selFlags & SF_Expanded)==0 ){
   74162     sqlite3SelectPrep(pParse, p, pOuterNC);
   74163     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   74164   }
   74165 
   74166   isCompound = p->pPrior!=0;
   74167   nCompound = 0;
   74168   pLeftmost = p;
   74169   while( p ){
   74170     assert( (p->selFlags & SF_Expanded)!=0 );
   74171     assert( (p->selFlags & SF_Resolved)==0 );
   74172     p->selFlags |= SF_Resolved;
   74173 
   74174     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   74175     ** are not allowed to refer to any names, so pass an empty NameContext.
   74176     */
   74177     memset(&sNC, 0, sizeof(sNC));
   74178     sNC.pParse = pParse;
   74179     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   74180         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   74181       return WRC_Abort;
   74182     }
   74183 
   74184     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   74185     ** resolve the result-set expression list.
   74186     */
   74187     sNC.allowAgg = 1;
   74188     sNC.pSrcList = p->pSrc;
   74189     sNC.pNext = pOuterNC;
   74190 
   74191     /* Resolve names in the result set. */
   74192     pEList = p->pEList;
   74193     assert( pEList!=0 );
   74194     for(i=0; i<pEList->nExpr; i++){
   74195       Expr *pX = pEList->a[i].pExpr;
   74196       if( sqlite3ResolveExprNames(&sNC, pX) ){
   74197         return WRC_Abort;
   74198       }
   74199     }
   74200 
   74201     /* Recursively resolve names in all subqueries
   74202     */
   74203     for(i=0; i<p->pSrc->nSrc; i++){
   74204       struct SrcList_item *pItem = &p->pSrc->a[i];
   74205       if( pItem->pSelect ){
   74206         NameContext *pNC;         /* Used to iterate name contexts */
   74207         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
   74208         const char *zSavedContext = pParse->zAuthContext;
   74209 
   74210         /* Count the total number of references to pOuterNC and all of its
   74211         ** parent contexts. After resolving references to expressions in
   74212         ** pItem->pSelect, check if this value has changed. If so, then
   74213         ** SELECT statement pItem->pSelect must be correlated. Set the
   74214         ** pItem->isCorrelated flag if this is the case. */
   74215         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
   74216 
   74217         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   74218         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   74219         pParse->zAuthContext = zSavedContext;
   74220         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   74221 
   74222         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
   74223         assert( pItem->isCorrelated==0 && nRef<=0 );
   74224         pItem->isCorrelated = (nRef!=0);
   74225       }
   74226     }
   74227 
   74228     /* If there are no aggregate functions in the result-set, and no GROUP BY
   74229     ** expression, do not allow aggregates in any of the other expressions.
   74230     */
   74231     assert( (p->selFlags & SF_Aggregate)==0 );
   74232     pGroupBy = p->pGroupBy;
   74233     if( pGroupBy || sNC.hasAgg ){
   74234       p->selFlags |= SF_Aggregate;
   74235     }else{
   74236       sNC.allowAgg = 0;
   74237     }
   74238 
   74239     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   74240     */
   74241     if( p->pHaving && !pGroupBy ){
   74242       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   74243       return WRC_Abort;
   74244     }
   74245 
   74246     /* Add the expression list to the name-context before parsing the
   74247     ** other expressions in the SELECT statement. This is so that
   74248     ** expressions in the WHERE clause (etc.) can refer to expressions by
   74249     ** aliases in the result set.
   74250     **
   74251     ** Minor point: If this is the case, then the expression will be
   74252     ** re-evaluated for each reference to it.
   74253     */
   74254     sNC.pEList = p->pEList;
   74255     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
   74256        sqlite3ResolveExprNames(&sNC, p->pHaving)
   74257     ){
   74258       return WRC_Abort;
   74259     }
   74260 
   74261     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   74262     ** outer queries
   74263     */
   74264     sNC.pNext = 0;
   74265     sNC.allowAgg = 1;
   74266 
   74267     /* Process the ORDER BY clause for singleton SELECT statements.
   74268     ** The ORDER BY clause for compounds SELECT statements is handled
   74269     ** below, after all of the result-sets for all of the elements of
   74270     ** the compound have been resolved.
   74271     */
   74272     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   74273       return WRC_Abort;
   74274     }
   74275     if( db->mallocFailed ){
   74276       return WRC_Abort;
   74277     }
   74278 
   74279     /* Resolve the GROUP BY clause.  At the same time, make sure
   74280     ** the GROUP BY clause does not contain aggregate functions.
   74281     */
   74282     if( pGroupBy ){
   74283       struct ExprList_item *pItem;
   74284 
   74285       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   74286         return WRC_Abort;
   74287       }
   74288       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   74289         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   74290           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   74291               "the GROUP BY clause");
   74292           return WRC_Abort;
   74293         }
   74294       }
   74295     }
   74296 
   74297     /* Advance to the next term of the compound
   74298     */
   74299     p = p->pPrior;
   74300     nCompound++;
   74301   }
   74302 
   74303   /* Resolve the ORDER BY on a compound SELECT after all terms of
   74304   ** the compound have been resolved.
   74305   */
   74306   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   74307     return WRC_Abort;
   74308   }
   74309 
   74310   return WRC_Prune;
   74311 }
   74312 
   74313 /*
   74314 ** This routine walks an expression tree and resolves references to
   74315 ** table columns and result-set columns.  At the same time, do error
   74316 ** checking on function usage and set a flag if any aggregate functions
   74317 ** are seen.
   74318 **
   74319 ** To resolve table columns references we look for nodes (or subtrees) of the
   74320 ** form X.Y.Z or Y.Z or just Z where
   74321 **
   74322 **      X:   The name of a database.  Ex:  "main" or "temp" or
   74323 **           the symbolic name assigned to an ATTACH-ed database.
   74324 **
   74325 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   74326 **           one of the special names "old" or "new".
   74327 **
   74328 **      Z:   The name of a column in table Y.
   74329 **
   74330 ** The node at the root of the subtree is modified as follows:
   74331 **
   74332 **    Expr.op        Changed to TK_COLUMN
   74333 **    Expr.pTab      Points to the Table object for X.Y
   74334 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   74335 **    Expr.iTable    The VDBE cursor number for X.Y
   74336 **
   74337 **
   74338 ** To resolve result-set references, look for expression nodes of the
   74339 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   74340 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   74341 ** is replaced by a copy of the left-hand side of the result-set expression.
   74342 ** Table-name and function resolution occurs on the substituted expression
   74343 ** tree.  For example, in:
   74344 **
   74345 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   74346 **
   74347 ** The "x" term of the order by is replaced by "a+b" to render:
   74348 **
   74349 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   74350 **
   74351 ** Function calls are checked to make sure that the function is
   74352 ** defined and that the correct number of arguments are specified.
   74353 ** If the function is an aggregate function, then the pNC->hasAgg is
   74354 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   74355 ** If an expression contains aggregate functions then the EP_Agg
   74356 ** property on the expression is set.
   74357 **
   74358 ** An error message is left in pParse if anything is amiss.  The number
   74359 ** if errors is returned.
   74360 */
   74361 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   74362   NameContext *pNC,       /* Namespace to resolve expressions in. */
   74363   Expr *pExpr             /* The expression to be analyzed. */
   74364 ){
   74365   int savedHasAgg;
   74366   Walker w;
   74367 
   74368   if( pExpr==0 ) return 0;
   74369 #if SQLITE_MAX_EXPR_DEPTH>0
   74370   {
   74371     Parse *pParse = pNC->pParse;
   74372     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   74373       return 1;
   74374     }
   74375     pParse->nHeight += pExpr->nHeight;
   74376   }
   74377 #endif
   74378   savedHasAgg = pNC->hasAgg;
   74379   pNC->hasAgg = 0;
   74380   w.xExprCallback = resolveExprStep;
   74381   w.xSelectCallback = resolveSelectStep;
   74382   w.pParse = pNC->pParse;
   74383   w.u.pNC = pNC;
   74384   sqlite3WalkExpr(&w, pExpr);
   74385 #if SQLITE_MAX_EXPR_DEPTH>0
   74386   pNC->pParse->nHeight -= pExpr->nHeight;
   74387 #endif
   74388   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   74389     ExprSetProperty(pExpr, EP_Error);
   74390   }
   74391   if( pNC->hasAgg ){
   74392     ExprSetProperty(pExpr, EP_Agg);
   74393   }else if( savedHasAgg ){
   74394     pNC->hasAgg = 1;
   74395   }
   74396   return ExprHasProperty(pExpr, EP_Error);
   74397 }
   74398 
   74399 
   74400 /*
   74401 ** Resolve all names in all expressions of a SELECT and in all
   74402 ** decendents of the SELECT, including compounds off of p->pPrior,
   74403 ** subqueries in expressions, and subqueries used as FROM clause
   74404 ** terms.
   74405 **
   74406 ** See sqlite3ResolveExprNames() for a description of the kinds of
   74407 ** transformations that occur.
   74408 **
   74409 ** All SELECT statements should have been expanded using
   74410 ** sqlite3SelectExpand() prior to invoking this routine.
   74411 */
   74412 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   74413   Parse *pParse,         /* The parser context */
   74414   Select *p,             /* The SELECT statement being coded. */
   74415   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   74416 ){
   74417   Walker w;
   74418 
   74419   assert( p!=0 );
   74420   w.xExprCallback = resolveExprStep;
   74421   w.xSelectCallback = resolveSelectStep;
   74422   w.pParse = pParse;
   74423   w.u.pNC = pOuterNC;
   74424   sqlite3WalkSelect(&w, p);
   74425 }
   74426 
   74427 /************** End of resolve.c *********************************************/
   74428 /************** Begin file expr.c ********************************************/
   74429 /*
   74430 ** 2001 September 15
   74431 **
   74432 ** The author disclaims copyright to this source code.  In place of
   74433 ** a legal notice, here is a blessing:
   74434 **
   74435 **    May you do good and not evil.
   74436 **    May you find forgiveness for yourself and forgive others.
   74437 **    May you share freely, never taking more than you give.
   74438 **
   74439 *************************************************************************
   74440 ** This file contains routines used for analyzing expressions and
   74441 ** for generating VDBE code that evaluates expressions in SQLite.
   74442 */
   74443 
   74444 /*
   74445 ** Return the 'affinity' of the expression pExpr if any.
   74446 **
   74447 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   74448 ** or a sub-select with a column as the return value, then the
   74449 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   74450 ** indicating no affinity for the expression.
   74451 **
   74452 ** i.e. the WHERE clause expresssions in the following statements all
   74453 ** have an affinity:
   74454 **
   74455 ** CREATE TABLE t1(a);
   74456 ** SELECT * FROM t1 WHERE a;
   74457 ** SELECT a AS b FROM t1 WHERE b;
   74458 ** SELECT * FROM t1 WHERE (select a from t1);
   74459 */
   74460 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   74461   int op = pExpr->op;
   74462   if( op==TK_SELECT ){
   74463     assert( pExpr->flags&EP_xIsSelect );
   74464     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   74465   }
   74466 #ifndef SQLITE_OMIT_CAST
   74467   if( op==TK_CAST ){
   74468     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   74469     return sqlite3AffinityType(pExpr->u.zToken);
   74470   }
   74471 #endif
   74472   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   74473    && pExpr->pTab!=0
   74474   ){
   74475     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   74476     ** a TK_COLUMN but was previously evaluated and cached in a register */
   74477     int j = pExpr->iColumn;
   74478     if( j<0 ) return SQLITE_AFF_INTEGER;
   74479     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   74480     return pExpr->pTab->aCol[j].affinity;
   74481   }
   74482   return pExpr->affinity;
   74483 }
   74484 
   74485 /*
   74486 ** Set the explicit collating sequence for an expression to the
   74487 ** collating sequence supplied in the second argument.
   74488 */
   74489 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
   74490   if( pExpr && pColl ){
   74491     pExpr->pColl = pColl;
   74492     pExpr->flags |= EP_ExpCollate;
   74493   }
   74494   return pExpr;
   74495 }
   74496 
   74497 /*
   74498 ** Set the collating sequence for expression pExpr to be the collating
   74499 ** sequence named by pToken.   Return a pointer to the revised expression.
   74500 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
   74501 ** flag.  An explicit collating sequence will override implicit
   74502 ** collating sequences.
   74503 */
   74504 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
   74505   char *zColl = 0;            /* Dequoted name of collation sequence */
   74506   CollSeq *pColl;
   74507   sqlite3 *db = pParse->db;
   74508   zColl = sqlite3NameFromToken(db, pCollName);
   74509   pColl = sqlite3LocateCollSeq(pParse, zColl);
   74510   sqlite3ExprSetColl(pExpr, pColl);
   74511   sqlite3DbFree(db, zColl);
   74512   return pExpr;
   74513 }
   74514 
   74515 /*
   74516 ** Return the default collation sequence for the expression pExpr. If
   74517 ** there is no default collation type, return 0.
   74518 */
   74519 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   74520   CollSeq *pColl = 0;
   74521   Expr *p = pExpr;
   74522   while( p ){
   74523     int op;
   74524     pColl = p->pColl;
   74525     if( pColl ) break;
   74526     op = p->op;
   74527     if( p->pTab!=0 && (
   74528         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
   74529     )){
   74530       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   74531       ** a TK_COLUMN but was previously evaluated and cached in a register */
   74532       const char *zColl;
   74533       int j = p->iColumn;
   74534       if( j>=0 ){
   74535         sqlite3 *db = pParse->db;
   74536         zColl = p->pTab->aCol[j].zColl;
   74537         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   74538         pExpr->pColl = pColl;
   74539       }
   74540       break;
   74541     }
   74542     if( op!=TK_CAST && op!=TK_UPLUS ){
   74543       break;
   74544     }
   74545     p = p->pLeft;
   74546   }
   74547   if( sqlite3CheckCollSeq(pParse, pColl) ){
   74548     pColl = 0;
   74549   }
   74550   return pColl;
   74551 }
   74552 
   74553 /*
   74554 ** pExpr is an operand of a comparison operator.  aff2 is the
   74555 ** type affinity of the other operand.  This routine returns the
   74556 ** type affinity that should be used for the comparison operator.
   74557 */
   74558 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   74559   char aff1 = sqlite3ExprAffinity(pExpr);
   74560   if( aff1 && aff2 ){
   74561     /* Both sides of the comparison are columns. If one has numeric
   74562     ** affinity, use that. Otherwise use no affinity.
   74563     */
   74564     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   74565       return SQLITE_AFF_NUMERIC;
   74566     }else{
   74567       return SQLITE_AFF_NONE;
   74568     }
   74569   }else if( !aff1 && !aff2 ){
   74570     /* Neither side of the comparison is a column.  Compare the
   74571     ** results directly.
   74572     */
   74573     return SQLITE_AFF_NONE;
   74574   }else{
   74575     /* One side is a column, the other is not. Use the columns affinity. */
   74576     assert( aff1==0 || aff2==0 );
   74577     return (aff1 + aff2);
   74578   }
   74579 }
   74580 
   74581 /*
   74582 ** pExpr is a comparison operator.  Return the type affinity that should
   74583 ** be applied to both operands prior to doing the comparison.
   74584 */
   74585 static char comparisonAffinity(Expr *pExpr){
   74586   char aff;
   74587   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   74588           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   74589           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   74590   assert( pExpr->pLeft );
   74591   aff = sqlite3ExprAffinity(pExpr->pLeft);
   74592   if( pExpr->pRight ){
   74593     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   74594   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   74595     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   74596   }else if( !aff ){
   74597     aff = SQLITE_AFF_NONE;
   74598   }
   74599   return aff;
   74600 }
   74601 
   74602 /*
   74603 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   74604 ** idx_affinity is the affinity of an indexed column. Return true
   74605 ** if the index with affinity idx_affinity may be used to implement
   74606 ** the comparison in pExpr.
   74607 */
   74608 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   74609   char aff = comparisonAffinity(pExpr);
   74610   switch( aff ){
   74611     case SQLITE_AFF_NONE:
   74612       return 1;
   74613     case SQLITE_AFF_TEXT:
   74614       return idx_affinity==SQLITE_AFF_TEXT;
   74615     default:
   74616       return sqlite3IsNumericAffinity(idx_affinity);
   74617   }
   74618 }
   74619 
   74620 /*
   74621 ** Return the P5 value that should be used for a binary comparison
   74622 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   74623 */
   74624 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   74625   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   74626   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   74627   return aff;
   74628 }
   74629 
   74630 /*
   74631 ** Return a pointer to the collation sequence that should be used by
   74632 ** a binary comparison operator comparing pLeft and pRight.
   74633 **
   74634 ** If the left hand expression has a collating sequence type, then it is
   74635 ** used. Otherwise the collation sequence for the right hand expression
   74636 ** is used, or the default (BINARY) if neither expression has a collating
   74637 ** type.
   74638 **
   74639 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   74640 ** it is not considered.
   74641 */
   74642 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   74643   Parse *pParse,
   74644   Expr *pLeft,
   74645   Expr *pRight
   74646 ){
   74647   CollSeq *pColl;
   74648   assert( pLeft );
   74649   if( pLeft->flags & EP_ExpCollate ){
   74650     assert( pLeft->pColl );
   74651     pColl = pLeft->pColl;
   74652   }else if( pRight && pRight->flags & EP_ExpCollate ){
   74653     assert( pRight->pColl );
   74654     pColl = pRight->pColl;
   74655   }else{
   74656     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   74657     if( !pColl ){
   74658       pColl = sqlite3ExprCollSeq(pParse, pRight);
   74659     }
   74660   }
   74661   return pColl;
   74662 }
   74663 
   74664 /*
   74665 ** Generate code for a comparison operator.
   74666 */
   74667 static int codeCompare(
   74668   Parse *pParse,    /* The parsing (and code generating) context */
   74669   Expr *pLeft,      /* The left operand */
   74670   Expr *pRight,     /* The right operand */
   74671   int opcode,       /* The comparison opcode */
   74672   int in1, int in2, /* Register holding operands */
   74673   int dest,         /* Jump here if true.  */
   74674   int jumpIfNull    /* If true, jump if either operand is NULL */
   74675 ){
   74676   int p5;
   74677   int addr;
   74678   CollSeq *p4;
   74679 
   74680   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   74681   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   74682   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   74683                            (void*)p4, P4_COLLSEQ);
   74684   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   74685   return addr;
   74686 }
   74687 
   74688 #if SQLITE_MAX_EXPR_DEPTH>0
   74689 /*
   74690 ** Check that argument nHeight is less than or equal to the maximum
   74691 ** expression depth allowed. If it is not, leave an error message in
   74692 ** pParse.
   74693 */
   74694 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   74695   int rc = SQLITE_OK;
   74696   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   74697   if( nHeight>mxHeight ){
   74698     sqlite3ErrorMsg(pParse,
   74699        "Expression tree is too large (maximum depth %d)", mxHeight
   74700     );
   74701     rc = SQLITE_ERROR;
   74702   }
   74703   return rc;
   74704 }
   74705 
   74706 /* The following three functions, heightOfExpr(), heightOfExprList()
   74707 ** and heightOfSelect(), are used to determine the maximum height
   74708 ** of any expression tree referenced by the structure passed as the
   74709 ** first argument.
   74710 **
   74711 ** If this maximum height is greater than the current value pointed
   74712 ** to by pnHeight, the second parameter, then set *pnHeight to that
   74713 ** value.
   74714 */
   74715 static void heightOfExpr(Expr *p, int *pnHeight){
   74716   if( p ){
   74717     if( p->nHeight>*pnHeight ){
   74718       *pnHeight = p->nHeight;
   74719     }
   74720   }
   74721 }
   74722 static void heightOfExprList(ExprList *p, int *pnHeight){
   74723   if( p ){
   74724     int i;
   74725     for(i=0; i<p->nExpr; i++){
   74726       heightOfExpr(p->a[i].pExpr, pnHeight);
   74727     }
   74728   }
   74729 }
   74730 static void heightOfSelect(Select *p, int *pnHeight){
   74731   if( p ){
   74732     heightOfExpr(p->pWhere, pnHeight);
   74733     heightOfExpr(p->pHaving, pnHeight);
   74734     heightOfExpr(p->pLimit, pnHeight);
   74735     heightOfExpr(p->pOffset, pnHeight);
   74736     heightOfExprList(p->pEList, pnHeight);
   74737     heightOfExprList(p->pGroupBy, pnHeight);
   74738     heightOfExprList(p->pOrderBy, pnHeight);
   74739     heightOfSelect(p->pPrior, pnHeight);
   74740   }
   74741 }
   74742 
   74743 /*
   74744 ** Set the Expr.nHeight variable in the structure passed as an
   74745 ** argument. An expression with no children, Expr.pList or
   74746 ** Expr.pSelect member has a height of 1. Any other expression
   74747 ** has a height equal to the maximum height of any other
   74748 ** referenced Expr plus one.
   74749 */
   74750 static void exprSetHeight(Expr *p){
   74751   int nHeight = 0;
   74752   heightOfExpr(p->pLeft, &nHeight);
   74753   heightOfExpr(p->pRight, &nHeight);
   74754   if( ExprHasProperty(p, EP_xIsSelect) ){
   74755     heightOfSelect(p->x.pSelect, &nHeight);
   74756   }else{
   74757     heightOfExprList(p->x.pList, &nHeight);
   74758   }
   74759   p->nHeight = nHeight + 1;
   74760 }
   74761 
   74762 /*
   74763 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   74764 ** the height is greater than the maximum allowed expression depth,
   74765 ** leave an error in pParse.
   74766 */
   74767 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   74768   exprSetHeight(p);
   74769   sqlite3ExprCheckHeight(pParse, p->nHeight);
   74770 }
   74771 
   74772 /*
   74773 ** Return the maximum height of any expression tree referenced
   74774 ** by the select statement passed as an argument.
   74775 */
   74776 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   74777   int nHeight = 0;
   74778   heightOfSelect(p, &nHeight);
   74779   return nHeight;
   74780 }
   74781 #else
   74782   #define exprSetHeight(y)
   74783 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   74784 
   74785 /*
   74786 ** This routine is the core allocator for Expr nodes.
   74787 **
   74788 ** Construct a new expression node and return a pointer to it.  Memory
   74789 ** for this node and for the pToken argument is a single allocation
   74790 ** obtained from sqlite3DbMalloc().  The calling function
   74791 ** is responsible for making sure the node eventually gets freed.
   74792 **
   74793 ** If dequote is true, then the token (if it exists) is dequoted.
   74794 ** If dequote is false, no dequoting is performance.  The deQuote
   74795 ** parameter is ignored if pToken is NULL or if the token does not
   74796 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   74797 ** then the EP_DblQuoted flag is set on the expression node.
   74798 **
   74799 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   74800 ** can be translated into a 32-bit integer, then the token is not
   74801 ** stored in u.zToken.  Instead, the integer values is written
   74802 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   74803 ** is allocated to hold the integer text and the dequote flag is ignored.
   74804 */
   74805 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   74806   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   74807   int op,                 /* Expression opcode */
   74808   const Token *pToken,    /* Token argument.  Might be NULL */
   74809   int dequote             /* True to dequote */
   74810 ){
   74811   Expr *pNew;
   74812   int nExtra = 0;
   74813   int iValue = 0;
   74814 
   74815   if( pToken ){
   74816     if( op!=TK_INTEGER || pToken->z==0
   74817           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   74818       nExtra = pToken->n+1;
   74819       assert( iValue>=0 );
   74820     }
   74821   }
   74822   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   74823   if( pNew ){
   74824     pNew->op = (u8)op;
   74825     pNew->iAgg = -1;
   74826     if( pToken ){
   74827       if( nExtra==0 ){
   74828         pNew->flags |= EP_IntValue;
   74829         pNew->u.iValue = iValue;
   74830       }else{
   74831         int c;
   74832         pNew->u.zToken = (char*)&pNew[1];
   74833         assert( pToken->z!=0 || pToken->n==0 );
   74834         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
   74835         pNew->u.zToken[pToken->n] = 0;
   74836         if( dequote && nExtra>=3
   74837              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   74838           sqlite3Dequote(pNew->u.zToken);
   74839           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   74840         }
   74841       }
   74842     }
   74843 #if SQLITE_MAX_EXPR_DEPTH>0
   74844     pNew->nHeight = 1;
   74845 #endif
   74846   }
   74847   return pNew;
   74848 }
   74849 
   74850 /*
   74851 ** Allocate a new expression node from a zero-terminated token that has
   74852 ** already been dequoted.
   74853 */
   74854 SQLITE_PRIVATE Expr *sqlite3Expr(
   74855   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   74856   int op,                 /* Expression opcode */
   74857   const char *zToken      /* Token argument.  Might be NULL */
   74858 ){
   74859   Token x;
   74860   x.z = zToken;
   74861   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   74862   return sqlite3ExprAlloc(db, op, &x, 0);
   74863 }
   74864 
   74865 /*
   74866 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   74867 **
   74868 ** If pRoot==NULL that means that a memory allocation error has occurred.
   74869 ** In that case, delete the subtrees pLeft and pRight.
   74870 */
   74871 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   74872   sqlite3 *db,
   74873   Expr *pRoot,
   74874   Expr *pLeft,
   74875   Expr *pRight
   74876 ){
   74877   if( pRoot==0 ){
   74878     assert( db->mallocFailed );
   74879     sqlite3ExprDelete(db, pLeft);
   74880     sqlite3ExprDelete(db, pRight);
   74881   }else{
   74882     if( pRight ){
   74883       pRoot->pRight = pRight;
   74884       if( pRight->flags & EP_ExpCollate ){
   74885         pRoot->flags |= EP_ExpCollate;
   74886         pRoot->pColl = pRight->pColl;
   74887       }
   74888     }
   74889     if( pLeft ){
   74890       pRoot->pLeft = pLeft;
   74891       if( pLeft->flags & EP_ExpCollate ){
   74892         pRoot->flags |= EP_ExpCollate;
   74893         pRoot->pColl = pLeft->pColl;
   74894       }
   74895     }
   74896     exprSetHeight(pRoot);
   74897   }
   74898 }
   74899 
   74900 /*
   74901 ** Allocate a Expr node which joins as many as two subtrees.
   74902 **
   74903 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   74904 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   74905 ** free the subtrees and return NULL.
   74906 */
   74907 SQLITE_PRIVATE Expr *sqlite3PExpr(
   74908   Parse *pParse,          /* Parsing context */
   74909   int op,                 /* Expression opcode */
   74910   Expr *pLeft,            /* Left operand */
   74911   Expr *pRight,           /* Right operand */
   74912   const Token *pToken     /* Argument token */
   74913 ){
   74914   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   74915   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   74916   if( p ) {
   74917     sqlite3ExprCheckHeight(pParse, p->nHeight);
   74918   }
   74919   return p;
   74920 }
   74921 
   74922 /*
   74923 ** Join two expressions using an AND operator.  If either expression is
   74924 ** NULL, then just return the other expression.
   74925 */
   74926 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   74927   if( pLeft==0 ){
   74928     return pRight;
   74929   }else if( pRight==0 ){
   74930     return pLeft;
   74931   }else{
   74932     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   74933     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   74934     return pNew;
   74935   }
   74936 }
   74937 
   74938 /*
   74939 ** Construct a new expression node for a function with multiple
   74940 ** arguments.
   74941 */
   74942 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   74943   Expr *pNew;
   74944   sqlite3 *db = pParse->db;
   74945   assert( pToken );
   74946   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   74947   if( pNew==0 ){
   74948     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   74949     return 0;
   74950   }
   74951   pNew->x.pList = pList;
   74952   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   74953   sqlite3ExprSetHeight(pParse, pNew);
   74954   return pNew;
   74955 }
   74956 
   74957 /*
   74958 ** Assign a variable number to an expression that encodes a wildcard
   74959 ** in the original SQL statement.
   74960 **
   74961 ** Wildcards consisting of a single "?" are assigned the next sequential
   74962 ** variable number.
   74963 **
   74964 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   74965 ** sure "nnn" is not too be to avoid a denial of service attack when
   74966 ** the SQL statement comes from an external source.
   74967 **
   74968 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   74969 ** as the previous instance of the same wildcard.  Or if this is the first
   74970 ** instance of the wildcard, the next sequenial variable number is
   74971 ** assigned.
   74972 */
   74973 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   74974   sqlite3 *db = pParse->db;
   74975   const char *z;
   74976 
   74977   if( pExpr==0 ) return;
   74978   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   74979   z = pExpr->u.zToken;
   74980   assert( z!=0 );
   74981   assert( z[0]!=0 );
   74982   if( z[1]==0 ){
   74983     /* Wildcard of the form "?".  Assign the next variable number */
   74984     assert( z[0]=='?' );
   74985     pExpr->iColumn = (ynVar)(++pParse->nVar);
   74986   }else{
   74987     ynVar x = 0;
   74988     u32 n = sqlite3Strlen30(z);
   74989     if( z[0]=='?' ){
   74990       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   74991       ** use it as the variable number */
   74992       i64 i;
   74993       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
   74994       pExpr->iColumn = x = (ynVar)i;
   74995       testcase( i==0 );
   74996       testcase( i==1 );
   74997       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   74998       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   74999       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   75000         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   75001             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   75002         x = 0;
   75003       }
   75004       if( i>pParse->nVar ){
   75005         pParse->nVar = (int)i;
   75006       }
   75007     }else{
   75008       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   75009       ** number as the prior appearance of the same name, or if the name
   75010       ** has never appeared before, reuse the same variable number
   75011       */
   75012       ynVar i;
   75013       for(i=0; i<pParse->nzVar; i++){
   75014         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
   75015           pExpr->iColumn = x = (ynVar)i+1;
   75016           break;
   75017         }
   75018       }
   75019       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
   75020     }
   75021     if( x>0 ){
   75022       if( x>pParse->nzVar ){
   75023         char **a;
   75024         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
   75025         if( a==0 ) return;  /* Error reported through db->mallocFailed */
   75026         pParse->azVar = a;
   75027         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
   75028         pParse->nzVar = x;
   75029       }
   75030       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
   75031         sqlite3DbFree(db, pParse->azVar[x-1]);
   75032         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
   75033       }
   75034     }
   75035   }
   75036   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   75037     sqlite3ErrorMsg(pParse, "too many SQL variables");
   75038   }
   75039 }
   75040 
   75041 /*
   75042 ** Recursively delete an expression tree.
   75043 */
   75044 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   75045   if( p==0 ) return;
   75046   /* Sanity check: Assert that the IntValue is non-negative if it exists */
   75047   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
   75048   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   75049     sqlite3ExprDelete(db, p->pLeft);
   75050     sqlite3ExprDelete(db, p->pRight);
   75051     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
   75052       sqlite3DbFree(db, p->u.zToken);
   75053     }
   75054     if( ExprHasProperty(p, EP_xIsSelect) ){
   75055       sqlite3SelectDelete(db, p->x.pSelect);
   75056     }else{
   75057       sqlite3ExprListDelete(db, p->x.pList);
   75058     }
   75059   }
   75060   if( !ExprHasProperty(p, EP_Static) ){
   75061     sqlite3DbFree(db, p);
   75062   }
   75063 }
   75064 
   75065 /*
   75066 ** Return the number of bytes allocated for the expression structure
   75067 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   75068 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   75069 */
   75070 static int exprStructSize(Expr *p){
   75071   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   75072   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   75073   return EXPR_FULLSIZE;
   75074 }
   75075 
   75076 /*
   75077 ** The dupedExpr*Size() routines each return the number of bytes required
   75078 ** to store a copy of an expression or expression tree.  They differ in
   75079 ** how much of the tree is measured.
   75080 **
   75081 **     dupedExprStructSize()     Size of only the Expr structure
   75082 **     dupedExprNodeSize()       Size of Expr + space for token
   75083 **     dupedExprSize()           Expr + token + subtree components
   75084 **
   75085 ***************************************************************************
   75086 **
   75087 ** The dupedExprStructSize() function returns two values OR-ed together:
   75088 ** (1) the space required for a copy of the Expr structure only and
   75089 ** (2) the EP_xxx flags that indicate what the structure size should be.
   75090 ** The return values is always one of:
   75091 **
   75092 **      EXPR_FULLSIZE
   75093 **      EXPR_REDUCEDSIZE   | EP_Reduced
   75094 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   75095 **
   75096 ** The size of the structure can be found by masking the return value
   75097 ** of this routine with 0xfff.  The flags can be found by masking the
   75098 ** return value with EP_Reduced|EP_TokenOnly.
   75099 **
   75100 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   75101 ** (unreduced) Expr objects as they or originally constructed by the parser.
   75102 ** During expression analysis, extra information is computed and moved into
   75103 ** later parts of teh Expr object and that extra information might get chopped
   75104 ** off if the expression is reduced.  Note also that it does not work to
   75105 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   75106 ** to reduce a pristine expression tree from the parser.  The implementation
   75107 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   75108 ** to enforce this constraint.
   75109 */
   75110 static int dupedExprStructSize(Expr *p, int flags){
   75111   int nSize;
   75112   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   75113   if( 0==(flags&EXPRDUP_REDUCE) ){
   75114     nSize = EXPR_FULLSIZE;
   75115   }else{
   75116     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   75117     assert( !ExprHasProperty(p, EP_FromJoin) );
   75118     assert( (p->flags2 & EP2_MallocedToken)==0 );
   75119     assert( (p->flags2 & EP2_Irreducible)==0 );
   75120     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
   75121       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   75122     }else{
   75123       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   75124     }
   75125   }
   75126   return nSize;
   75127 }
   75128 
   75129 /*
   75130 ** This function returns the space in bytes required to store the copy
   75131 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   75132 ** string is defined.)
   75133 */
   75134 static int dupedExprNodeSize(Expr *p, int flags){
   75135   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   75136   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   75137     nByte += sqlite3Strlen30(p->u.zToken)+1;
   75138   }
   75139   return ROUND8(nByte);
   75140 }
   75141 
   75142 /*
   75143 ** Return the number of bytes required to create a duplicate of the
   75144 ** expression passed as the first argument. The second argument is a
   75145 ** mask containing EXPRDUP_XXX flags.
   75146 **
   75147 ** The value returned includes space to create a copy of the Expr struct
   75148 ** itself and the buffer referred to by Expr.u.zToken, if any.
   75149 **
   75150 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   75151 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   75152 ** and Expr.pRight variables (but not for any structures pointed to or
   75153 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   75154 */
   75155 static int dupedExprSize(Expr *p, int flags){
   75156   int nByte = 0;
   75157   if( p ){
   75158     nByte = dupedExprNodeSize(p, flags);
   75159     if( flags&EXPRDUP_REDUCE ){
   75160       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   75161     }
   75162   }
   75163   return nByte;
   75164 }
   75165 
   75166 /*
   75167 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   75168 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   75169 ** to store the copy of expression p, the copies of p->u.zToken
   75170 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   75171 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   75172 ** portion of the buffer copied into by this function.
   75173 */
   75174 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   75175   Expr *pNew = 0;                      /* Value to return */
   75176   if( p ){
   75177     const int isReduced = (flags&EXPRDUP_REDUCE);
   75178     u8 *zAlloc;
   75179     u32 staticFlag = 0;
   75180 
   75181     assert( pzBuffer==0 || isReduced );
   75182 
   75183     /* Figure out where to write the new Expr structure. */
   75184     if( pzBuffer ){
   75185       zAlloc = *pzBuffer;
   75186       staticFlag = EP_Static;
   75187     }else{
   75188       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   75189     }
   75190     pNew = (Expr *)zAlloc;
   75191 
   75192     if( pNew ){
   75193       /* Set nNewSize to the size allocated for the structure pointed to
   75194       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   75195       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   75196       ** by the copy of the p->u.zToken string (if any).
   75197       */
   75198       const unsigned nStructSize = dupedExprStructSize(p, flags);
   75199       const int nNewSize = nStructSize & 0xfff;
   75200       int nToken;
   75201       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   75202         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   75203       }else{
   75204         nToken = 0;
   75205       }
   75206       if( isReduced ){
   75207         assert( ExprHasProperty(p, EP_Reduced)==0 );
   75208         memcpy(zAlloc, p, nNewSize);
   75209       }else{
   75210         int nSize = exprStructSize(p);
   75211         memcpy(zAlloc, p, nSize);
   75212         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   75213       }
   75214 
   75215       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   75216       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
   75217       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   75218       pNew->flags |= staticFlag;
   75219 
   75220       /* Copy the p->u.zToken string, if any. */
   75221       if( nToken ){
   75222         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   75223         memcpy(zToken, p->u.zToken, nToken);
   75224       }
   75225 
   75226       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   75227         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   75228         if( ExprHasProperty(p, EP_xIsSelect) ){
   75229           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   75230         }else{
   75231           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   75232         }
   75233       }
   75234 
   75235       /* Fill in pNew->pLeft and pNew->pRight. */
   75236       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   75237         zAlloc += dupedExprNodeSize(p, flags);
   75238         if( ExprHasProperty(pNew, EP_Reduced) ){
   75239           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   75240           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   75241         }
   75242         if( pzBuffer ){
   75243           *pzBuffer = zAlloc;
   75244         }
   75245       }else{
   75246         pNew->flags2 = 0;
   75247         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   75248           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   75249           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   75250         }
   75251       }
   75252 
   75253     }
   75254   }
   75255   return pNew;
   75256 }
   75257 
   75258 /*
   75259 ** The following group of routines make deep copies of expressions,
   75260 ** expression lists, ID lists, and select statements.  The copies can
   75261 ** be deleted (by being passed to their respective ...Delete() routines)
   75262 ** without effecting the originals.
   75263 **
   75264 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   75265 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   75266 ** by subsequent calls to sqlite*ListAppend() routines.
   75267 **
   75268 ** Any tables that the SrcList might point to are not duplicated.
   75269 **
   75270 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   75271 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   75272 ** truncated version of the usual Expr structure that will be stored as
   75273 ** part of the in-memory representation of the database schema.
   75274 */
   75275 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   75276   return exprDup(db, p, flags, 0);
   75277 }
   75278 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   75279   ExprList *pNew;
   75280   struct ExprList_item *pItem, *pOldItem;
   75281   int i;
   75282   if( p==0 ) return 0;
   75283   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   75284   if( pNew==0 ) return 0;
   75285   pNew->iECursor = 0;
   75286   pNew->nExpr = i = p->nExpr;
   75287   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
   75288   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
   75289   if( pItem==0 ){
   75290     sqlite3DbFree(db, pNew);
   75291     return 0;
   75292   }
   75293   pOldItem = p->a;
   75294   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   75295     Expr *pOldExpr = pOldItem->pExpr;
   75296     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   75297     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75298     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   75299     pItem->sortOrder = pOldItem->sortOrder;
   75300     pItem->done = 0;
   75301     pItem->iOrderByCol = pOldItem->iOrderByCol;
   75302     pItem->iAlias = pOldItem->iAlias;
   75303   }
   75304   return pNew;
   75305 }
   75306 
   75307 /*
   75308 ** If cursors, triggers, views and subqueries are all omitted from
   75309 ** the build, then none of the following routines, except for
   75310 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   75311 ** called with a NULL argument.
   75312 */
   75313 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   75314  || !defined(SQLITE_OMIT_SUBQUERY)
   75315 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   75316   SrcList *pNew;
   75317   int i;
   75318   int nByte;
   75319   if( p==0 ) return 0;
   75320   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   75321   pNew = sqlite3DbMallocRaw(db, nByte );
   75322   if( pNew==0 ) return 0;
   75323   pNew->nSrc = pNew->nAlloc = p->nSrc;
   75324   for(i=0; i<p->nSrc; i++){
   75325     struct SrcList_item *pNewItem = &pNew->a[i];
   75326     struct SrcList_item *pOldItem = &p->a[i];
   75327     Table *pTab;
   75328     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   75329     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75330     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   75331     pNewItem->jointype = pOldItem->jointype;
   75332     pNewItem->iCursor = pOldItem->iCursor;
   75333     pNewItem->addrFillSub = pOldItem->addrFillSub;
   75334     pNewItem->regReturn = pOldItem->regReturn;
   75335     pNewItem->isCorrelated = pOldItem->isCorrelated;
   75336     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   75337     pNewItem->notIndexed = pOldItem->notIndexed;
   75338     pNewItem->pIndex = pOldItem->pIndex;
   75339     pTab = pNewItem->pTab = pOldItem->pTab;
   75340     if( pTab ){
   75341       pTab->nRef++;
   75342     }
   75343     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   75344     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   75345     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   75346     pNewItem->colUsed = pOldItem->colUsed;
   75347   }
   75348   return pNew;
   75349 }
   75350 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   75351   IdList *pNew;
   75352   int i;
   75353   if( p==0 ) return 0;
   75354   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   75355   if( pNew==0 ) return 0;
   75356   pNew->nId = p->nId;
   75357   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   75358   if( pNew->a==0 ){
   75359     sqlite3DbFree(db, pNew);
   75360     return 0;
   75361   }
   75362   /* Note that because the size of the allocation for p->a[] is not
   75363   ** necessarily a power of two, sqlite3IdListAppend() may not be called
   75364   ** on the duplicate created by this function. */
   75365   for(i=0; i<p->nId; i++){
   75366     struct IdList_item *pNewItem = &pNew->a[i];
   75367     struct IdList_item *pOldItem = &p->a[i];
   75368     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75369     pNewItem->idx = pOldItem->idx;
   75370   }
   75371   return pNew;
   75372 }
   75373 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   75374   Select *pNew, *pPrior;
   75375   if( p==0 ) return 0;
   75376   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   75377   if( pNew==0 ) return 0;
   75378   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   75379   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   75380   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   75381   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   75382   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   75383   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   75384   pNew->op = p->op;
   75385   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   75386   if( pPrior ) pPrior->pNext = pNew;
   75387   pNew->pNext = 0;
   75388   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   75389   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   75390   pNew->iLimit = 0;
   75391   pNew->iOffset = 0;
   75392   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   75393   pNew->pRightmost = 0;
   75394   pNew->addrOpenEphm[0] = -1;
   75395   pNew->addrOpenEphm[1] = -1;
   75396   pNew->addrOpenEphm[2] = -1;
   75397   return pNew;
   75398 }
   75399 #else
   75400 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   75401   assert( p==0 );
   75402   return 0;
   75403 }
   75404 #endif
   75405 
   75406 
   75407 /*
   75408 ** Add a new element to the end of an expression list.  If pList is
   75409 ** initially NULL, then create a new expression list.
   75410 **
   75411 ** If a memory allocation error occurs, the entire list is freed and
   75412 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   75413 ** that the new entry was successfully appended.
   75414 */
   75415 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   75416   Parse *pParse,          /* Parsing context */
   75417   ExprList *pList,        /* List to which to append. Might be NULL */
   75418   Expr *pExpr             /* Expression to be appended. Might be NULL */
   75419 ){
   75420   sqlite3 *db = pParse->db;
   75421   if( pList==0 ){
   75422     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   75423     if( pList==0 ){
   75424       goto no_mem;
   75425     }
   75426     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
   75427     if( pList->a==0 ) goto no_mem;
   75428   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
   75429     struct ExprList_item *a;
   75430     assert( pList->nExpr>0 );
   75431     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
   75432     if( a==0 ){
   75433       goto no_mem;
   75434     }
   75435     pList->a = a;
   75436   }
   75437   assert( pList->a!=0 );
   75438   if( 1 ){
   75439     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   75440     memset(pItem, 0, sizeof(*pItem));
   75441     pItem->pExpr = pExpr;
   75442   }
   75443   return pList;
   75444 
   75445 no_mem:
   75446   /* Avoid leaking memory if malloc has failed. */
   75447   sqlite3ExprDelete(db, pExpr);
   75448   sqlite3ExprListDelete(db, pList);
   75449   return 0;
   75450 }
   75451 
   75452 /*
   75453 ** Set the ExprList.a[].zName element of the most recently added item
   75454 ** on the expression list.
   75455 **
   75456 ** pList might be NULL following an OOM error.  But pName should never be
   75457 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   75458 ** is set.
   75459 */
   75460 SQLITE_PRIVATE void sqlite3ExprListSetName(
   75461   Parse *pParse,          /* Parsing context */
   75462   ExprList *pList,        /* List to which to add the span. */
   75463   Token *pName,           /* Name to be added */
   75464   int dequote             /* True to cause the name to be dequoted */
   75465 ){
   75466   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   75467   if( pList ){
   75468     struct ExprList_item *pItem;
   75469     assert( pList->nExpr>0 );
   75470     pItem = &pList->a[pList->nExpr-1];
   75471     assert( pItem->zName==0 );
   75472     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   75473     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   75474   }
   75475 }
   75476 
   75477 /*
   75478 ** Set the ExprList.a[].zSpan element of the most recently added item
   75479 ** on the expression list.
   75480 **
   75481 ** pList might be NULL following an OOM error.  But pSpan should never be
   75482 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   75483 ** is set.
   75484 */
   75485 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   75486   Parse *pParse,          /* Parsing context */
   75487   ExprList *pList,        /* List to which to add the span. */
   75488   ExprSpan *pSpan         /* The span to be added */
   75489 ){
   75490   sqlite3 *db = pParse->db;
   75491   assert( pList!=0 || db->mallocFailed!=0 );
   75492   if( pList ){
   75493     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   75494     assert( pList->nExpr>0 );
   75495     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   75496     sqlite3DbFree(db, pItem->zSpan);
   75497     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   75498                                     (int)(pSpan->zEnd - pSpan->zStart));
   75499   }
   75500 }
   75501 
   75502 /*
   75503 ** If the expression list pEList contains more than iLimit elements,
   75504 ** leave an error message in pParse.
   75505 */
   75506 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   75507   Parse *pParse,
   75508   ExprList *pEList,
   75509   const char *zObject
   75510 ){
   75511   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   75512   testcase( pEList && pEList->nExpr==mx );
   75513   testcase( pEList && pEList->nExpr==mx+1 );
   75514   if( pEList && pEList->nExpr>mx ){
   75515     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   75516   }
   75517 }
   75518 
   75519 /*
   75520 ** Delete an entire expression list.
   75521 */
   75522 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   75523   int i;
   75524   struct ExprList_item *pItem;
   75525   if( pList==0 ) return;
   75526   assert( pList->a!=0 || pList->nExpr==0 );
   75527   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   75528     sqlite3ExprDelete(db, pItem->pExpr);
   75529     sqlite3DbFree(db, pItem->zName);
   75530     sqlite3DbFree(db, pItem->zSpan);
   75531   }
   75532   sqlite3DbFree(db, pList->a);
   75533   sqlite3DbFree(db, pList);
   75534 }
   75535 
   75536 /*
   75537 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   75538 ** to an integer.  These routines are checking an expression to see
   75539 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   75540 ** not constant.
   75541 **
   75542 ** These callback routines are used to implement the following:
   75543 **
   75544 **     sqlite3ExprIsConstant()
   75545 **     sqlite3ExprIsConstantNotJoin()
   75546 **     sqlite3ExprIsConstantOrFunction()
   75547 **
   75548 */
   75549 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   75550 
   75551   /* If pWalker->u.i is 3 then any term of the expression that comes from
   75552   ** the ON or USING clauses of a join disqualifies the expression
   75553   ** from being considered constant. */
   75554   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
   75555     pWalker->u.i = 0;
   75556     return WRC_Abort;
   75557   }
   75558 
   75559   switch( pExpr->op ){
   75560     /* Consider functions to be constant if all their arguments are constant
   75561     ** and pWalker->u.i==2 */
   75562     case TK_FUNCTION:
   75563       if( pWalker->u.i==2 ) return 0;
   75564       /* Fall through */
   75565     case TK_ID:
   75566     case TK_COLUMN:
   75567     case TK_AGG_FUNCTION:
   75568     case TK_AGG_COLUMN:
   75569       testcase( pExpr->op==TK_ID );
   75570       testcase( pExpr->op==TK_COLUMN );
   75571       testcase( pExpr->op==TK_AGG_FUNCTION );
   75572       testcase( pExpr->op==TK_AGG_COLUMN );
   75573       pWalker->u.i = 0;
   75574       return WRC_Abort;
   75575     default:
   75576       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   75577       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   75578       return WRC_Continue;
   75579   }
   75580 }
   75581 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   75582   UNUSED_PARAMETER(NotUsed);
   75583   pWalker->u.i = 0;
   75584   return WRC_Abort;
   75585 }
   75586 static int exprIsConst(Expr *p, int initFlag){
   75587   Walker w;
   75588   w.u.i = initFlag;
   75589   w.xExprCallback = exprNodeIsConstant;
   75590   w.xSelectCallback = selectNodeIsConstant;
   75591   sqlite3WalkExpr(&w, p);
   75592   return w.u.i;
   75593 }
   75594 
   75595 /*
   75596 ** Walk an expression tree.  Return 1 if the expression is constant
   75597 ** and 0 if it involves variables or function calls.
   75598 **
   75599 ** For the purposes of this function, a double-quoted string (ex: "abc")
   75600 ** is considered a variable but a single-quoted string (ex: 'abc') is
   75601 ** a constant.
   75602 */
   75603 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   75604   return exprIsConst(p, 1);
   75605 }
   75606 
   75607 /*
   75608 ** Walk an expression tree.  Return 1 if the expression is constant
   75609 ** that does no originate from the ON or USING clauses of a join.
   75610 ** Return 0 if it involves variables or function calls or terms from
   75611 ** an ON or USING clause.
   75612 */
   75613 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   75614   return exprIsConst(p, 3);
   75615 }
   75616 
   75617 /*
   75618 ** Walk an expression tree.  Return 1 if the expression is constant
   75619 ** or a function call with constant arguments.  Return and 0 if there
   75620 ** are any variables.
   75621 **
   75622 ** For the purposes of this function, a double-quoted string (ex: "abc")
   75623 ** is considered a variable but a single-quoted string (ex: 'abc') is
   75624 ** a constant.
   75625 */
   75626 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   75627   return exprIsConst(p, 2);
   75628 }
   75629 
   75630 /*
   75631 ** If the expression p codes a constant integer that is small enough
   75632 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   75633 ** in *pValue.  If the expression is not an integer or if it is too big
   75634 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   75635 */
   75636 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   75637   int rc = 0;
   75638 
   75639   /* If an expression is an integer literal that fits in a signed 32-bit
   75640   ** integer, then the EP_IntValue flag will have already been set */
   75641   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
   75642            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
   75643 
   75644   if( p->flags & EP_IntValue ){
   75645     *pValue = p->u.iValue;
   75646     return 1;
   75647   }
   75648   switch( p->op ){
   75649     case TK_UPLUS: {
   75650       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   75651       break;
   75652     }
   75653     case TK_UMINUS: {
   75654       int v;
   75655       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   75656         *pValue = -v;
   75657         rc = 1;
   75658       }
   75659       break;
   75660     }
   75661     default: break;
   75662   }
   75663   return rc;
   75664 }
   75665 
   75666 /*
   75667 ** Return FALSE if there is no chance that the expression can be NULL.
   75668 **
   75669 ** If the expression might be NULL or if the expression is too complex
   75670 ** to tell return TRUE.
   75671 **
   75672 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   75673 ** when we know that a value cannot be NULL.  Hence, a false positive
   75674 ** (returning TRUE when in fact the expression can never be NULL) might
   75675 ** be a small performance hit but is otherwise harmless.  On the other
   75676 ** hand, a false negative (returning FALSE when the result could be NULL)
   75677 ** will likely result in an incorrect answer.  So when in doubt, return
   75678 ** TRUE.
   75679 */
   75680 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   75681   u8 op;
   75682   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   75683   op = p->op;
   75684   if( op==TK_REGISTER ) op = p->op2;
   75685   switch( op ){
   75686     case TK_INTEGER:
   75687     case TK_STRING:
   75688     case TK_FLOAT:
   75689     case TK_BLOB:
   75690       return 0;
   75691     default:
   75692       return 1;
   75693   }
   75694 }
   75695 
   75696 /*
   75697 ** Generate an OP_IsNull instruction that tests register iReg and jumps
   75698 ** to location iDest if the value in iReg is NULL.  The value in iReg
   75699 ** was computed by pExpr.  If we can look at pExpr at compile-time and
   75700 ** determine that it can never generate a NULL, then the OP_IsNull operation
   75701 ** can be omitted.
   75702 */
   75703 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
   75704   Vdbe *v,            /* The VDBE under construction */
   75705   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
   75706   int iReg,           /* Test the value in this register for NULL */
   75707   int iDest           /* Jump here if the value is null */
   75708 ){
   75709   if( sqlite3ExprCanBeNull(pExpr) ){
   75710     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
   75711   }
   75712 }
   75713 
   75714 /*
   75715 ** Return TRUE if the given expression is a constant which would be
   75716 ** unchanged by OP_Affinity with the affinity given in the second
   75717 ** argument.
   75718 **
   75719 ** This routine is used to determine if the OP_Affinity operation
   75720 ** can be omitted.  When in doubt return FALSE.  A false negative
   75721 ** is harmless.  A false positive, however, can result in the wrong
   75722 ** answer.
   75723 */
   75724 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   75725   u8 op;
   75726   if( aff==SQLITE_AFF_NONE ) return 1;
   75727   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   75728   op = p->op;
   75729   if( op==TK_REGISTER ) op = p->op2;
   75730   switch( op ){
   75731     case TK_INTEGER: {
   75732       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   75733     }
   75734     case TK_FLOAT: {
   75735       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   75736     }
   75737     case TK_STRING: {
   75738       return aff==SQLITE_AFF_TEXT;
   75739     }
   75740     case TK_BLOB: {
   75741       return 1;
   75742     }
   75743     case TK_COLUMN: {
   75744       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   75745       return p->iColumn<0
   75746           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   75747     }
   75748     default: {
   75749       return 0;
   75750     }
   75751   }
   75752 }
   75753 
   75754 /*
   75755 ** Return TRUE if the given string is a row-id column name.
   75756 */
   75757 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   75758   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   75759   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   75760   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   75761   return 0;
   75762 }
   75763 
   75764 /*
   75765 ** Return true if we are able to the IN operator optimization on a
   75766 ** query of the form
   75767 **
   75768 **       x IN (SELECT ...)
   75769 **
   75770 ** Where the SELECT... clause is as specified by the parameter to this
   75771 ** routine.
   75772 **
   75773 ** The Select object passed in has already been preprocessed and no
   75774 ** errors have been found.
   75775 */
   75776 #ifndef SQLITE_OMIT_SUBQUERY
   75777 static int isCandidateForInOpt(Select *p){
   75778   SrcList *pSrc;
   75779   ExprList *pEList;
   75780   Table *pTab;
   75781   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   75782   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   75783   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   75784     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   75785     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   75786     return 0; /* No DISTINCT keyword and no aggregate functions */
   75787   }
   75788   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   75789   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   75790   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   75791   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   75792   pSrc = p->pSrc;
   75793   assert( pSrc!=0 );
   75794   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   75795   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   75796   pTab = pSrc->a[0].pTab;
   75797   if( NEVER(pTab==0) ) return 0;
   75798   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   75799   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   75800   pEList = p->pEList;
   75801   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   75802   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   75803   return 1;
   75804 }
   75805 #endif /* SQLITE_OMIT_SUBQUERY */
   75806 
   75807 /*
   75808 ** Code an OP_Once instruction and allocate space for its flag. Return the
   75809 ** address of the new instruction.
   75810 */
   75811 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
   75812   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   75813   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
   75814 }
   75815 
   75816 /*
   75817 ** This function is used by the implementation of the IN (...) operator.
   75818 ** It's job is to find or create a b-tree structure that may be used
   75819 ** either to test for membership of the (...) set or to iterate through
   75820 ** its members, skipping duplicates.
   75821 **
   75822 ** The index of the cursor opened on the b-tree (database table, database index
   75823 ** or ephermal table) is stored in pX->iTable before this function returns.
   75824 ** The returned value of this function indicates the b-tree type, as follows:
   75825 **
   75826 **   IN_INDEX_ROWID - The cursor was opened on a database table.
   75827 **   IN_INDEX_INDEX - The cursor was opened on a database index.
   75828 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
   75829 **                    populated epheremal table.
   75830 **
   75831 ** An existing b-tree may only be used if the SELECT is of the simple
   75832 ** form:
   75833 **
   75834 **     SELECT <column> FROM <table>
   75835 **
   75836 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
   75837 ** through the set members, skipping any duplicates. In this case an
   75838 ** epheremal table must be used unless the selected <column> is guaranteed
   75839 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   75840 ** has a UNIQUE constraint or UNIQUE index.
   75841 **
   75842 ** If the prNotFound parameter is not 0, then the b-tree will be used
   75843 ** for fast set membership tests. In this case an epheremal table must
   75844 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   75845 ** be found with <column> as its left-most column.
   75846 **
   75847 ** When the b-tree is being used for membership tests, the calling function
   75848 ** needs to know whether or not the structure contains an SQL NULL
   75849 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
   75850 ** If there is any chance that the (...) might contain a NULL value at
   75851 ** runtime, then a register is allocated and the register number written
   75852 ** to *prNotFound. If there is no chance that the (...) contains a
   75853 ** NULL value, then *prNotFound is left unchanged.
   75854 **
   75855 ** If a register is allocated and its location stored in *prNotFound, then
   75856 ** its initial value is NULL.  If the (...) does not remain constant
   75857 ** for the duration of the query (i.e. the SELECT within the (...)
   75858 ** is a correlated subquery) then the value of the allocated register is
   75859 ** reset to NULL each time the subquery is rerun. This allows the
   75860 ** caller to use vdbe code equivalent to the following:
   75861 **
   75862 **   if( register==NULL ){
   75863 **     has_null = <test if data structure contains null>
   75864 **     register = 1
   75865 **   }
   75866 **
   75867 ** in order to avoid running the <test if data structure contains null>
   75868 ** test more often than is necessary.
   75869 */
   75870 #ifndef SQLITE_OMIT_SUBQUERY
   75871 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
   75872   Select *p;                            /* SELECT to the right of IN operator */
   75873   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   75874   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   75875   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
   75876   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
   75877 
   75878   assert( pX->op==TK_IN );
   75879 
   75880   /* Check to see if an existing table or index can be used to
   75881   ** satisfy the query.  This is preferable to generating a new
   75882   ** ephemeral table.
   75883   */
   75884   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   75885   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   75886     sqlite3 *db = pParse->db;              /* Database connection */
   75887     Table *pTab;                           /* Table <table>. */
   75888     Expr *pExpr;                           /* Expression <column> */
   75889     int iCol;                              /* Index of column <column> */
   75890     int iDb;                               /* Database idx for pTab */
   75891 
   75892     assert( p );                        /* Because of isCandidateForInOpt(p) */
   75893     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
   75894     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
   75895     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
   75896     pTab = p->pSrc->a[0].pTab;
   75897     pExpr = p->pEList->a[0].pExpr;
   75898     iCol = pExpr->iColumn;
   75899 
   75900     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
   75901     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   75902     sqlite3CodeVerifySchema(pParse, iDb);
   75903     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   75904 
   75905     /* This function is only called from two places. In both cases the vdbe
   75906     ** has already been allocated. So assume sqlite3GetVdbe() is always
   75907     ** successful here.
   75908     */
   75909     assert(v);
   75910     if( iCol<0 ){
   75911       int iAddr;
   75912 
   75913       iAddr = sqlite3CodeOnce(pParse);
   75914 
   75915       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   75916       eType = IN_INDEX_ROWID;
   75917 
   75918       sqlite3VdbeJumpHere(v, iAddr);
   75919     }else{
   75920       Index *pIdx;                         /* Iterator variable */
   75921 
   75922       /* The collation sequence used by the comparison. If an index is to
   75923       ** be used in place of a temp-table, it must be ordered according
   75924       ** to this collation sequence.  */
   75925       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   75926 
   75927       /* Check that the affinity that will be used to perform the
   75928       ** comparison is the same as the affinity of the column. If
   75929       ** it is not, it is not possible to use any index.
   75930       */
   75931       char aff = comparisonAffinity(pX);
   75932       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
   75933 
   75934       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   75935         if( (pIdx->aiColumn[0]==iCol)
   75936          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   75937          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
   75938         ){
   75939           int iAddr;
   75940           char *pKey;
   75941 
   75942           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
   75943           iAddr = sqlite3CodeOnce(pParse);
   75944 
   75945           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
   75946                                pKey,P4_KEYINFO_HANDOFF);
   75947           VdbeComment((v, "%s", pIdx->zName));
   75948           eType = IN_INDEX_INDEX;
   75949 
   75950           sqlite3VdbeJumpHere(v, iAddr);
   75951           if( prNotFound && !pTab->aCol[iCol].notNull ){
   75952             *prNotFound = ++pParse->nMem;
   75953             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
   75954           }
   75955         }
   75956       }
   75957     }
   75958   }
   75959 
   75960   if( eType==0 ){
   75961     /* Could not found an existing table or index to use as the RHS b-tree.
   75962     ** We will have to generate an ephemeral table to do the job.
   75963     */
   75964     double savedNQueryLoop = pParse->nQueryLoop;
   75965     int rMayHaveNull = 0;
   75966     eType = IN_INDEX_EPH;
   75967     if( prNotFound ){
   75968       *prNotFound = rMayHaveNull = ++pParse->nMem;
   75969       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
   75970     }else{
   75971       testcase( pParse->nQueryLoop>(double)1 );
   75972       pParse->nQueryLoop = (double)1;
   75973       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
   75974         eType = IN_INDEX_ROWID;
   75975       }
   75976     }
   75977     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   75978     pParse->nQueryLoop = savedNQueryLoop;
   75979   }else{
   75980     pX->iTable = iTab;
   75981   }
   75982   return eType;
   75983 }
   75984 #endif
   75985 
   75986 /*
   75987 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   75988 ** or IN operators.  Examples:
   75989 **
   75990 **     (SELECT a FROM b)          -- subquery
   75991 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   75992 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   75993 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   75994 **
   75995 ** The pExpr parameter describes the expression that contains the IN
   75996 ** operator or subquery.
   75997 **
   75998 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   75999 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   76000 ** to some integer key column of a table B-Tree. In this case, use an
   76001 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   76002 ** (slower) variable length keys B-Tree.
   76003 **
   76004 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   76005 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   76006 ** Furthermore, the IN is in a WHERE clause and that we really want
   76007 ** to iterate over the RHS of the IN operator in order to quickly locate
   76008 ** all corresponding LHS elements.  All this routine does is initialize
   76009 ** the register given by rMayHaveNull to NULL.  Calling routines will take
   76010 ** care of changing this register value to non-NULL if the RHS is NULL-free.
   76011 **
   76012 ** If rMayHaveNull is zero, that means that the subquery is being used
   76013 ** for membership testing only.  There is no need to initialize any
   76014 ** registers to indicate the presense or absence of NULLs on the RHS.
   76015 **
   76016 ** For a SELECT or EXISTS operator, return the register that holds the
   76017 ** result.  For IN operators or if an error occurs, the return value is 0.
   76018 */
   76019 #ifndef SQLITE_OMIT_SUBQUERY
   76020 SQLITE_PRIVATE int sqlite3CodeSubselect(
   76021   Parse *pParse,          /* Parsing context */
   76022   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   76023   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
   76024   int isRowid             /* If true, LHS of IN operator is a rowid */
   76025 ){
   76026   int testAddr = -1;                      /* One-time test address */
   76027   int rReg = 0;                           /* Register storing resulting */
   76028   Vdbe *v = sqlite3GetVdbe(pParse);
   76029   if( NEVER(v==0) ) return 0;
   76030   sqlite3ExprCachePush(pParse);
   76031 
   76032   /* This code must be run in its entirety every time it is encountered
   76033   ** if any of the following is true:
   76034   **
   76035   **    *  The right-hand side is a correlated subquery
   76036   **    *  The right-hand side is an expression list containing variables
   76037   **    *  We are inside a trigger
   76038   **
   76039   ** If all of the above are false, then we can run this code just once
   76040   ** save the results, and reuse the same result on subsequent invocations.
   76041   */
   76042   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
   76043     testAddr = sqlite3CodeOnce(pParse);
   76044   }
   76045 
   76046 #ifndef SQLITE_OMIT_EXPLAIN
   76047   if( pParse->explain==2 ){
   76048     char *zMsg = sqlite3MPrintf(
   76049         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
   76050         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
   76051     );
   76052     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   76053   }
   76054 #endif
   76055 
   76056   switch( pExpr->op ){
   76057     case TK_IN: {
   76058       char affinity;              /* Affinity of the LHS of the IN */
   76059       KeyInfo keyInfo;            /* Keyinfo for the generated table */
   76060       int addr;                   /* Address of OP_OpenEphemeral instruction */
   76061       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   76062 
   76063       if( rMayHaveNull ){
   76064         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
   76065       }
   76066 
   76067       affinity = sqlite3ExprAffinity(pLeft);
   76068 
   76069       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   76070       ** expression it is handled the same way.  An ephemeral table is
   76071       ** filled with single-field index keys representing the results
   76072       ** from the SELECT or the <exprlist>.
   76073       **
   76074       ** If the 'x' expression is a column value, or the SELECT...
   76075       ** statement returns a column value, then the affinity of that
   76076       ** column is used to build the index keys. If both 'x' and the
   76077       ** SELECT... statement are columns, then numeric affinity is used
   76078       ** if either column has NUMERIC or INTEGER affinity. If neither
   76079       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   76080       ** is used.
   76081       */
   76082       pExpr->iTable = pParse->nTab++;
   76083       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   76084       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   76085       memset(&keyInfo, 0, sizeof(keyInfo));
   76086       keyInfo.nField = 1;
   76087 
   76088       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   76089         /* Case 1:     expr IN (SELECT ...)
   76090         **
   76091         ** Generate code to write the results of the select into the temporary
   76092         ** table allocated and opened above.
   76093         */
   76094         SelectDest dest;
   76095         ExprList *pEList;
   76096 
   76097         assert( !isRowid );
   76098         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   76099         dest.affinity = (u8)affinity;
   76100         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   76101         pExpr->x.pSelect->iLimit = 0;
   76102         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
   76103           return 0;
   76104         }
   76105         pEList = pExpr->x.pSelect->pEList;
   76106         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
   76107           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   76108               pEList->a[0].pExpr);
   76109         }
   76110       }else if( ALWAYS(pExpr->x.pList!=0) ){
   76111         /* Case 2:     expr IN (exprlist)
   76112         **
   76113         ** For each expression, build an index key from the evaluation and
   76114         ** store it in the temporary table. If <expr> is a column, then use
   76115         ** that columns affinity when building index keys. If <expr> is not
   76116         ** a column, use numeric affinity.
   76117         */
   76118         int i;
   76119         ExprList *pList = pExpr->x.pList;
   76120         struct ExprList_item *pItem;
   76121         int r1, r2, r3;
   76122 
   76123         if( !affinity ){
   76124           affinity = SQLITE_AFF_NONE;
   76125         }
   76126         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   76127 
   76128         /* Loop through each expression in <exprlist>. */
   76129         r1 = sqlite3GetTempReg(pParse);
   76130         r2 = sqlite3GetTempReg(pParse);
   76131         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   76132         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   76133           Expr *pE2 = pItem->pExpr;
   76134           int iValToIns;
   76135 
   76136           /* If the expression is not constant then we will need to
   76137           ** disable the test that was generated above that makes sure
   76138           ** this code only executes once.  Because for a non-constant
   76139           ** expression we need to rerun this code each time.
   76140           */
   76141           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
   76142             sqlite3VdbeChangeToNoop(v, testAddr);
   76143             testAddr = -1;
   76144           }
   76145 
   76146           /* Evaluate the expression and insert it into the temp table */
   76147           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   76148             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   76149           }else{
   76150             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   76151             if( isRowid ){
   76152               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   76153                                 sqlite3VdbeCurrentAddr(v)+2);
   76154               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   76155             }else{
   76156               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   76157               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   76158               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   76159             }
   76160           }
   76161         }
   76162         sqlite3ReleaseTempReg(pParse, r1);
   76163         sqlite3ReleaseTempReg(pParse, r2);
   76164       }
   76165       if( !isRowid ){
   76166         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
   76167       }
   76168       break;
   76169     }
   76170 
   76171     case TK_EXISTS:
   76172     case TK_SELECT:
   76173     default: {
   76174       /* If this has to be a scalar SELECT.  Generate code to put the
   76175       ** value of this select in a memory cell and record the number
   76176       ** of the memory cell in iColumn.  If this is an EXISTS, write
   76177       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   76178       ** and record that memory cell in iColumn.
   76179       */
   76180       Select *pSel;                         /* SELECT statement to encode */
   76181       SelectDest dest;                      /* How to deal with SELECt result */
   76182 
   76183       testcase( pExpr->op==TK_EXISTS );
   76184       testcase( pExpr->op==TK_SELECT );
   76185       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   76186 
   76187       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   76188       pSel = pExpr->x.pSelect;
   76189       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   76190       if( pExpr->op==TK_SELECT ){
   76191         dest.eDest = SRT_Mem;
   76192         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
   76193         VdbeComment((v, "Init subquery result"));
   76194       }else{
   76195         dest.eDest = SRT_Exists;
   76196         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
   76197         VdbeComment((v, "Init EXISTS result"));
   76198       }
   76199       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   76200       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
   76201                                   &sqlite3IntTokens[1]);
   76202       pSel->iLimit = 0;
   76203       if( sqlite3Select(pParse, pSel, &dest) ){
   76204         return 0;
   76205       }
   76206       rReg = dest.iParm;
   76207       ExprSetIrreducible(pExpr);
   76208       break;
   76209     }
   76210   }
   76211 
   76212   if( testAddr>=0 ){
   76213     sqlite3VdbeJumpHere(v, testAddr);
   76214   }
   76215   sqlite3ExprCachePop(pParse, 1);
   76216 
   76217   return rReg;
   76218 }
   76219 #endif /* SQLITE_OMIT_SUBQUERY */
   76220 
   76221 #ifndef SQLITE_OMIT_SUBQUERY
   76222 /*
   76223 ** Generate code for an IN expression.
   76224 **
   76225 **      x IN (SELECT ...)
   76226 **      x IN (value, value, ...)
   76227 **
   76228 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   76229 ** is an array of zero or more values.  The expression is true if the LHS is
   76230 ** contained within the RHS.  The value of the expression is unknown (NULL)
   76231 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   76232 ** RHS contains one or more NULL values.
   76233 **
   76234 ** This routine generates code will jump to destIfFalse if the LHS is not
   76235 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   76236 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   76237 ** within the RHS then fall through.
   76238 */
   76239 static void sqlite3ExprCodeIN(
   76240   Parse *pParse,        /* Parsing and code generating context */
   76241   Expr *pExpr,          /* The IN expression */
   76242   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   76243   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   76244 ){
   76245   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   76246   char affinity;        /* Comparison affinity to use */
   76247   int eType;            /* Type of the RHS */
   76248   int r1;               /* Temporary use register */
   76249   Vdbe *v;              /* Statement under construction */
   76250 
   76251   /* Compute the RHS.   After this step, the table with cursor
   76252   ** pExpr->iTable will contains the values that make up the RHS.
   76253   */
   76254   v = pParse->pVdbe;
   76255   assert( v!=0 );       /* OOM detected prior to this routine */
   76256   VdbeNoopComment((v, "begin IN expr"));
   76257   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
   76258 
   76259   /* Figure out the affinity to use to create a key from the results
   76260   ** of the expression. affinityStr stores a static string suitable for
   76261   ** P4 of OP_MakeRecord.
   76262   */
   76263   affinity = comparisonAffinity(pExpr);
   76264 
   76265   /* Code the LHS, the <expr> from "<expr> IN (...)".
   76266   */
   76267   sqlite3ExprCachePush(pParse);
   76268   r1 = sqlite3GetTempReg(pParse);
   76269   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   76270 
   76271   /* If the LHS is NULL, then the result is either false or NULL depending
   76272   ** on whether the RHS is empty or not, respectively.
   76273   */
   76274   if( destIfNull==destIfFalse ){
   76275     /* Shortcut for the common case where the false and NULL outcomes are
   76276     ** the same. */
   76277     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
   76278   }else{
   76279     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
   76280     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   76281     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   76282     sqlite3VdbeJumpHere(v, addr1);
   76283   }
   76284 
   76285   if( eType==IN_INDEX_ROWID ){
   76286     /* In this case, the RHS is the ROWID of table b-tree
   76287     */
   76288     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
   76289     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   76290   }else{
   76291     /* In this case, the RHS is an index b-tree.
   76292     */
   76293     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   76294 
   76295     /* If the set membership test fails, then the result of the
   76296     ** "x IN (...)" expression must be either 0 or NULL. If the set
   76297     ** contains no NULL values, then the result is 0. If the set
   76298     ** contains one or more NULL values, then the result of the
   76299     ** expression is also NULL.
   76300     */
   76301     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
   76302       /* This branch runs if it is known at compile time that the RHS
   76303       ** cannot contain NULL values. This happens as the result
   76304       ** of a "NOT NULL" constraint in the database schema.
   76305       **
   76306       ** Also run this branch if NULL is equivalent to FALSE
   76307       ** for this particular IN operator.
   76308       */
   76309       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   76310 
   76311     }else{
   76312       /* In this branch, the RHS of the IN might contain a NULL and
   76313       ** the presence of a NULL on the RHS makes a difference in the
   76314       ** outcome.
   76315       */
   76316       int j1, j2, j3;
   76317 
   76318       /* First check to see if the LHS is contained in the RHS.  If so,
   76319       ** then the presence of NULLs in the RHS does not matter, so jump
   76320       ** over all of the code that follows.
   76321       */
   76322       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   76323 
   76324       /* Here we begin generating code that runs if the LHS is not
   76325       ** contained within the RHS.  Generate additional code that
   76326       ** tests the RHS for NULLs.  If the RHS contains a NULL then
   76327       ** jump to destIfNull.  If there are no NULLs in the RHS then
   76328       ** jump to destIfFalse.
   76329       */
   76330       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
   76331       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
   76332       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
   76333       sqlite3VdbeJumpHere(v, j3);
   76334       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
   76335       sqlite3VdbeJumpHere(v, j2);
   76336 
   76337       /* Jump to the appropriate target depending on whether or not
   76338       ** the RHS contains a NULL
   76339       */
   76340       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
   76341       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   76342 
   76343       /* The OP_Found at the top of this branch jumps here when true,
   76344       ** causing the overall IN expression evaluation to fall through.
   76345       */
   76346       sqlite3VdbeJumpHere(v, j1);
   76347     }
   76348   }
   76349   sqlite3ReleaseTempReg(pParse, r1);
   76350   sqlite3ExprCachePop(pParse, 1);
   76351   VdbeComment((v, "end IN expr"));
   76352 }
   76353 #endif /* SQLITE_OMIT_SUBQUERY */
   76354 
   76355 /*
   76356 ** Duplicate an 8-byte value
   76357 */
   76358 static char *dup8bytes(Vdbe *v, const char *in){
   76359   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   76360   if( out ){
   76361     memcpy(out, in, 8);
   76362   }
   76363   return out;
   76364 }
   76365 
   76366 #ifndef SQLITE_OMIT_FLOATING_POINT
   76367 /*
   76368 ** Generate an instruction that will put the floating point
   76369 ** value described by z[0..n-1] into register iMem.
   76370 **
   76371 ** The z[] string will probably not be zero-terminated.  But the
   76372 ** z[n] character is guaranteed to be something that does not look
   76373 ** like the continuation of the number.
   76374 */
   76375 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   76376   if( ALWAYS(z!=0) ){
   76377     double value;
   76378     char *zV;
   76379     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   76380     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   76381     if( negateFlag ) value = -value;
   76382     zV = dup8bytes(v, (char*)&value);
   76383     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   76384   }
   76385 }
   76386 #endif
   76387 
   76388 
   76389 /*
   76390 ** Generate an instruction that will put the integer describe by
   76391 ** text z[0..n-1] into register iMem.
   76392 **
   76393 ** Expr.u.zToken is always UTF8 and zero-terminated.
   76394 */
   76395 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   76396   Vdbe *v = pParse->pVdbe;
   76397   if( pExpr->flags & EP_IntValue ){
   76398     int i = pExpr->u.iValue;
   76399     assert( i>=0 );
   76400     if( negFlag ) i = -i;
   76401     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   76402   }else{
   76403     int c;
   76404     i64 value;
   76405     const char *z = pExpr->u.zToken;
   76406     assert( z!=0 );
   76407     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   76408     if( c==0 || (c==2 && negFlag) ){
   76409       char *zV;
   76410       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
   76411       zV = dup8bytes(v, (char*)&value);
   76412       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   76413     }else{
   76414 #ifdef SQLITE_OMIT_FLOATING_POINT
   76415       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   76416 #else
   76417       codeReal(v, z, negFlag, iMem);
   76418 #endif
   76419     }
   76420   }
   76421 }
   76422 
   76423 /*
   76424 ** Clear a cache entry.
   76425 */
   76426 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   76427   if( p->tempReg ){
   76428     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   76429       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   76430     }
   76431     p->tempReg = 0;
   76432   }
   76433 }
   76434 
   76435 
   76436 /*
   76437 ** Record in the column cache that a particular column from a
   76438 ** particular table is stored in a particular register.
   76439 */
   76440 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   76441   int i;
   76442   int minLru;
   76443   int idxLru;
   76444   struct yColCache *p;
   76445 
   76446   assert( iReg>0 );  /* Register numbers are always positive */
   76447   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   76448 
   76449   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   76450   ** for testing only - to verify that SQLite always gets the same answer
   76451   ** with and without the column cache.
   76452   */
   76453   if( pParse->db->flags & SQLITE_ColumnCache ) return;
   76454 
   76455   /* First replace any existing entry.
   76456   **
   76457   ** Actually, the way the column cache is currently used, we are guaranteed
   76458   ** that the object will never already be in cache.  Verify this guarantee.
   76459   */
   76460 #ifndef NDEBUG
   76461   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76462 #if 0 /* This code wold remove the entry from the cache if it existed */
   76463     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
   76464       cacheEntryClear(pParse, p);
   76465       p->iLevel = pParse->iCacheLevel;
   76466       p->iReg = iReg;
   76467       p->lru = pParse->iCacheCnt++;
   76468       return;
   76469     }
   76470 #endif
   76471     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   76472   }
   76473 #endif
   76474 
   76475   /* Find an empty slot and replace it */
   76476   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76477     if( p->iReg==0 ){
   76478       p->iLevel = pParse->iCacheLevel;
   76479       p->iTable = iTab;
   76480       p->iColumn = iCol;
   76481       p->iReg = iReg;
   76482       p->tempReg = 0;
   76483       p->lru = pParse->iCacheCnt++;
   76484       return;
   76485     }
   76486   }
   76487 
   76488   /* Replace the last recently used */
   76489   minLru = 0x7fffffff;
   76490   idxLru = -1;
   76491   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76492     if( p->lru<minLru ){
   76493       idxLru = i;
   76494       minLru = p->lru;
   76495     }
   76496   }
   76497   if( ALWAYS(idxLru>=0) ){
   76498     p = &pParse->aColCache[idxLru];
   76499     p->iLevel = pParse->iCacheLevel;
   76500     p->iTable = iTab;
   76501     p->iColumn = iCol;
   76502     p->iReg = iReg;
   76503     p->tempReg = 0;
   76504     p->lru = pParse->iCacheCnt++;
   76505     return;
   76506   }
   76507 }
   76508 
   76509 /*
   76510 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   76511 ** Purge the range of registers from the column cache.
   76512 */
   76513 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   76514   int i;
   76515   int iLast = iReg + nReg - 1;
   76516   struct yColCache *p;
   76517   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76518     int r = p->iReg;
   76519     if( r>=iReg && r<=iLast ){
   76520       cacheEntryClear(pParse, p);
   76521       p->iReg = 0;
   76522     }
   76523   }
   76524 }
   76525 
   76526 /*
   76527 ** Remember the current column cache context.  Any new entries added
   76528 ** added to the column cache after this call are removed when the
   76529 ** corresponding pop occurs.
   76530 */
   76531 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   76532   pParse->iCacheLevel++;
   76533 }
   76534 
   76535 /*
   76536 ** Remove from the column cache any entries that were added since the
   76537 ** the previous N Push operations.  In other words, restore the cache
   76538 ** to the state it was in N Pushes ago.
   76539 */
   76540 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
   76541   int i;
   76542   struct yColCache *p;
   76543   assert( N>0 );
   76544   assert( pParse->iCacheLevel>=N );
   76545   pParse->iCacheLevel -= N;
   76546   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76547     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   76548       cacheEntryClear(pParse, p);
   76549       p->iReg = 0;
   76550     }
   76551   }
   76552 }
   76553 
   76554 /*
   76555 ** When a cached column is reused, make sure that its register is
   76556 ** no longer available as a temp register.  ticket #3879:  that same
   76557 ** register might be in the cache in multiple places, so be sure to
   76558 ** get them all.
   76559 */
   76560 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   76561   int i;
   76562   struct yColCache *p;
   76563   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76564     if( p->iReg==iReg ){
   76565       p->tempReg = 0;
   76566     }
   76567   }
   76568 }
   76569 
   76570 /*
   76571 ** Generate code to extract the value of the iCol-th column of a table.
   76572 */
   76573 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   76574   Vdbe *v,        /* The VDBE under construction */
   76575   Table *pTab,    /* The table containing the value */
   76576   int iTabCur,    /* The cursor for this table */
   76577   int iCol,       /* Index of the column to extract */
   76578   int regOut      /* Extract the valud into this register */
   76579 ){
   76580   if( iCol<0 || iCol==pTab->iPKey ){
   76581     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   76582   }else{
   76583     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   76584     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
   76585   }
   76586   if( iCol>=0 ){
   76587     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   76588   }
   76589 }
   76590 
   76591 /*
   76592 ** Generate code that will extract the iColumn-th column from
   76593 ** table pTab and store the column value in a register.  An effort
   76594 ** is made to store the column value in register iReg, but this is
   76595 ** not guaranteed.  The location of the column value is returned.
   76596 **
   76597 ** There must be an open cursor to pTab in iTable when this routine
   76598 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   76599 */
   76600 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   76601   Parse *pParse,   /* Parsing and code generating context */
   76602   Table *pTab,     /* Description of the table we are reading from */
   76603   int iColumn,     /* Index of the table column */
   76604   int iTable,      /* The cursor pointing to the table */
   76605   int iReg         /* Store results here */
   76606 ){
   76607   Vdbe *v = pParse->pVdbe;
   76608   int i;
   76609   struct yColCache *p;
   76610 
   76611   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76612     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   76613       p->lru = pParse->iCacheCnt++;
   76614       sqlite3ExprCachePinRegister(pParse, p->iReg);
   76615       return p->iReg;
   76616     }
   76617   }
   76618   assert( v!=0 );
   76619   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   76620   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   76621   return iReg;
   76622 }
   76623 
   76624 /*
   76625 ** Clear all column cache entries.
   76626 */
   76627 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   76628   int i;
   76629   struct yColCache *p;
   76630 
   76631   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76632     if( p->iReg ){
   76633       cacheEntryClear(pParse, p);
   76634       p->iReg = 0;
   76635     }
   76636   }
   76637 }
   76638 
   76639 /*
   76640 ** Record the fact that an affinity change has occurred on iCount
   76641 ** registers starting with iStart.
   76642 */
   76643 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   76644   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   76645 }
   76646 
   76647 /*
   76648 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   76649 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   76650 */
   76651 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   76652   int i;
   76653   struct yColCache *p;
   76654   if( NEVER(iFrom==iTo) ) return;
   76655   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   76656   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76657     int x = p->iReg;
   76658     if( x>=iFrom && x<iFrom+nReg ){
   76659       p->iReg += iTo-iFrom;
   76660     }
   76661   }
   76662 }
   76663 
   76664 /*
   76665 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
   76666 ** over to iTo..iTo+nReg-1.
   76667 */
   76668 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
   76669   int i;
   76670   if( NEVER(iFrom==iTo) ) return;
   76671   for(i=0; i<nReg; i++){
   76672     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
   76673   }
   76674 }
   76675 
   76676 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   76677 /*
   76678 ** Return true if any register in the range iFrom..iTo (inclusive)
   76679 ** is used as part of the column cache.
   76680 **
   76681 ** This routine is used within assert() and testcase() macros only
   76682 ** and does not appear in a normal build.
   76683 */
   76684 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   76685   int i;
   76686   struct yColCache *p;
   76687   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76688     int r = p->iReg;
   76689     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   76690   }
   76691   return 0;
   76692 }
   76693 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   76694 
   76695 /*
   76696 ** Generate code into the current Vdbe to evaluate the given
   76697 ** expression.  Attempt to store the results in register "target".
   76698 ** Return the register where results are stored.
   76699 **
   76700 ** With this routine, there is no guarantee that results will
   76701 ** be stored in target.  The result might be stored in some other
   76702 ** register if it is convenient to do so.  The calling function
   76703 ** must check the return code and move the results to the desired
   76704 ** register.
   76705 */
   76706 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   76707   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   76708   int op;                   /* The opcode being coded */
   76709   int inReg = target;       /* Results stored in register inReg */
   76710   int regFree1 = 0;         /* If non-zero free this temporary register */
   76711   int regFree2 = 0;         /* If non-zero free this temporary register */
   76712   int r1, r2, r3, r4;       /* Various register numbers */
   76713   sqlite3 *db = pParse->db; /* The database connection */
   76714 
   76715   assert( target>0 && target<=pParse->nMem );
   76716   if( v==0 ){
   76717     assert( pParse->db->mallocFailed );
   76718     return 0;
   76719   }
   76720 
   76721   if( pExpr==0 ){
   76722     op = TK_NULL;
   76723   }else{
   76724     op = pExpr->op;
   76725   }
   76726   switch( op ){
   76727     case TK_AGG_COLUMN: {
   76728       AggInfo *pAggInfo = pExpr->pAggInfo;
   76729       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   76730       if( !pAggInfo->directMode ){
   76731         assert( pCol->iMem>0 );
   76732         inReg = pCol->iMem;
   76733         break;
   76734       }else if( pAggInfo->useSortingIdx ){
   76735         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
   76736                               pCol->iSorterColumn, target);
   76737         break;
   76738       }
   76739       /* Otherwise, fall thru into the TK_COLUMN case */
   76740     }
   76741     case TK_COLUMN: {
   76742       if( pExpr->iTable<0 ){
   76743         /* This only happens when coding check constraints */
   76744         assert( pParse->ckBase>0 );
   76745         inReg = pExpr->iColumn + pParse->ckBase;
   76746       }else{
   76747         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   76748                                  pExpr->iColumn, pExpr->iTable, target);
   76749       }
   76750       break;
   76751     }
   76752     case TK_INTEGER: {
   76753       codeInteger(pParse, pExpr, 0, target);
   76754       break;
   76755     }
   76756 #ifndef SQLITE_OMIT_FLOATING_POINT
   76757     case TK_FLOAT: {
   76758       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76759       codeReal(v, pExpr->u.zToken, 0, target);
   76760       break;
   76761     }
   76762 #endif
   76763     case TK_STRING: {
   76764       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76765       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   76766       break;
   76767     }
   76768     case TK_NULL: {
   76769       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   76770       break;
   76771     }
   76772 #ifndef SQLITE_OMIT_BLOB_LITERAL
   76773     case TK_BLOB: {
   76774       int n;
   76775       const char *z;
   76776       char *zBlob;
   76777       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76778       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   76779       assert( pExpr->u.zToken[1]=='\'' );
   76780       z = &pExpr->u.zToken[2];
   76781       n = sqlite3Strlen30(z) - 1;
   76782       assert( z[n]=='\'' );
   76783       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   76784       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   76785       break;
   76786     }
   76787 #endif
   76788     case TK_VARIABLE: {
   76789       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76790       assert( pExpr->u.zToken!=0 );
   76791       assert( pExpr->u.zToken[0]!=0 );
   76792       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   76793       if( pExpr->u.zToken[1]!=0 ){
   76794         assert( pExpr->u.zToken[0]=='?'
   76795              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
   76796         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
   76797       }
   76798       break;
   76799     }
   76800     case TK_REGISTER: {
   76801       inReg = pExpr->iTable;
   76802       break;
   76803     }
   76804     case TK_AS: {
   76805       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   76806       break;
   76807     }
   76808 #ifndef SQLITE_OMIT_CAST
   76809     case TK_CAST: {
   76810       /* Expressions of the form:   CAST(pLeft AS token) */
   76811       int aff, to_op;
   76812       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   76813       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76814       aff = sqlite3AffinityType(pExpr->u.zToken);
   76815       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   76816       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   76817       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   76818       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   76819       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   76820       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   76821       testcase( to_op==OP_ToText );
   76822       testcase( to_op==OP_ToBlob );
   76823       testcase( to_op==OP_ToNumeric );
   76824       testcase( to_op==OP_ToInt );
   76825       testcase( to_op==OP_ToReal );
   76826       if( inReg!=target ){
   76827         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   76828         inReg = target;
   76829       }
   76830       sqlite3VdbeAddOp1(v, to_op, inReg);
   76831       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   76832       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   76833       break;
   76834     }
   76835 #endif /* SQLITE_OMIT_CAST */
   76836     case TK_LT:
   76837     case TK_LE:
   76838     case TK_GT:
   76839     case TK_GE:
   76840     case TK_NE:
   76841     case TK_EQ: {
   76842       assert( TK_LT==OP_Lt );
   76843       assert( TK_LE==OP_Le );
   76844       assert( TK_GT==OP_Gt );
   76845       assert( TK_GE==OP_Ge );
   76846       assert( TK_EQ==OP_Eq );
   76847       assert( TK_NE==OP_Ne );
   76848       testcase( op==TK_LT );
   76849       testcase( op==TK_LE );
   76850       testcase( op==TK_GT );
   76851       testcase( op==TK_GE );
   76852       testcase( op==TK_EQ );
   76853       testcase( op==TK_NE );
   76854       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76855       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76856       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   76857                   r1, r2, inReg, SQLITE_STOREP2);
   76858       testcase( regFree1==0 );
   76859       testcase( regFree2==0 );
   76860       break;
   76861     }
   76862     case TK_IS:
   76863     case TK_ISNOT: {
   76864       testcase( op==TK_IS );
   76865       testcase( op==TK_ISNOT );
   76866       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76867       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76868       op = (op==TK_IS) ? TK_EQ : TK_NE;
   76869       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   76870                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   76871       testcase( regFree1==0 );
   76872       testcase( regFree2==0 );
   76873       break;
   76874     }
   76875     case TK_AND:
   76876     case TK_OR:
   76877     case TK_PLUS:
   76878     case TK_STAR:
   76879     case TK_MINUS:
   76880     case TK_REM:
   76881     case TK_BITAND:
   76882     case TK_BITOR:
   76883     case TK_SLASH:
   76884     case TK_LSHIFT:
   76885     case TK_RSHIFT:
   76886     case TK_CONCAT: {
   76887       assert( TK_AND==OP_And );
   76888       assert( TK_OR==OP_Or );
   76889       assert( TK_PLUS==OP_Add );
   76890       assert( TK_MINUS==OP_Subtract );
   76891       assert( TK_REM==OP_Remainder );
   76892       assert( TK_BITAND==OP_BitAnd );
   76893       assert( TK_BITOR==OP_BitOr );
   76894       assert( TK_SLASH==OP_Divide );
   76895       assert( TK_LSHIFT==OP_ShiftLeft );
   76896       assert( TK_RSHIFT==OP_ShiftRight );
   76897       assert( TK_CONCAT==OP_Concat );
   76898       testcase( op==TK_AND );
   76899       testcase( op==TK_OR );
   76900       testcase( op==TK_PLUS );
   76901       testcase( op==TK_MINUS );
   76902       testcase( op==TK_REM );
   76903       testcase( op==TK_BITAND );
   76904       testcase( op==TK_BITOR );
   76905       testcase( op==TK_SLASH );
   76906       testcase( op==TK_LSHIFT );
   76907       testcase( op==TK_RSHIFT );
   76908       testcase( op==TK_CONCAT );
   76909       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76910       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76911       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   76912       testcase( regFree1==0 );
   76913       testcase( regFree2==0 );
   76914       break;
   76915     }
   76916     case TK_UMINUS: {
   76917       Expr *pLeft = pExpr->pLeft;
   76918       assert( pLeft );
   76919       if( pLeft->op==TK_INTEGER ){
   76920         codeInteger(pParse, pLeft, 1, target);
   76921 #ifndef SQLITE_OMIT_FLOATING_POINT
   76922       }else if( pLeft->op==TK_FLOAT ){
   76923         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76924         codeReal(v, pLeft->u.zToken, 1, target);
   76925 #endif
   76926       }else{
   76927         regFree1 = r1 = sqlite3GetTempReg(pParse);
   76928         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
   76929         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   76930         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   76931         testcase( regFree2==0 );
   76932       }
   76933       inReg = target;
   76934       break;
   76935     }
   76936     case TK_BITNOT:
   76937     case TK_NOT: {
   76938       assert( TK_BITNOT==OP_BitNot );
   76939       assert( TK_NOT==OP_Not );
   76940       testcase( op==TK_BITNOT );
   76941       testcase( op==TK_NOT );
   76942       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76943       testcase( regFree1==0 );
   76944       inReg = target;
   76945       sqlite3VdbeAddOp2(v, op, r1, inReg);
   76946       break;
   76947     }
   76948     case TK_ISNULL:
   76949     case TK_NOTNULL: {
   76950       int addr;
   76951       assert( TK_ISNULL==OP_IsNull );
   76952       assert( TK_NOTNULL==OP_NotNull );
   76953       testcase( op==TK_ISNULL );
   76954       testcase( op==TK_NOTNULL );
   76955       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   76956       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76957       testcase( regFree1==0 );
   76958       addr = sqlite3VdbeAddOp1(v, op, r1);
   76959       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
   76960       sqlite3VdbeJumpHere(v, addr);
   76961       break;
   76962     }
   76963     case TK_AGG_FUNCTION: {
   76964       AggInfo *pInfo = pExpr->pAggInfo;
   76965       if( pInfo==0 ){
   76966         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76967         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   76968       }else{
   76969         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   76970       }
   76971       break;
   76972     }
   76973     case TK_CONST_FUNC:
   76974     case TK_FUNCTION: {
   76975       ExprList *pFarg;       /* List of function arguments */
   76976       int nFarg;             /* Number of function arguments */
   76977       FuncDef *pDef;         /* The function definition object */
   76978       int nId;               /* Length of the function name in bytes */
   76979       const char *zId;       /* The function name */
   76980       int constMask = 0;     /* Mask of function arguments that are constant */
   76981       int i;                 /* Loop counter */
   76982       u8 enc = ENC(db);      /* The text encoding used by this database */
   76983       CollSeq *pColl = 0;    /* A collating sequence */
   76984 
   76985       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   76986       testcase( op==TK_CONST_FUNC );
   76987       testcase( op==TK_FUNCTION );
   76988       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   76989         pFarg = 0;
   76990       }else{
   76991         pFarg = pExpr->x.pList;
   76992       }
   76993       nFarg = pFarg ? pFarg->nExpr : 0;
   76994       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76995       zId = pExpr->u.zToken;
   76996       nId = sqlite3Strlen30(zId);
   76997       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   76998       if( pDef==0 ){
   76999         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   77000         break;
   77001       }
   77002 
   77003       /* Attempt a direct implementation of the built-in COALESCE() and
   77004       ** IFNULL() functions.  This avoids unnecessary evalation of
   77005       ** arguments past the first non-NULL argument.
   77006       */
   77007       if( pDef->flags & SQLITE_FUNC_COALESCE ){
   77008         int endCoalesce = sqlite3VdbeMakeLabel(v);
   77009         assert( nFarg>=2 );
   77010         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   77011         for(i=1; i<nFarg; i++){
   77012           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   77013           sqlite3ExprCacheRemove(pParse, target, 1);
   77014           sqlite3ExprCachePush(pParse);
   77015           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   77016           sqlite3ExprCachePop(pParse, 1);
   77017         }
   77018         sqlite3VdbeResolveLabel(v, endCoalesce);
   77019         break;
   77020       }
   77021 
   77022 
   77023       if( pFarg ){
   77024         r1 = sqlite3GetTempRange(pParse, nFarg);
   77025         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   77026         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
   77027         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
   77028       }else{
   77029         r1 = 0;
   77030       }
   77031 #ifndef SQLITE_OMIT_VIRTUALTABLE
   77032       /* Possibly overload the function if the first argument is
   77033       ** a virtual table column.
   77034       **
   77035       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   77036       ** second argument, not the first, as the argument to test to
   77037       ** see if it is a column in a virtual table.  This is done because
   77038       ** the left operand of infix functions (the operand we want to
   77039       ** control overloading) ends up as the second argument to the
   77040       ** function.  The expression "A glob B" is equivalent to
   77041       ** "glob(B,A).  We want to use the A in "A glob B" to test
   77042       ** for function overloading.  But we use the B term in "glob(B,A)".
   77043       */
   77044       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   77045         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   77046       }else if( nFarg>0 ){
   77047         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   77048       }
   77049 #endif
   77050       for(i=0; i<nFarg; i++){
   77051         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   77052           constMask |= (1<<i);
   77053         }
   77054         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   77055           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   77056         }
   77057       }
   77058       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
   77059         if( !pColl ) pColl = db->pDfltColl;
   77060         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   77061       }
   77062       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   77063                         (char*)pDef, P4_FUNCDEF);
   77064       sqlite3VdbeChangeP5(v, (u8)nFarg);
   77065       if( nFarg ){
   77066         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   77067       }
   77068       break;
   77069     }
   77070 #ifndef SQLITE_OMIT_SUBQUERY
   77071     case TK_EXISTS:
   77072     case TK_SELECT: {
   77073       testcase( op==TK_EXISTS );
   77074       testcase( op==TK_SELECT );
   77075       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   77076       break;
   77077     }
   77078     case TK_IN: {
   77079       int destIfFalse = sqlite3VdbeMakeLabel(v);
   77080       int destIfNull = sqlite3VdbeMakeLabel(v);
   77081       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   77082       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   77083       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   77084       sqlite3VdbeResolveLabel(v, destIfFalse);
   77085       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   77086       sqlite3VdbeResolveLabel(v, destIfNull);
   77087       break;
   77088     }
   77089 #endif /* SQLITE_OMIT_SUBQUERY */
   77090 
   77091 
   77092     /*
   77093     **    x BETWEEN y AND z
   77094     **
   77095     ** This is equivalent to
   77096     **
   77097     **    x>=y AND x<=z
   77098     **
   77099     ** X is stored in pExpr->pLeft.
   77100     ** Y is stored in pExpr->pList->a[0].pExpr.
   77101     ** Z is stored in pExpr->pList->a[1].pExpr.
   77102     */
   77103     case TK_BETWEEN: {
   77104       Expr *pLeft = pExpr->pLeft;
   77105       struct ExprList_item *pLItem = pExpr->x.pList->a;
   77106       Expr *pRight = pLItem->pExpr;
   77107 
   77108       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   77109       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   77110       testcase( regFree1==0 );
   77111       testcase( regFree2==0 );
   77112       r3 = sqlite3GetTempReg(pParse);
   77113       r4 = sqlite3GetTempReg(pParse);
   77114       codeCompare(pParse, pLeft, pRight, OP_Ge,
   77115                   r1, r2, r3, SQLITE_STOREP2);
   77116       pLItem++;
   77117       pRight = pLItem->pExpr;
   77118       sqlite3ReleaseTempReg(pParse, regFree2);
   77119       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   77120       testcase( regFree2==0 );
   77121       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   77122       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   77123       sqlite3ReleaseTempReg(pParse, r3);
   77124       sqlite3ReleaseTempReg(pParse, r4);
   77125       break;
   77126     }
   77127     case TK_UPLUS: {
   77128       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   77129       break;
   77130     }
   77131 
   77132     case TK_TRIGGER: {
   77133       /* If the opcode is TK_TRIGGER, then the expression is a reference
   77134       ** to a column in the new.* or old.* pseudo-tables available to
   77135       ** trigger programs. In this case Expr.iTable is set to 1 for the
   77136       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   77137       ** is set to the column of the pseudo-table to read, or to -1 to
   77138       ** read the rowid field.
   77139       **
   77140       ** The expression is implemented using an OP_Param opcode. The p1
   77141       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   77142       ** to reference another column of the old.* pseudo-table, where
   77143       ** i is the index of the column. For a new.rowid reference, p1 is
   77144       ** set to (n+1), where n is the number of columns in each pseudo-table.
   77145       ** For a reference to any other column in the new.* pseudo-table, p1
   77146       ** is set to (n+2+i), where n and i are as defined previously. For
   77147       ** example, if the table on which triggers are being fired is
   77148       ** declared as:
   77149       **
   77150       **   CREATE TABLE t1(a, b);
   77151       **
   77152       ** Then p1 is interpreted as follows:
   77153       **
   77154       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   77155       **   p1==1   ->    old.a         p1==4   ->    new.a
   77156       **   p1==2   ->    old.b         p1==5   ->    new.b
   77157       */
   77158       Table *pTab = pExpr->pTab;
   77159       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   77160 
   77161       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   77162       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   77163       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   77164       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   77165 
   77166       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   77167       VdbeComment((v, "%s.%s -> $%d",
   77168         (pExpr->iTable ? "new" : "old"),
   77169         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   77170         target
   77171       ));
   77172 
   77173 #ifndef SQLITE_OMIT_FLOATING_POINT
   77174       /* If the column has REAL affinity, it may currently be stored as an
   77175       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   77176       if( pExpr->iColumn>=0
   77177        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   77178       ){
   77179         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   77180       }
   77181 #endif
   77182       break;
   77183     }
   77184 
   77185 
   77186     /*
   77187     ** Form A:
   77188     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   77189     **
   77190     ** Form B:
   77191     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   77192     **
   77193     ** Form A is can be transformed into the equivalent form B as follows:
   77194     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   77195     **        WHEN x=eN THEN rN ELSE y END
   77196     **
   77197     ** X (if it exists) is in pExpr->pLeft.
   77198     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
   77199     ** ELSE clause and no other term matches, then the result of the
   77200     ** exprssion is NULL.
   77201     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   77202     **
   77203     ** The result of the expression is the Ri for the first matching Ei,
   77204     ** or if there is no matching Ei, the ELSE term Y, or if there is
   77205     ** no ELSE term, NULL.
   77206     */
   77207     default: assert( op==TK_CASE ); {
   77208       int endLabel;                     /* GOTO label for end of CASE stmt */
   77209       int nextCase;                     /* GOTO label for next WHEN clause */
   77210       int nExpr;                        /* 2x number of WHEN terms */
   77211       int i;                            /* Loop counter */
   77212       ExprList *pEList;                 /* List of WHEN terms */
   77213       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   77214       Expr opCompare;                   /* The X==Ei expression */
   77215       Expr cacheX;                      /* Cached expression X */
   77216       Expr *pX;                         /* The X expression */
   77217       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   77218       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   77219 
   77220       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   77221       assert((pExpr->x.pList->nExpr % 2) == 0);
   77222       assert(pExpr->x.pList->nExpr > 0);
   77223       pEList = pExpr->x.pList;
   77224       aListelem = pEList->a;
   77225       nExpr = pEList->nExpr;
   77226       endLabel = sqlite3VdbeMakeLabel(v);
   77227       if( (pX = pExpr->pLeft)!=0 ){
   77228         cacheX = *pX;
   77229         testcase( pX->op==TK_COLUMN );
   77230         testcase( pX->op==TK_REGISTER );
   77231         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
   77232         testcase( regFree1==0 );
   77233         cacheX.op = TK_REGISTER;
   77234         opCompare.op = TK_EQ;
   77235         opCompare.pLeft = &cacheX;
   77236         pTest = &opCompare;
   77237         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   77238         ** The value in regFree1 might get SCopy-ed into the file result.
   77239         ** So make sure that the regFree1 register is not reused for other
   77240         ** purposes and possibly overwritten.  */
   77241         regFree1 = 0;
   77242       }
   77243       for(i=0; i<nExpr; i=i+2){
   77244         sqlite3ExprCachePush(pParse);
   77245         if( pX ){
   77246           assert( pTest!=0 );
   77247           opCompare.pRight = aListelem[i].pExpr;
   77248         }else{
   77249           pTest = aListelem[i].pExpr;
   77250         }
   77251         nextCase = sqlite3VdbeMakeLabel(v);
   77252         testcase( pTest->op==TK_COLUMN );
   77253         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   77254         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   77255         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
   77256         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   77257         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   77258         sqlite3ExprCachePop(pParse, 1);
   77259         sqlite3VdbeResolveLabel(v, nextCase);
   77260       }
   77261       if( pExpr->pRight ){
   77262         sqlite3ExprCachePush(pParse);
   77263         sqlite3ExprCode(pParse, pExpr->pRight, target);
   77264         sqlite3ExprCachePop(pParse, 1);
   77265       }else{
   77266         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   77267       }
   77268       assert( db->mallocFailed || pParse->nErr>0
   77269            || pParse->iCacheLevel==iCacheLevel );
   77270       sqlite3VdbeResolveLabel(v, endLabel);
   77271       break;
   77272     }
   77273 #ifndef SQLITE_OMIT_TRIGGER
   77274     case TK_RAISE: {
   77275       assert( pExpr->affinity==OE_Rollback
   77276            || pExpr->affinity==OE_Abort
   77277            || pExpr->affinity==OE_Fail
   77278            || pExpr->affinity==OE_Ignore
   77279       );
   77280       if( !pParse->pTriggerTab ){
   77281         sqlite3ErrorMsg(pParse,
   77282                        "RAISE() may only be used within a trigger-program");
   77283         return 0;
   77284       }
   77285       if( pExpr->affinity==OE_Abort ){
   77286         sqlite3MayAbort(pParse);
   77287       }
   77288       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   77289       if( pExpr->affinity==OE_Ignore ){
   77290         sqlite3VdbeAddOp4(
   77291             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   77292       }else{
   77293         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
   77294       }
   77295 
   77296       break;
   77297     }
   77298 #endif
   77299   }
   77300   sqlite3ReleaseTempReg(pParse, regFree1);
   77301   sqlite3ReleaseTempReg(pParse, regFree2);
   77302   return inReg;
   77303 }
   77304 
   77305 /*
   77306 ** Generate code to evaluate an expression and store the results
   77307 ** into a register.  Return the register number where the results
   77308 ** are stored.
   77309 **
   77310 ** If the register is a temporary register that can be deallocated,
   77311 ** then write its number into *pReg.  If the result register is not
   77312 ** a temporary, then set *pReg to zero.
   77313 */
   77314 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   77315   int r1 = sqlite3GetTempReg(pParse);
   77316   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   77317   if( r2==r1 ){
   77318     *pReg = r1;
   77319   }else{
   77320     sqlite3ReleaseTempReg(pParse, r1);
   77321     *pReg = 0;
   77322   }
   77323   return r2;
   77324 }
   77325 
   77326 /*
   77327 ** Generate code that will evaluate expression pExpr and store the
   77328 ** results in register target.  The results are guaranteed to appear
   77329 ** in register target.
   77330 */
   77331 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   77332   int inReg;
   77333 
   77334   assert( target>0 && target<=pParse->nMem );
   77335   if( pExpr && pExpr->op==TK_REGISTER ){
   77336     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   77337   }else{
   77338     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   77339     assert( pParse->pVdbe || pParse->db->mallocFailed );
   77340     if( inReg!=target && pParse->pVdbe ){
   77341       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   77342     }
   77343   }
   77344   return target;
   77345 }
   77346 
   77347 /*
   77348 ** Generate code that evalutes the given expression and puts the result
   77349 ** in register target.
   77350 **
   77351 ** Also make a copy of the expression results into another "cache" register
   77352 ** and modify the expression so that the next time it is evaluated,
   77353 ** the result is a copy of the cache register.
   77354 **
   77355 ** This routine is used for expressions that are used multiple
   77356 ** times.  They are evaluated once and the results of the expression
   77357 ** are reused.
   77358 */
   77359 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   77360   Vdbe *v = pParse->pVdbe;
   77361   int inReg;
   77362   inReg = sqlite3ExprCode(pParse, pExpr, target);
   77363   assert( target>0 );
   77364   /* This routine is called for terms to INSERT or UPDATE.  And the only
   77365   ** other place where expressions can be converted into TK_REGISTER is
   77366   ** in WHERE clause processing.  So as currently implemented, there is
   77367   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
   77368   ** keep the ALWAYS() in case the conditions above change with future
   77369   ** modifications or enhancements. */
   77370   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
   77371     int iMem;
   77372     iMem = ++pParse->nMem;
   77373     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
   77374     pExpr->iTable = iMem;
   77375     pExpr->op2 = pExpr->op;
   77376     pExpr->op = TK_REGISTER;
   77377   }
   77378   return inReg;
   77379 }
   77380 
   77381 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   77382 /*
   77383 ** Generate a human-readable explanation of an expression tree.
   77384 */
   77385 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
   77386   int op;                   /* The opcode being coded */
   77387   const char *zBinOp = 0;   /* Binary operator */
   77388   const char *zUniOp = 0;   /* Unary operator */
   77389   if( pExpr==0 ){
   77390     op = TK_NULL;
   77391   }else{
   77392     op = pExpr->op;
   77393   }
   77394   switch( op ){
   77395     case TK_AGG_COLUMN: {
   77396       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
   77397             pExpr->iTable, pExpr->iColumn);
   77398       break;
   77399     }
   77400     case TK_COLUMN: {
   77401       if( pExpr->iTable<0 ){
   77402         /* This only happens when coding check constraints */
   77403         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
   77404       }else{
   77405         sqlite3ExplainPrintf(pOut, "{%d:%d}",
   77406                              pExpr->iTable, pExpr->iColumn);
   77407       }
   77408       break;
   77409     }
   77410     case TK_INTEGER: {
   77411       if( pExpr->flags & EP_IntValue ){
   77412         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
   77413       }else{
   77414         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
   77415       }
   77416       break;
   77417     }
   77418 #ifndef SQLITE_OMIT_FLOATING_POINT
   77419     case TK_FLOAT: {
   77420       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   77421       break;
   77422     }
   77423 #endif
   77424     case TK_STRING: {
   77425       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
   77426       break;
   77427     }
   77428     case TK_NULL: {
   77429       sqlite3ExplainPrintf(pOut,"NULL");
   77430       break;
   77431     }
   77432 #ifndef SQLITE_OMIT_BLOB_LITERAL
   77433     case TK_BLOB: {
   77434       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   77435       break;
   77436     }
   77437 #endif
   77438     case TK_VARIABLE: {
   77439       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
   77440                            pExpr->u.zToken, pExpr->iColumn);
   77441       break;
   77442     }
   77443     case TK_REGISTER: {
   77444       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
   77445       break;
   77446     }
   77447     case TK_AS: {
   77448       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77449       break;
   77450     }
   77451 #ifndef SQLITE_OMIT_CAST
   77452     case TK_CAST: {
   77453       /* Expressions of the form:   CAST(pLeft AS token) */
   77454       const char *zAff = "unk";
   77455       switch( sqlite3AffinityType(pExpr->u.zToken) ){
   77456         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
   77457         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
   77458         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
   77459         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
   77460         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
   77461       }
   77462       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
   77463       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77464       sqlite3ExplainPrintf(pOut, ")");
   77465       break;
   77466     }
   77467 #endif /* SQLITE_OMIT_CAST */
   77468     case TK_LT:      zBinOp = "LT";     break;
   77469     case TK_LE:      zBinOp = "LE";     break;
   77470     case TK_GT:      zBinOp = "GT";     break;
   77471     case TK_GE:      zBinOp = "GE";     break;
   77472     case TK_NE:      zBinOp = "NE";     break;
   77473     case TK_EQ:      zBinOp = "EQ";     break;
   77474     case TK_IS:      zBinOp = "IS";     break;
   77475     case TK_ISNOT:   zBinOp = "ISNOT";  break;
   77476     case TK_AND:     zBinOp = "AND";    break;
   77477     case TK_OR:      zBinOp = "OR";     break;
   77478     case TK_PLUS:    zBinOp = "ADD";    break;
   77479     case TK_STAR:    zBinOp = "MUL";    break;
   77480     case TK_MINUS:   zBinOp = "SUB";    break;
   77481     case TK_REM:     zBinOp = "REM";    break;
   77482     case TK_BITAND:  zBinOp = "BITAND"; break;
   77483     case TK_BITOR:   zBinOp = "BITOR";  break;
   77484     case TK_SLASH:   zBinOp = "DIV";    break;
   77485     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
   77486     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
   77487     case TK_CONCAT:  zBinOp = "CONCAT"; break;
   77488 
   77489     case TK_UMINUS:  zUniOp = "UMINUS"; break;
   77490     case TK_UPLUS:   zUniOp = "UPLUS";  break;
   77491     case TK_BITNOT:  zUniOp = "BITNOT"; break;
   77492     case TK_NOT:     zUniOp = "NOT";    break;
   77493     case TK_ISNULL:  zUniOp = "ISNULL"; break;
   77494     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
   77495 
   77496     case TK_AGG_FUNCTION:
   77497     case TK_CONST_FUNC:
   77498     case TK_FUNCTION: {
   77499       ExprList *pFarg;       /* List of function arguments */
   77500       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   77501         pFarg = 0;
   77502       }else{
   77503         pFarg = pExpr->x.pList;
   77504       }
   77505       sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
   77506                            op==TK_AGG_FUNCTION ? "AGG_" : "",
   77507                            pExpr->u.zToken);
   77508       if( pFarg ){
   77509         sqlite3ExplainExprList(pOut, pFarg);
   77510       }
   77511       sqlite3ExplainPrintf(pOut, ")");
   77512       break;
   77513     }
   77514 #ifndef SQLITE_OMIT_SUBQUERY
   77515     case TK_EXISTS: {
   77516       sqlite3ExplainPrintf(pOut, "EXISTS(");
   77517       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77518       sqlite3ExplainPrintf(pOut,")");
   77519       break;
   77520     }
   77521     case TK_SELECT: {
   77522       sqlite3ExplainPrintf(pOut, "(");
   77523       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77524       sqlite3ExplainPrintf(pOut, ")");
   77525       break;
   77526     }
   77527     case TK_IN: {
   77528       sqlite3ExplainPrintf(pOut, "IN(");
   77529       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77530       sqlite3ExplainPrintf(pOut, ",");
   77531       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   77532         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77533       }else{
   77534         sqlite3ExplainExprList(pOut, pExpr->x.pList);
   77535       }
   77536       sqlite3ExplainPrintf(pOut, ")");
   77537       break;
   77538     }
   77539 #endif /* SQLITE_OMIT_SUBQUERY */
   77540 
   77541     /*
   77542     **    x BETWEEN y AND z
   77543     **
   77544     ** This is equivalent to
   77545     **
   77546     **    x>=y AND x<=z
   77547     **
   77548     ** X is stored in pExpr->pLeft.
   77549     ** Y is stored in pExpr->pList->a[0].pExpr.
   77550     ** Z is stored in pExpr->pList->a[1].pExpr.
   77551     */
   77552     case TK_BETWEEN: {
   77553       Expr *pX = pExpr->pLeft;
   77554       Expr *pY = pExpr->x.pList->a[0].pExpr;
   77555       Expr *pZ = pExpr->x.pList->a[1].pExpr;
   77556       sqlite3ExplainPrintf(pOut, "BETWEEN(");
   77557       sqlite3ExplainExpr(pOut, pX);
   77558       sqlite3ExplainPrintf(pOut, ",");
   77559       sqlite3ExplainExpr(pOut, pY);
   77560       sqlite3ExplainPrintf(pOut, ",");
   77561       sqlite3ExplainExpr(pOut, pZ);
   77562       sqlite3ExplainPrintf(pOut, ")");
   77563       break;
   77564     }
   77565     case TK_TRIGGER: {
   77566       /* If the opcode is TK_TRIGGER, then the expression is a reference
   77567       ** to a column in the new.* or old.* pseudo-tables available to
   77568       ** trigger programs. In this case Expr.iTable is set to 1 for the
   77569       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   77570       ** is set to the column of the pseudo-table to read, or to -1 to
   77571       ** read the rowid field.
   77572       */
   77573       sqlite3ExplainPrintf(pOut, "%s(%d)",
   77574           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
   77575       break;
   77576     }
   77577     case TK_CASE: {
   77578       sqlite3ExplainPrintf(pOut, "CASE(");
   77579       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77580       sqlite3ExplainPrintf(pOut, ",");
   77581       sqlite3ExplainExprList(pOut, pExpr->x.pList);
   77582       break;
   77583     }
   77584 #ifndef SQLITE_OMIT_TRIGGER
   77585     case TK_RAISE: {
   77586       const char *zType = "unk";
   77587       switch( pExpr->affinity ){
   77588         case OE_Rollback:   zType = "rollback";  break;
   77589         case OE_Abort:      zType = "abort";     break;
   77590         case OE_Fail:       zType = "fail";      break;
   77591         case OE_Ignore:     zType = "ignore";    break;
   77592       }
   77593       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
   77594       break;
   77595     }
   77596 #endif
   77597   }
   77598   if( zBinOp ){
   77599     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
   77600     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77601     sqlite3ExplainPrintf(pOut,",");
   77602     sqlite3ExplainExpr(pOut, pExpr->pRight);
   77603     sqlite3ExplainPrintf(pOut,")");
   77604   }else if( zUniOp ){
   77605     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
   77606     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77607     sqlite3ExplainPrintf(pOut,")");
   77608   }
   77609 }
   77610 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   77611 
   77612 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   77613 /*
   77614 ** Generate a human-readable explanation of an expression list.
   77615 */
   77616 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
   77617   int i;
   77618   if( pList==0 || pList->nExpr==0 ){
   77619     sqlite3ExplainPrintf(pOut, "(empty-list)");
   77620     return;
   77621   }else if( pList->nExpr==1 ){
   77622     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
   77623   }else{
   77624     sqlite3ExplainPush(pOut);
   77625     for(i=0; i<pList->nExpr; i++){
   77626       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
   77627       sqlite3ExplainPush(pOut);
   77628       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
   77629       sqlite3ExplainPop(pOut);
   77630       if( i<pList->nExpr-1 ){
   77631         sqlite3ExplainNL(pOut);
   77632       }
   77633     }
   77634     sqlite3ExplainPop(pOut);
   77635   }
   77636 }
   77637 #endif /* SQLITE_DEBUG */
   77638 
   77639 /*
   77640 ** Return TRUE if pExpr is an constant expression that is appropriate
   77641 ** for factoring out of a loop.  Appropriate expressions are:
   77642 **
   77643 **    *  Any expression that evaluates to two or more opcodes.
   77644 **
   77645 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
   77646 **       or OP_Variable that does not need to be placed in a
   77647 **       specific register.
   77648 **
   77649 ** There is no point in factoring out single-instruction constant
   77650 ** expressions that need to be placed in a particular register.
   77651 ** We could factor them out, but then we would end up adding an
   77652 ** OP_SCopy instruction to move the value into the correct register
   77653 ** later.  We might as well just use the original instruction and
   77654 ** avoid the OP_SCopy.
   77655 */
   77656 static int isAppropriateForFactoring(Expr *p){
   77657   if( !sqlite3ExprIsConstantNotJoin(p) ){
   77658     return 0;  /* Only constant expressions are appropriate for factoring */
   77659   }
   77660   if( (p->flags & EP_FixedDest)==0 ){
   77661     return 1;  /* Any constant without a fixed destination is appropriate */
   77662   }
   77663   while( p->op==TK_UPLUS ) p = p->pLeft;
   77664   switch( p->op ){
   77665 #ifndef SQLITE_OMIT_BLOB_LITERAL
   77666     case TK_BLOB:
   77667 #endif
   77668     case TK_VARIABLE:
   77669     case TK_INTEGER:
   77670     case TK_FLOAT:
   77671     case TK_NULL:
   77672     case TK_STRING: {
   77673       testcase( p->op==TK_BLOB );
   77674       testcase( p->op==TK_VARIABLE );
   77675       testcase( p->op==TK_INTEGER );
   77676       testcase( p->op==TK_FLOAT );
   77677       testcase( p->op==TK_NULL );
   77678       testcase( p->op==TK_STRING );
   77679       /* Single-instruction constants with a fixed destination are
   77680       ** better done in-line.  If we factor them, they will just end
   77681       ** up generating an OP_SCopy to move the value to the destination
   77682       ** register. */
   77683       return 0;
   77684     }
   77685     case TK_UMINUS: {
   77686       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
   77687         return 0;
   77688       }
   77689       break;
   77690     }
   77691     default: {
   77692       break;
   77693     }
   77694   }
   77695   return 1;
   77696 }
   77697 
   77698 /*
   77699 ** If pExpr is a constant expression that is appropriate for
   77700 ** factoring out of a loop, then evaluate the expression
   77701 ** into a register and convert the expression into a TK_REGISTER
   77702 ** expression.
   77703 */
   77704 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
   77705   Parse *pParse = pWalker->pParse;
   77706   switch( pExpr->op ){
   77707     case TK_IN:
   77708     case TK_REGISTER: {
   77709       return WRC_Prune;
   77710     }
   77711     case TK_FUNCTION:
   77712     case TK_AGG_FUNCTION:
   77713     case TK_CONST_FUNC: {
   77714       /* The arguments to a function have a fixed destination.
   77715       ** Mark them this way to avoid generated unneeded OP_SCopy
   77716       ** instructions.
   77717       */
   77718       ExprList *pList = pExpr->x.pList;
   77719       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77720       if( pList ){
   77721         int i = pList->nExpr;
   77722         struct ExprList_item *pItem = pList->a;
   77723         for(; i>0; i--, pItem++){
   77724           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
   77725         }
   77726       }
   77727       break;
   77728     }
   77729   }
   77730   if( isAppropriateForFactoring(pExpr) ){
   77731     int r1 = ++pParse->nMem;
   77732     int r2;
   77733     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   77734     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
   77735     pExpr->op2 = pExpr->op;
   77736     pExpr->op = TK_REGISTER;
   77737     pExpr->iTable = r2;
   77738     return WRC_Prune;
   77739   }
   77740   return WRC_Continue;
   77741 }
   77742 
   77743 /*
   77744 ** Preevaluate constant subexpressions within pExpr and store the
   77745 ** results in registers.  Modify pExpr so that the constant subexpresions
   77746 ** are TK_REGISTER opcodes that refer to the precomputed values.
   77747 **
   77748 ** This routine is a no-op if the jump to the cookie-check code has
   77749 ** already occur.  Since the cookie-check jump is generated prior to
   77750 ** any other serious processing, this check ensures that there is no
   77751 ** way to accidently bypass the constant initializations.
   77752 **
   77753 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
   77754 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
   77755 ** interface.  This allows test logic to verify that the same answer is
   77756 ** obtained for queries regardless of whether or not constants are
   77757 ** precomputed into registers or if they are inserted in-line.
   77758 */
   77759 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
   77760   Walker w;
   77761   if( pParse->cookieGoto ) return;
   77762   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
   77763   w.xExprCallback = evalConstExpr;
   77764   w.xSelectCallback = 0;
   77765   w.pParse = pParse;
   77766   sqlite3WalkExpr(&w, pExpr);
   77767 }
   77768 
   77769 
   77770 /*
   77771 ** Generate code that pushes the value of every element of the given
   77772 ** expression list into a sequence of registers beginning at target.
   77773 **
   77774 ** Return the number of elements evaluated.
   77775 */
   77776 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   77777   Parse *pParse,     /* Parsing context */
   77778   ExprList *pList,   /* The expression list to be coded */
   77779   int target,        /* Where to write results */
   77780   int doHardCopy     /* Make a hard copy of every element */
   77781 ){
   77782   struct ExprList_item *pItem;
   77783   int i, n;
   77784   assert( pList!=0 );
   77785   assert( target>0 );
   77786   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   77787   n = pList->nExpr;
   77788   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   77789     Expr *pExpr = pItem->pExpr;
   77790     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   77791     if( inReg!=target+i ){
   77792       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
   77793                         inReg, target+i);
   77794     }
   77795   }
   77796   return n;
   77797 }
   77798 
   77799 /*
   77800 ** Generate code for a BETWEEN operator.
   77801 **
   77802 **    x BETWEEN y AND z
   77803 **
   77804 ** The above is equivalent to
   77805 **
   77806 **    x>=y AND x<=z
   77807 **
   77808 ** Code it as such, taking care to do the common subexpression
   77809 ** elementation of x.
   77810 */
   77811 static void exprCodeBetween(
   77812   Parse *pParse,    /* Parsing and code generating context */
   77813   Expr *pExpr,      /* The BETWEEN expression */
   77814   int dest,         /* Jump here if the jump is taken */
   77815   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   77816   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   77817 ){
   77818   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   77819   Expr compLeft;    /* The  x>=y  term */
   77820   Expr compRight;   /* The  x<=z  term */
   77821   Expr exprX;       /* The  x  subexpression */
   77822   int regFree1 = 0; /* Temporary use register */
   77823 
   77824   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77825   exprX = *pExpr->pLeft;
   77826   exprAnd.op = TK_AND;
   77827   exprAnd.pLeft = &compLeft;
   77828   exprAnd.pRight = &compRight;
   77829   compLeft.op = TK_GE;
   77830   compLeft.pLeft = &exprX;
   77831   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   77832   compRight.op = TK_LE;
   77833   compRight.pLeft = &exprX;
   77834   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   77835   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
   77836   exprX.op = TK_REGISTER;
   77837   if( jumpIfTrue ){
   77838     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   77839   }else{
   77840     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   77841   }
   77842   sqlite3ReleaseTempReg(pParse, regFree1);
   77843 
   77844   /* Ensure adequate test coverage */
   77845   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   77846   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   77847   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   77848   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   77849   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   77850   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   77851   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   77852   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   77853 }
   77854 
   77855 /*
   77856 ** Generate code for a boolean expression such that a jump is made
   77857 ** to the label "dest" if the expression is true but execution
   77858 ** continues straight thru if the expression is false.
   77859 **
   77860 ** If the expression evaluates to NULL (neither true nor false), then
   77861 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   77862 **
   77863 ** This code depends on the fact that certain token values (ex: TK_EQ)
   77864 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   77865 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   77866 ** the make process cause these values to align.  Assert()s in the code
   77867 ** below verify that the numbers are aligned correctly.
   77868 */
   77869 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   77870   Vdbe *v = pParse->pVdbe;
   77871   int op = 0;
   77872   int regFree1 = 0;
   77873   int regFree2 = 0;
   77874   int r1, r2;
   77875 
   77876   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   77877   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
   77878   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   77879   op = pExpr->op;
   77880   switch( op ){
   77881     case TK_AND: {
   77882       int d2 = sqlite3VdbeMakeLabel(v);
   77883       testcase( jumpIfNull==0 );
   77884       sqlite3ExprCachePush(pParse);
   77885       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   77886       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   77887       sqlite3VdbeResolveLabel(v, d2);
   77888       sqlite3ExprCachePop(pParse, 1);
   77889       break;
   77890     }
   77891     case TK_OR: {
   77892       testcase( jumpIfNull==0 );
   77893       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   77894       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   77895       break;
   77896     }
   77897     case TK_NOT: {
   77898       testcase( jumpIfNull==0 );
   77899       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   77900       break;
   77901     }
   77902     case TK_LT:
   77903     case TK_LE:
   77904     case TK_GT:
   77905     case TK_GE:
   77906     case TK_NE:
   77907     case TK_EQ: {
   77908       assert( TK_LT==OP_Lt );
   77909       assert( TK_LE==OP_Le );
   77910       assert( TK_GT==OP_Gt );
   77911       assert( TK_GE==OP_Ge );
   77912       assert( TK_EQ==OP_Eq );
   77913       assert( TK_NE==OP_Ne );
   77914       testcase( op==TK_LT );
   77915       testcase( op==TK_LE );
   77916       testcase( op==TK_GT );
   77917       testcase( op==TK_GE );
   77918       testcase( op==TK_EQ );
   77919       testcase( op==TK_NE );
   77920       testcase( jumpIfNull==0 );
   77921       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77922       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   77923       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   77924                   r1, r2, dest, jumpIfNull);
   77925       testcase( regFree1==0 );
   77926       testcase( regFree2==0 );
   77927       break;
   77928     }
   77929     case TK_IS:
   77930     case TK_ISNOT: {
   77931       testcase( op==TK_IS );
   77932       testcase( op==TK_ISNOT );
   77933       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77934       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   77935       op = (op==TK_IS) ? TK_EQ : TK_NE;
   77936       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   77937                   r1, r2, dest, SQLITE_NULLEQ);
   77938       testcase( regFree1==0 );
   77939       testcase( regFree2==0 );
   77940       break;
   77941     }
   77942     case TK_ISNULL:
   77943     case TK_NOTNULL: {
   77944       assert( TK_ISNULL==OP_IsNull );
   77945       assert( TK_NOTNULL==OP_NotNull );
   77946       testcase( op==TK_ISNULL );
   77947       testcase( op==TK_NOTNULL );
   77948       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77949       sqlite3VdbeAddOp2(v, op, r1, dest);
   77950       testcase( regFree1==0 );
   77951       break;
   77952     }
   77953     case TK_BETWEEN: {
   77954       testcase( jumpIfNull==0 );
   77955       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   77956       break;
   77957     }
   77958 #ifndef SQLITE_OMIT_SUBQUERY
   77959     case TK_IN: {
   77960       int destIfFalse = sqlite3VdbeMakeLabel(v);
   77961       int destIfNull = jumpIfNull ? dest : destIfFalse;
   77962       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   77963       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   77964       sqlite3VdbeResolveLabel(v, destIfFalse);
   77965       break;
   77966     }
   77967 #endif
   77968     default: {
   77969       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   77970       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   77971       testcase( regFree1==0 );
   77972       testcase( jumpIfNull==0 );
   77973       break;
   77974     }
   77975   }
   77976   sqlite3ReleaseTempReg(pParse, regFree1);
   77977   sqlite3ReleaseTempReg(pParse, regFree2);
   77978 }
   77979 
   77980 /*
   77981 ** Generate code for a boolean expression such that a jump is made
   77982 ** to the label "dest" if the expression is false but execution
   77983 ** continues straight thru if the expression is true.
   77984 **
   77985 ** If the expression evaluates to NULL (neither true nor false) then
   77986 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   77987 ** is 0.
   77988 */
   77989 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   77990   Vdbe *v = pParse->pVdbe;
   77991   int op = 0;
   77992   int regFree1 = 0;
   77993   int regFree2 = 0;
   77994   int r1, r2;
   77995 
   77996   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   77997   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
   77998   if( pExpr==0 )    return;
   77999 
   78000   /* The value of pExpr->op and op are related as follows:
   78001   **
   78002   **       pExpr->op            op
   78003   **       ---------          ----------
   78004   **       TK_ISNULL          OP_NotNull
   78005   **       TK_NOTNULL         OP_IsNull
   78006   **       TK_NE              OP_Eq
   78007   **       TK_EQ              OP_Ne
   78008   **       TK_GT              OP_Le
   78009   **       TK_LE              OP_Gt
   78010   **       TK_GE              OP_Lt
   78011   **       TK_LT              OP_Ge
   78012   **
   78013   ** For other values of pExpr->op, op is undefined and unused.
   78014   ** The value of TK_ and OP_ constants are arranged such that we
   78015   ** can compute the mapping above using the following expression.
   78016   ** Assert()s verify that the computation is correct.
   78017   */
   78018   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   78019 
   78020   /* Verify correct alignment of TK_ and OP_ constants
   78021   */
   78022   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   78023   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   78024   assert( pExpr->op!=TK_NE || op==OP_Eq );
   78025   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   78026   assert( pExpr->op!=TK_LT || op==OP_Ge );
   78027   assert( pExpr->op!=TK_LE || op==OP_Gt );
   78028   assert( pExpr->op!=TK_GT || op==OP_Le );
   78029   assert( pExpr->op!=TK_GE || op==OP_Lt );
   78030 
   78031   switch( pExpr->op ){
   78032     case TK_AND: {
   78033       testcase( jumpIfNull==0 );
   78034       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   78035       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   78036       break;
   78037     }
   78038     case TK_OR: {
   78039       int d2 = sqlite3VdbeMakeLabel(v);
   78040       testcase( jumpIfNull==0 );
   78041       sqlite3ExprCachePush(pParse);
   78042       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   78043       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   78044       sqlite3VdbeResolveLabel(v, d2);
   78045       sqlite3ExprCachePop(pParse, 1);
   78046       break;
   78047     }
   78048     case TK_NOT: {
   78049       testcase( jumpIfNull==0 );
   78050       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   78051       break;
   78052     }
   78053     case TK_LT:
   78054     case TK_LE:
   78055     case TK_GT:
   78056     case TK_GE:
   78057     case TK_NE:
   78058     case TK_EQ: {
   78059       testcase( op==TK_LT );
   78060       testcase( op==TK_LE );
   78061       testcase( op==TK_GT );
   78062       testcase( op==TK_GE );
   78063       testcase( op==TK_EQ );
   78064       testcase( op==TK_NE );
   78065       testcase( jumpIfNull==0 );
   78066       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78067       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   78068       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   78069                   r1, r2, dest, jumpIfNull);
   78070       testcase( regFree1==0 );
   78071       testcase( regFree2==0 );
   78072       break;
   78073     }
   78074     case TK_IS:
   78075     case TK_ISNOT: {
   78076       testcase( pExpr->op==TK_IS );
   78077       testcase( pExpr->op==TK_ISNOT );
   78078       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78079       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   78080       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   78081       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   78082                   r1, r2, dest, SQLITE_NULLEQ);
   78083       testcase( regFree1==0 );
   78084       testcase( regFree2==0 );
   78085       break;
   78086     }
   78087     case TK_ISNULL:
   78088     case TK_NOTNULL: {
   78089       testcase( op==TK_ISNULL );
   78090       testcase( op==TK_NOTNULL );
   78091       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78092       sqlite3VdbeAddOp2(v, op, r1, dest);
   78093       testcase( regFree1==0 );
   78094       break;
   78095     }
   78096     case TK_BETWEEN: {
   78097       testcase( jumpIfNull==0 );
   78098       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   78099       break;
   78100     }
   78101 #ifndef SQLITE_OMIT_SUBQUERY
   78102     case TK_IN: {
   78103       if( jumpIfNull ){
   78104         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   78105       }else{
   78106         int destIfNull = sqlite3VdbeMakeLabel(v);
   78107         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   78108         sqlite3VdbeResolveLabel(v, destIfNull);
   78109       }
   78110       break;
   78111     }
   78112 #endif
   78113     default: {
   78114       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   78115       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   78116       testcase( regFree1==0 );
   78117       testcase( jumpIfNull==0 );
   78118       break;
   78119     }
   78120   }
   78121   sqlite3ReleaseTempReg(pParse, regFree1);
   78122   sqlite3ReleaseTempReg(pParse, regFree2);
   78123 }
   78124 
   78125 /*
   78126 ** Do a deep comparison of two expression trees.  Return 0 if the two
   78127 ** expressions are completely identical.  Return 1 if they differ only
   78128 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   78129 ** other than the top-level COLLATE operator.
   78130 **
   78131 ** Sometimes this routine will return 2 even if the two expressions
   78132 ** really are equivalent.  If we cannot prove that the expressions are
   78133 ** identical, we return 2 just to be safe.  So if this routine
   78134 ** returns 2, then you do not really know for certain if the two
   78135 ** expressions are the same.  But if you get a 0 or 1 return, then you
   78136 ** can be sure the expressions are the same.  In the places where
   78137 ** this routine is used, it does not hurt to get an extra 2 - that
   78138 ** just might result in some slightly slower code.  But returning
   78139 ** an incorrect 0 or 1 could lead to a malfunction.
   78140 */
   78141 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
   78142   if( pA==0||pB==0 ){
   78143     return pB==pA ? 0 : 2;
   78144   }
   78145   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
   78146   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
   78147   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
   78148     return 2;
   78149   }
   78150   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   78151   if( pA->op!=pB->op ) return 2;
   78152   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
   78153   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
   78154   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
   78155   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
   78156   if( ExprHasProperty(pA, EP_IntValue) ){
   78157     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
   78158       return 2;
   78159     }
   78160   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
   78161     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
   78162     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
   78163       return 2;
   78164     }
   78165   }
   78166   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
   78167   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
   78168   return 0;
   78169 }
   78170 
   78171 /*
   78172 ** Compare two ExprList objects.  Return 0 if they are identical and
   78173 ** non-zero if they differ in any way.
   78174 **
   78175 ** This routine might return non-zero for equivalent ExprLists.  The
   78176 ** only consequence will be disabled optimizations.  But this routine
   78177 ** must never return 0 if the two ExprList objects are different, or
   78178 ** a malfunction will result.
   78179 **
   78180 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   78181 ** always differs from a non-NULL pointer.
   78182 */
   78183 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
   78184   int i;
   78185   if( pA==0 && pB==0 ) return 0;
   78186   if( pA==0 || pB==0 ) return 1;
   78187   if( pA->nExpr!=pB->nExpr ) return 1;
   78188   for(i=0; i<pA->nExpr; i++){
   78189     Expr *pExprA = pA->a[i].pExpr;
   78190     Expr *pExprB = pB->a[i].pExpr;
   78191     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   78192     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
   78193   }
   78194   return 0;
   78195 }
   78196 
   78197 /*
   78198 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   78199 ** the new element.  Return a negative number if malloc fails.
   78200 */
   78201 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   78202   int i;
   78203   pInfo->aCol = sqlite3ArrayAllocate(
   78204        db,
   78205        pInfo->aCol,
   78206        sizeof(pInfo->aCol[0]),
   78207        &pInfo->nColumn,
   78208        &i
   78209   );
   78210   return i;
   78211 }
   78212 
   78213 /*
   78214 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   78215 ** the new element.  Return a negative number if malloc fails.
   78216 */
   78217 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   78218   int i;
   78219   pInfo->aFunc = sqlite3ArrayAllocate(
   78220        db,
   78221        pInfo->aFunc,
   78222        sizeof(pInfo->aFunc[0]),
   78223        &pInfo->nFunc,
   78224        &i
   78225   );
   78226   return i;
   78227 }
   78228 
   78229 /*
   78230 ** This is the xExprCallback for a tree walker.  It is used to
   78231 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   78232 ** for additional information.
   78233 */
   78234 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   78235   int i;
   78236   NameContext *pNC = pWalker->u.pNC;
   78237   Parse *pParse = pNC->pParse;
   78238   SrcList *pSrcList = pNC->pSrcList;
   78239   AggInfo *pAggInfo = pNC->pAggInfo;
   78240 
   78241   switch( pExpr->op ){
   78242     case TK_AGG_COLUMN:
   78243     case TK_COLUMN: {
   78244       testcase( pExpr->op==TK_AGG_COLUMN );
   78245       testcase( pExpr->op==TK_COLUMN );
   78246       /* Check to see if the column is in one of the tables in the FROM
   78247       ** clause of the aggregate query */
   78248       if( ALWAYS(pSrcList!=0) ){
   78249         struct SrcList_item *pItem = pSrcList->a;
   78250         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   78251           struct AggInfo_col *pCol;
   78252           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   78253           if( pExpr->iTable==pItem->iCursor ){
   78254             /* If we reach this point, it means that pExpr refers to a table
   78255             ** that is in the FROM clause of the aggregate query.
   78256             **
   78257             ** Make an entry for the column in pAggInfo->aCol[] if there
   78258             ** is not an entry there already.
   78259             */
   78260             int k;
   78261             pCol = pAggInfo->aCol;
   78262             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   78263               if( pCol->iTable==pExpr->iTable &&
   78264                   pCol->iColumn==pExpr->iColumn ){
   78265                 break;
   78266               }
   78267             }
   78268             if( (k>=pAggInfo->nColumn)
   78269              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   78270             ){
   78271               pCol = &pAggInfo->aCol[k];
   78272               pCol->pTab = pExpr->pTab;
   78273               pCol->iTable = pExpr->iTable;
   78274               pCol->iColumn = pExpr->iColumn;
   78275               pCol->iMem = ++pParse->nMem;
   78276               pCol->iSorterColumn = -1;
   78277               pCol->pExpr = pExpr;
   78278               if( pAggInfo->pGroupBy ){
   78279                 int j, n;
   78280                 ExprList *pGB = pAggInfo->pGroupBy;
   78281                 struct ExprList_item *pTerm = pGB->a;
   78282                 n = pGB->nExpr;
   78283                 for(j=0; j<n; j++, pTerm++){
   78284                   Expr *pE = pTerm->pExpr;
   78285                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   78286                       pE->iColumn==pExpr->iColumn ){
   78287                     pCol->iSorterColumn = j;
   78288                     break;
   78289                   }
   78290                 }
   78291               }
   78292               if( pCol->iSorterColumn<0 ){
   78293                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   78294               }
   78295             }
   78296             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   78297             ** because it was there before or because we just created it).
   78298             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   78299             ** pAggInfo->aCol[] entry.
   78300             */
   78301             ExprSetIrreducible(pExpr);
   78302             pExpr->pAggInfo = pAggInfo;
   78303             pExpr->op = TK_AGG_COLUMN;
   78304             pExpr->iAgg = (i16)k;
   78305             break;
   78306           } /* endif pExpr->iTable==pItem->iCursor */
   78307         } /* end loop over pSrcList */
   78308       }
   78309       return WRC_Prune;
   78310     }
   78311     case TK_AGG_FUNCTION: {
   78312       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
   78313       ** to be ignored */
   78314       if( pNC->nDepth==0 ){
   78315         /* Check to see if pExpr is a duplicate of another aggregate
   78316         ** function that is already in the pAggInfo structure
   78317         */
   78318         struct AggInfo_func *pItem = pAggInfo->aFunc;
   78319         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   78320           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
   78321             break;
   78322           }
   78323         }
   78324         if( i>=pAggInfo->nFunc ){
   78325           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   78326           */
   78327           u8 enc = ENC(pParse->db);
   78328           i = addAggInfoFunc(pParse->db, pAggInfo);
   78329           if( i>=0 ){
   78330             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   78331             pItem = &pAggInfo->aFunc[i];
   78332             pItem->pExpr = pExpr;
   78333             pItem->iMem = ++pParse->nMem;
   78334             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   78335             pItem->pFunc = sqlite3FindFunction(pParse->db,
   78336                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   78337                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   78338             if( pExpr->flags & EP_Distinct ){
   78339               pItem->iDistinct = pParse->nTab++;
   78340             }else{
   78341               pItem->iDistinct = -1;
   78342             }
   78343           }
   78344         }
   78345         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   78346         */
   78347         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   78348         ExprSetIrreducible(pExpr);
   78349         pExpr->iAgg = (i16)i;
   78350         pExpr->pAggInfo = pAggInfo;
   78351         return WRC_Prune;
   78352       }
   78353     }
   78354   }
   78355   return WRC_Continue;
   78356 }
   78357 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   78358   NameContext *pNC = pWalker->u.pNC;
   78359   if( pNC->nDepth==0 ){
   78360     pNC->nDepth++;
   78361     sqlite3WalkSelect(pWalker, pSelect);
   78362     pNC->nDepth--;
   78363     return WRC_Prune;
   78364   }else{
   78365     return WRC_Continue;
   78366   }
   78367 }
   78368 
   78369 /*
   78370 ** Analyze the given expression looking for aggregate functions and
   78371 ** for variables that need to be added to the pParse->aAgg[] array.
   78372 ** Make additional entries to the pParse->aAgg[] array as necessary.
   78373 **
   78374 ** This routine should only be called after the expression has been
   78375 ** analyzed by sqlite3ResolveExprNames().
   78376 */
   78377 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   78378   Walker w;
   78379   w.xExprCallback = analyzeAggregate;
   78380   w.xSelectCallback = analyzeAggregatesInSelect;
   78381   w.u.pNC = pNC;
   78382   assert( pNC->pSrcList!=0 );
   78383   sqlite3WalkExpr(&w, pExpr);
   78384 }
   78385 
   78386 /*
   78387 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   78388 ** expression list.  Return the number of errors.
   78389 **
   78390 ** If an error is found, the analysis is cut short.
   78391 */
   78392 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   78393   struct ExprList_item *pItem;
   78394   int i;
   78395   if( pList ){
   78396     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   78397       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   78398     }
   78399   }
   78400 }
   78401 
   78402 /*
   78403 ** Allocate a single new register for use to hold some intermediate result.
   78404 */
   78405 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   78406   if( pParse->nTempReg==0 ){
   78407     return ++pParse->nMem;
   78408   }
   78409   return pParse->aTempReg[--pParse->nTempReg];
   78410 }
   78411 
   78412 /*
   78413 ** Deallocate a register, making available for reuse for some other
   78414 ** purpose.
   78415 **
   78416 ** If a register is currently being used by the column cache, then
   78417 ** the dallocation is deferred until the column cache line that uses
   78418 ** the register becomes stale.
   78419 */
   78420 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   78421   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   78422     int i;
   78423     struct yColCache *p;
   78424     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   78425       if( p->iReg==iReg ){
   78426         p->tempReg = 1;
   78427         return;
   78428       }
   78429     }
   78430     pParse->aTempReg[pParse->nTempReg++] = iReg;
   78431   }
   78432 }
   78433 
   78434 /*
   78435 ** Allocate or deallocate a block of nReg consecutive registers
   78436 */
   78437 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   78438   int i, n;
   78439   i = pParse->iRangeReg;
   78440   n = pParse->nRangeReg;
   78441   if( nReg<=n ){
   78442     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   78443     pParse->iRangeReg += nReg;
   78444     pParse->nRangeReg -= nReg;
   78445   }else{
   78446     i = pParse->nMem+1;
   78447     pParse->nMem += nReg;
   78448   }
   78449   return i;
   78450 }
   78451 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   78452   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   78453   if( nReg>pParse->nRangeReg ){
   78454     pParse->nRangeReg = nReg;
   78455     pParse->iRangeReg = iReg;
   78456   }
   78457 }
   78458 
   78459 /*
   78460 ** Mark all temporary registers as being unavailable for reuse.
   78461 */
   78462 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
   78463   pParse->nTempReg = 0;
   78464   pParse->nRangeReg = 0;
   78465 }
   78466 
   78467 /************** End of expr.c ************************************************/
   78468 /************** Begin file alter.c *******************************************/
   78469 /*
   78470 ** 2005 February 15
   78471 **
   78472 ** The author disclaims copyright to this source code.  In place of
   78473 ** a legal notice, here is a blessing:
   78474 **
   78475 **    May you do good and not evil.
   78476 **    May you find forgiveness for yourself and forgive others.
   78477 **    May you share freely, never taking more than you give.
   78478 **
   78479 *************************************************************************
   78480 ** This file contains C code routines that used to generate VDBE code
   78481 ** that implements the ALTER TABLE command.
   78482 */
   78483 
   78484 /*
   78485 ** The code in this file only exists if we are not omitting the
   78486 ** ALTER TABLE logic from the build.
   78487 */
   78488 #ifndef SQLITE_OMIT_ALTERTABLE
   78489 
   78490 
   78491 /*
   78492 ** This function is used by SQL generated to implement the
   78493 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   78494 ** CREATE INDEX command. The second is a table name. The table name in
   78495 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   78496 ** argument and the result returned. Examples:
   78497 **
   78498 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   78499 **     -> 'CREATE TABLE def(a, b, c)'
   78500 **
   78501 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   78502 **     -> 'CREATE INDEX i ON def(a, b, c)'
   78503 */
   78504 static void renameTableFunc(
   78505   sqlite3_context *context,
   78506   int NotUsed,
   78507   sqlite3_value **argv
   78508 ){
   78509   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   78510   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   78511 
   78512   int token;
   78513   Token tname;
   78514   unsigned char const *zCsr = zSql;
   78515   int len = 0;
   78516   char *zRet;
   78517 
   78518   sqlite3 *db = sqlite3_context_db_handle(context);
   78519 
   78520   UNUSED_PARAMETER(NotUsed);
   78521 
   78522   /* The principle used to locate the table name in the CREATE TABLE
   78523   ** statement is that the table name is the first non-space token that
   78524   ** is immediately followed by a TK_LP or TK_USING token.
   78525   */
   78526   if( zSql ){
   78527     do {
   78528       if( !*zCsr ){
   78529         /* Ran out of input before finding an opening bracket. Return NULL. */
   78530         return;
   78531       }
   78532 
   78533       /* Store the token that zCsr points to in tname. */
   78534       tname.z = (char*)zCsr;
   78535       tname.n = len;
   78536 
   78537       /* Advance zCsr to the next token. Store that token type in 'token',
   78538       ** and its length in 'len' (to be used next iteration of this loop).
   78539       */
   78540       do {
   78541         zCsr += len;
   78542         len = sqlite3GetToken(zCsr, &token);
   78543       } while( token==TK_SPACE );
   78544       assert( len>0 );
   78545     } while( token!=TK_LP && token!=TK_USING );
   78546 
   78547     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   78548        zTableName, tname.z+tname.n);
   78549     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   78550   }
   78551 }
   78552 
   78553 /*
   78554 ** This C function implements an SQL user function that is used by SQL code
   78555 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   78556 ** of any foreign key constraints that use the table being renamed as the
   78557 ** parent table. It is passed three arguments:
   78558 **
   78559 **   1) The complete text of the CREATE TABLE statement being modified,
   78560 **   2) The old name of the table being renamed, and
   78561 **   3) The new name of the table being renamed.
   78562 **
   78563 ** It returns the new CREATE TABLE statement. For example:
   78564 **
   78565 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   78566 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   78567 */
   78568 #ifndef SQLITE_OMIT_FOREIGN_KEY
   78569 static void renameParentFunc(
   78570   sqlite3_context *context,
   78571   int NotUsed,
   78572   sqlite3_value **argv
   78573 ){
   78574   sqlite3 *db = sqlite3_context_db_handle(context);
   78575   char *zOutput = 0;
   78576   char *zResult;
   78577   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   78578   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   78579   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   78580 
   78581   unsigned const char *z;         /* Pointer to token */
   78582   int n;                          /* Length of token z */
   78583   int token;                      /* Type of token */
   78584 
   78585   UNUSED_PARAMETER(NotUsed);
   78586   for(z=zInput; *z; z=z+n){
   78587     n = sqlite3GetToken(z, &token);
   78588     if( token==TK_REFERENCES ){
   78589       char *zParent;
   78590       do {
   78591         z += n;
   78592         n = sqlite3GetToken(z, &token);
   78593       }while( token==TK_SPACE );
   78594 
   78595       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   78596       if( zParent==0 ) break;
   78597       sqlite3Dequote(zParent);
   78598       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   78599         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   78600             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
   78601         );
   78602         sqlite3DbFree(db, zOutput);
   78603         zOutput = zOut;
   78604         zInput = &z[n];
   78605       }
   78606       sqlite3DbFree(db, zParent);
   78607     }
   78608   }
   78609 
   78610   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   78611   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   78612   sqlite3DbFree(db, zOutput);
   78613 }
   78614 #endif
   78615 
   78616 #ifndef SQLITE_OMIT_TRIGGER
   78617 /* This function is used by SQL generated to implement the
   78618 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   78619 ** statement. The second is a table name. The table name in the CREATE
   78620 ** TRIGGER statement is replaced with the third argument and the result
   78621 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   78622 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   78623 */
   78624 static void renameTriggerFunc(
   78625   sqlite3_context *context,
   78626   int NotUsed,
   78627   sqlite3_value **argv
   78628 ){
   78629   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   78630   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   78631 
   78632   int token;
   78633   Token tname;
   78634   int dist = 3;
   78635   unsigned char const *zCsr = zSql;
   78636   int len = 0;
   78637   char *zRet;
   78638   sqlite3 *db = sqlite3_context_db_handle(context);
   78639 
   78640   UNUSED_PARAMETER(NotUsed);
   78641 
   78642   /* The principle used to locate the table name in the CREATE TRIGGER
   78643   ** statement is that the table name is the first token that is immediatedly
   78644   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   78645   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   78646   */
   78647   if( zSql ){
   78648     do {
   78649 
   78650       if( !*zCsr ){
   78651         /* Ran out of input before finding the table name. Return NULL. */
   78652         return;
   78653       }
   78654 
   78655       /* Store the token that zCsr points to in tname. */
   78656       tname.z = (char*)zCsr;
   78657       tname.n = len;
   78658 
   78659       /* Advance zCsr to the next token. Store that token type in 'token',
   78660       ** and its length in 'len' (to be used next iteration of this loop).
   78661       */
   78662       do {
   78663         zCsr += len;
   78664         len = sqlite3GetToken(zCsr, &token);
   78665       }while( token==TK_SPACE );
   78666       assert( len>0 );
   78667 
   78668       /* Variable 'dist' stores the number of tokens read since the most
   78669       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   78670       ** token is read and 'dist' equals 2, the condition stated above
   78671       ** to be met.
   78672       **
   78673       ** Note that ON cannot be a database, table or column name, so
   78674       ** there is no need to worry about syntax like
   78675       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   78676       */
   78677       dist++;
   78678       if( token==TK_DOT || token==TK_ON ){
   78679         dist = 0;
   78680       }
   78681     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   78682 
   78683     /* Variable tname now contains the token that is the old table-name
   78684     ** in the CREATE TRIGGER statement.
   78685     */
   78686     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   78687        zTableName, tname.z+tname.n);
   78688     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   78689   }
   78690 }
   78691 #endif   /* !SQLITE_OMIT_TRIGGER */
   78692 
   78693 /*
   78694 ** Register built-in functions used to help implement ALTER TABLE
   78695 */
   78696 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   78697   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
   78698     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   78699 #ifndef SQLITE_OMIT_TRIGGER
   78700     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   78701 #endif
   78702 #ifndef SQLITE_OMIT_FOREIGN_KEY
   78703     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   78704 #endif
   78705   };
   78706   int i;
   78707   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   78708   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
   78709 
   78710   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
   78711     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   78712   }
   78713 }
   78714 
   78715 /*
   78716 ** This function is used to create the text of expressions of the form:
   78717 **
   78718 **   name=<constant1> OR name=<constant2> OR ...
   78719 **
   78720 ** If argument zWhere is NULL, then a pointer string containing the text
   78721 ** "name=<constant>" is returned, where <constant> is the quoted version
   78722 ** of the string passed as argument zConstant. The returned buffer is
   78723 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   78724 ** caller to ensure that it is eventually freed.
   78725 **
   78726 ** If argument zWhere is not NULL, then the string returned is
   78727 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   78728 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   78729 **
   78730 */
   78731 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   78732   char *zNew;
   78733   if( !zWhere ){
   78734     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   78735   }else{
   78736     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   78737     sqlite3DbFree(db, zWhere);
   78738   }
   78739   return zNew;
   78740 }
   78741 
   78742 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   78743 /*
   78744 ** Generate the text of a WHERE expression which can be used to select all
   78745 ** tables that have foreign key constraints that refer to table pTab (i.e.
   78746 ** constraints for which pTab is the parent table) from the sqlite_master
   78747 ** table.
   78748 */
   78749 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   78750   FKey *p;
   78751   char *zWhere = 0;
   78752   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   78753     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   78754   }
   78755   return zWhere;
   78756 }
   78757 #endif
   78758 
   78759 /*
   78760 ** Generate the text of a WHERE expression which can be used to select all
   78761 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   78762 ** table pTab has no temporary triggers, or is itself stored in the
   78763 ** temporary database, NULL is returned.
   78764 */
   78765 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   78766   Trigger *pTrig;
   78767   char *zWhere = 0;
   78768   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   78769 
   78770   /* If the table is not located in the temp-db (in which case NULL is
   78771   ** returned, loop through the tables list of triggers. For each trigger
   78772   ** that is not part of the temp-db schema, add a clause to the WHERE
   78773   ** expression being built up in zWhere.
   78774   */
   78775   if( pTab->pSchema!=pTempSchema ){
   78776     sqlite3 *db = pParse->db;
   78777     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   78778       if( pTrig->pSchema==pTempSchema ){
   78779         zWhere = whereOrName(db, zWhere, pTrig->zName);
   78780       }
   78781     }
   78782   }
   78783   if( zWhere ){
   78784     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   78785     sqlite3DbFree(pParse->db, zWhere);
   78786     zWhere = zNew;
   78787   }
   78788   return zWhere;
   78789 }
   78790 
   78791 /*
   78792 ** Generate code to drop and reload the internal representation of table
   78793 ** pTab from the database, including triggers and temporary triggers.
   78794 ** Argument zName is the name of the table in the database schema at
   78795 ** the time the generated code is executed. This can be different from
   78796 ** pTab->zName if this function is being called to code part of an
   78797 ** "ALTER TABLE RENAME TO" statement.
   78798 */
   78799 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   78800   Vdbe *v;
   78801   char *zWhere;
   78802   int iDb;                   /* Index of database containing pTab */
   78803 #ifndef SQLITE_OMIT_TRIGGER
   78804   Trigger *pTrig;
   78805 #endif
   78806 
   78807   v = sqlite3GetVdbe(pParse);
   78808   if( NEVER(v==0) ) return;
   78809   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   78810   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   78811   assert( iDb>=0 );
   78812 
   78813 #ifndef SQLITE_OMIT_TRIGGER
   78814   /* Drop any table triggers from the internal schema. */
   78815   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   78816     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   78817     assert( iTrigDb==iDb || iTrigDb==1 );
   78818     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   78819   }
   78820 #endif
   78821 
   78822   /* Drop the table and index from the internal schema.  */
   78823   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   78824 
   78825   /* Reload the table, index and permanent trigger schemas. */
   78826   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   78827   if( !zWhere ) return;
   78828   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   78829 
   78830 #ifndef SQLITE_OMIT_TRIGGER
   78831   /* Now, if the table is not stored in the temp database, reload any temp
   78832   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   78833   */
   78834   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   78835     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
   78836   }
   78837 #endif
   78838 }
   78839 
   78840 /*
   78841 ** Parameter zName is the name of a table that is about to be altered
   78842 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
   78843 ** If the table is a system table, this function leaves an error message
   78844 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
   78845 **
   78846 ** Or, if zName is not a system table, zero is returned.
   78847 */
   78848 static int isSystemTable(Parse *pParse, const char *zName){
   78849   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   78850     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
   78851     return 1;
   78852   }
   78853   return 0;
   78854 }
   78855 
   78856 /*
   78857 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   78858 ** command.
   78859 */
   78860 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   78861   Parse *pParse,            /* Parser context. */
   78862   SrcList *pSrc,            /* The table to rename. */
   78863   Token *pName              /* The new table name. */
   78864 ){
   78865   int iDb;                  /* Database that contains the table */
   78866   char *zDb;                /* Name of database iDb */
   78867   Table *pTab;              /* Table being renamed */
   78868   char *zName = 0;          /* NULL-terminated version of pName */
   78869   sqlite3 *db = pParse->db; /* Database connection */
   78870   int nTabName;             /* Number of UTF-8 characters in zTabName */
   78871   const char *zTabName;     /* Original name of the table */
   78872   Vdbe *v;
   78873 #ifndef SQLITE_OMIT_TRIGGER
   78874   char *zWhere = 0;         /* Where clause to locate temp triggers */
   78875 #endif
   78876   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   78877   int savedDbFlags;         /* Saved value of db->flags */
   78878 
   78879   savedDbFlags = db->flags;
   78880   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   78881   assert( pSrc->nSrc==1 );
   78882   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   78883 
   78884   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   78885   if( !pTab ) goto exit_rename_table;
   78886   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   78887   zDb = db->aDb[iDb].zName;
   78888   db->flags |= SQLITE_PreferBuiltin;
   78889 
   78890   /* Get a NULL terminated version of the new table name. */
   78891   zName = sqlite3NameFromToken(db, pName);
   78892   if( !zName ) goto exit_rename_table;
   78893 
   78894   /* Check that a table or index named 'zName' does not already exist
   78895   ** in database iDb. If so, this is an error.
   78896   */
   78897   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   78898     sqlite3ErrorMsg(pParse,
   78899         "there is already another table or index with this name: %s", zName);
   78900     goto exit_rename_table;
   78901   }
   78902 
   78903   /* Make sure it is not a system table being altered, or a reserved name
   78904   ** that the table is being renamed to.
   78905   */
   78906   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   78907     goto exit_rename_table;
   78908   }
   78909   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
   78910     exit_rename_table;
   78911   }
   78912 
   78913 #ifndef SQLITE_OMIT_VIEW
   78914   if( pTab->pSelect ){
   78915     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   78916     goto exit_rename_table;
   78917   }
   78918 #endif
   78919 
   78920 #ifndef SQLITE_OMIT_AUTHORIZATION
   78921   /* Invoke the authorization callback. */
   78922   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   78923     goto exit_rename_table;
   78924   }
   78925 #endif
   78926 
   78927 #ifndef SQLITE_OMIT_VIRTUALTABLE
   78928   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   78929     goto exit_rename_table;
   78930   }
   78931   if( IsVirtual(pTab) ){
   78932     pVTab = sqlite3GetVTable(db, pTab);
   78933     if( pVTab->pVtab->pModule->xRename==0 ){
   78934       pVTab = 0;
   78935     }
   78936   }
   78937 #endif
   78938 
   78939   /* Begin a transaction and code the VerifyCookie for database iDb.
   78940   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   78941   ** schema). Open a statement transaction if the table is a virtual
   78942   ** table.
   78943   */
   78944   v = sqlite3GetVdbe(pParse);
   78945   if( v==0 ){
   78946     goto exit_rename_table;
   78947   }
   78948   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   78949   sqlite3ChangeCookie(pParse, iDb);
   78950 
   78951   /* If this is a virtual table, invoke the xRename() function if
   78952   ** one is defined. The xRename() callback will modify the names
   78953   ** of any resources used by the v-table implementation (including other
   78954   ** SQLite tables) that are identified by the name of the virtual table.
   78955   */
   78956 #ifndef SQLITE_OMIT_VIRTUALTABLE
   78957   if( pVTab ){
   78958     int i = ++pParse->nMem;
   78959     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   78960     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   78961     sqlite3MayAbort(pParse);
   78962   }
   78963 #endif
   78964 
   78965   /* figure out how many UTF-8 characters are in zName */
   78966   zTabName = pTab->zName;
   78967   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   78968 
   78969 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   78970   if( db->flags&SQLITE_ForeignKeys ){
   78971     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   78972     ** statements corresponding to all child tables of foreign key constraints
   78973     ** for which the renamed table is the parent table.  */
   78974     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   78975       sqlite3NestedParse(pParse,
   78976           "UPDATE \"%w\".%s SET "
   78977               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   78978               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
   78979       sqlite3DbFree(db, zWhere);
   78980     }
   78981   }
   78982 #endif
   78983 
   78984   /* Modify the sqlite_master table to use the new table name. */
   78985   sqlite3NestedParse(pParse,
   78986       "UPDATE %Q.%s SET "
   78987 #ifdef SQLITE_OMIT_TRIGGER
   78988           "sql = sqlite_rename_table(sql, %Q), "
   78989 #else
   78990           "sql = CASE "
   78991             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   78992             "ELSE sqlite_rename_table(sql, %Q) END, "
   78993 #endif
   78994           "tbl_name = %Q, "
   78995           "name = CASE "
   78996             "WHEN type='table' THEN %Q "
   78997             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   78998              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   78999             "ELSE name END "
   79000       "WHERE tbl_name=%Q COLLATE nocase AND "
   79001           "(type='table' OR type='index' OR type='trigger');",
   79002       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   79003 #ifndef SQLITE_OMIT_TRIGGER
   79004       zName,
   79005 #endif
   79006       zName, nTabName, zTabName
   79007   );
   79008 
   79009 #ifndef SQLITE_OMIT_AUTOINCREMENT
   79010   /* If the sqlite_sequence table exists in this database, then update
   79011   ** it with the new table name.
   79012   */
   79013   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   79014     sqlite3NestedParse(pParse,
   79015         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   79016         zDb, zName, pTab->zName);
   79017   }
   79018 #endif
   79019 
   79020 #ifndef SQLITE_OMIT_TRIGGER
   79021   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   79022   ** table. Don't do this if the table being ALTERed is itself located in
   79023   ** the temp database.
   79024   */
   79025   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   79026     sqlite3NestedParse(pParse,
   79027         "UPDATE sqlite_temp_master SET "
   79028             "sql = sqlite_rename_trigger(sql, %Q), "
   79029             "tbl_name = %Q "
   79030             "WHERE %s;", zName, zName, zWhere);
   79031     sqlite3DbFree(db, zWhere);
   79032   }
   79033 #endif
   79034 
   79035 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   79036   if( db->flags&SQLITE_ForeignKeys ){
   79037     FKey *p;
   79038     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   79039       Table *pFrom = p->pFrom;
   79040       if( pFrom!=pTab ){
   79041         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   79042       }
   79043     }
   79044   }
   79045 #endif
   79046 
   79047   /* Drop and reload the internal table schema. */
   79048   reloadTableSchema(pParse, pTab, zName);
   79049 
   79050 exit_rename_table:
   79051   sqlite3SrcListDelete(db, pSrc);
   79052   sqlite3DbFree(db, zName);
   79053   db->flags = savedDbFlags;
   79054 }
   79055 
   79056 
   79057 /*
   79058 ** Generate code to make sure the file format number is at least minFormat.
   79059 ** The generated code will increase the file format number if necessary.
   79060 */
   79061 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   79062   Vdbe *v;
   79063   v = sqlite3GetVdbe(pParse);
   79064   /* The VDBE should have been allocated before this routine is called.
   79065   ** If that allocation failed, we would have quit before reaching this
   79066   ** point */
   79067   if( ALWAYS(v) ){
   79068     int r1 = sqlite3GetTempReg(pParse);
   79069     int r2 = sqlite3GetTempReg(pParse);
   79070     int j1;
   79071     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   79072     sqlite3VdbeUsesBtree(v, iDb);
   79073     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   79074     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   79075     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   79076     sqlite3VdbeJumpHere(v, j1);
   79077     sqlite3ReleaseTempReg(pParse, r1);
   79078     sqlite3ReleaseTempReg(pParse, r2);
   79079   }
   79080 }
   79081 
   79082 /*
   79083 ** This function is called after an "ALTER TABLE ... ADD" statement
   79084 ** has been parsed. Argument pColDef contains the text of the new
   79085 ** column definition.
   79086 **
   79087 ** The Table structure pParse->pNewTable was extended to include
   79088 ** the new column during parsing.
   79089 */
   79090 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   79091   Table *pNew;              /* Copy of pParse->pNewTable */
   79092   Table *pTab;              /* Table being altered */
   79093   int iDb;                  /* Database number */
   79094   const char *zDb;          /* Database name */
   79095   const char *zTab;         /* Table name */
   79096   char *zCol;               /* Null-terminated column definition */
   79097   Column *pCol;             /* The new column */
   79098   Expr *pDflt;              /* Default value for the new column */
   79099   sqlite3 *db;              /* The database connection; */
   79100 
   79101   db = pParse->db;
   79102   if( pParse->nErr || db->mallocFailed ) return;
   79103   pNew = pParse->pNewTable;
   79104   assert( pNew );
   79105 
   79106   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79107   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   79108   zDb = db->aDb[iDb].zName;
   79109   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   79110   pCol = &pNew->aCol[pNew->nCol-1];
   79111   pDflt = pCol->pDflt;
   79112   pTab = sqlite3FindTable(db, zTab, zDb);
   79113   assert( pTab );
   79114 
   79115 #ifndef SQLITE_OMIT_AUTHORIZATION
   79116   /* Invoke the authorization callback. */
   79117   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   79118     return;
   79119   }
   79120 #endif
   79121 
   79122   /* If the default value for the new column was specified with a
   79123   ** literal NULL, then set pDflt to 0. This simplifies checking
   79124   ** for an SQL NULL default below.
   79125   */
   79126   if( pDflt && pDflt->op==TK_NULL ){
   79127     pDflt = 0;
   79128   }
   79129 
   79130   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   79131   ** If there is a NOT NULL constraint, then the default value for the
   79132   ** column must not be NULL.
   79133   */
   79134   if( pCol->isPrimKey ){
   79135     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   79136     return;
   79137   }
   79138   if( pNew->pIndex ){
   79139     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   79140     return;
   79141   }
   79142   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   79143     sqlite3ErrorMsg(pParse,
   79144         "Cannot add a REFERENCES column with non-NULL default value");
   79145     return;
   79146   }
   79147   if( pCol->notNull && !pDflt ){
   79148     sqlite3ErrorMsg(pParse,
   79149         "Cannot add a NOT NULL column with default value NULL");
   79150     return;
   79151   }
   79152 
   79153   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   79154   ** can handle (i.e. not CURRENT_TIME etc.)
   79155   */
   79156   if( pDflt ){
   79157     sqlite3_value *pVal;
   79158     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   79159       db->mallocFailed = 1;
   79160       return;
   79161     }
   79162     if( !pVal ){
   79163       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   79164       return;
   79165     }
   79166     sqlite3ValueFree(pVal);
   79167   }
   79168 
   79169   /* Modify the CREATE TABLE statement. */
   79170   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   79171   if( zCol ){
   79172     char *zEnd = &zCol[pColDef->n-1];
   79173     int savedDbFlags = db->flags;
   79174     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   79175       *zEnd-- = '\0';
   79176     }
   79177     db->flags |= SQLITE_PreferBuiltin;
   79178     sqlite3NestedParse(pParse,
   79179         "UPDATE \"%w\".%s SET "
   79180           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   79181         "WHERE type = 'table' AND name = %Q",
   79182       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   79183       zTab
   79184     );
   79185     sqlite3DbFree(db, zCol);
   79186     db->flags = savedDbFlags;
   79187   }
   79188 
   79189   /* If the default value of the new column is NULL, then set the file
   79190   ** format to 2. If the default value of the new column is not NULL,
   79191   ** the file format becomes 3.
   79192   */
   79193   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   79194 
   79195   /* Reload the schema of the modified table. */
   79196   reloadTableSchema(pParse, pTab, pTab->zName);
   79197 }
   79198 
   79199 /*
   79200 ** This function is called by the parser after the table-name in
   79201 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   79202 ** pSrc is the full-name of the table being altered.
   79203 **
   79204 ** This routine makes a (partial) copy of the Table structure
   79205 ** for the table being altered and sets Parse.pNewTable to point
   79206 ** to it. Routines called by the parser as the column definition
   79207 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   79208 ** the copy. The copy of the Table structure is deleted by tokenize.c
   79209 ** after parsing is finished.
   79210 **
   79211 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   79212 ** coding the "ALTER TABLE ... ADD" statement.
   79213 */
   79214 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   79215   Table *pNew;
   79216   Table *pTab;
   79217   Vdbe *v;
   79218   int iDb;
   79219   int i;
   79220   int nAlloc;
   79221   sqlite3 *db = pParse->db;
   79222 
   79223   /* Look up the table being altered. */
   79224   assert( pParse->pNewTable==0 );
   79225   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79226   if( db->mallocFailed ) goto exit_begin_add_column;
   79227   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   79228   if( !pTab ) goto exit_begin_add_column;
   79229 
   79230 #ifndef SQLITE_OMIT_VIRTUALTABLE
   79231   if( IsVirtual(pTab) ){
   79232     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   79233     goto exit_begin_add_column;
   79234   }
   79235 #endif
   79236 
   79237   /* Make sure this is not an attempt to ALTER a view. */
   79238   if( pTab->pSelect ){
   79239     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   79240     goto exit_begin_add_column;
   79241   }
   79242   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   79243     goto exit_begin_add_column;
   79244   }
   79245 
   79246   assert( pTab->addColOffset>0 );
   79247   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79248 
   79249   /* Put a copy of the Table struct in Parse.pNewTable for the
   79250   ** sqlite3AddColumn() function and friends to modify.  But modify
   79251   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   79252   ** prefix, we insure that the name will not collide with an existing
   79253   ** table because user table are not allowed to have the "sqlite_"
   79254   ** prefix on their name.
   79255   */
   79256   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   79257   if( !pNew ) goto exit_begin_add_column;
   79258   pParse->pNewTable = pNew;
   79259   pNew->nRef = 1;
   79260   pNew->nCol = pTab->nCol;
   79261   assert( pNew->nCol>0 );
   79262   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   79263   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   79264   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   79265   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   79266   if( !pNew->aCol || !pNew->zName ){
   79267     db->mallocFailed = 1;
   79268     goto exit_begin_add_column;
   79269   }
   79270   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   79271   for(i=0; i<pNew->nCol; i++){
   79272     Column *pCol = &pNew->aCol[i];
   79273     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   79274     pCol->zColl = 0;
   79275     pCol->zType = 0;
   79276     pCol->pDflt = 0;
   79277     pCol->zDflt = 0;
   79278   }
   79279   pNew->pSchema = db->aDb[iDb].pSchema;
   79280   pNew->addColOffset = pTab->addColOffset;
   79281   pNew->nRef = 1;
   79282 
   79283   /* Begin a transaction and increment the schema cookie.  */
   79284   sqlite3BeginWriteOperation(pParse, 0, iDb);
   79285   v = sqlite3GetVdbe(pParse);
   79286   if( !v ) goto exit_begin_add_column;
   79287   sqlite3ChangeCookie(pParse, iDb);
   79288 
   79289 exit_begin_add_column:
   79290   sqlite3SrcListDelete(db, pSrc);
   79291   return;
   79292 }
   79293 #endif  /* SQLITE_ALTER_TABLE */
   79294 
   79295 /************** End of alter.c ***********************************************/
   79296 /************** Begin file analyze.c *****************************************/
   79297 /*
   79298 ** 2005 July 8
   79299 **
   79300 ** The author disclaims copyright to this source code.  In place of
   79301 ** a legal notice, here is a blessing:
   79302 **
   79303 **    May you do good and not evil.
   79304 **    May you find forgiveness for yourself and forgive others.
   79305 **    May you share freely, never taking more than you give.
   79306 **
   79307 *************************************************************************
   79308 ** This file contains code associated with the ANALYZE command.
   79309 **
   79310 ** The ANALYZE command gather statistics about the content of tables
   79311 ** and indices.  These statistics are made available to the query planner
   79312 ** to help it make better decisions about how to perform queries.
   79313 **
   79314 ** The following system tables are or have been supported:
   79315 **
   79316 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
   79317 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
   79318 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
   79319 **
   79320 ** Additional tables might be added in future releases of SQLite.
   79321 ** The sqlite_stat2 table is not created or used unless the SQLite version
   79322 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
   79323 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
   79324 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
   79325 ** created and used by SQLite versions 3.7.9 and later and with
   79326 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
   79327 ** is a superset of sqlite_stat2.
   79328 **
   79329 ** Format of sqlite_stat1:
   79330 **
   79331 ** There is normally one row per index, with the index identified by the
   79332 ** name in the idx column.  The tbl column is the name of the table to
   79333 ** which the index belongs.  In each such row, the stat column will be
   79334 ** a string consisting of a list of integers.  The first integer in this
   79335 ** list is the number of rows in the index and in the table.  The second
   79336 ** integer is the average number of rows in the index that have the same
   79337 ** value in the first column of the index.  The third integer is the average
   79338 ** number of rows in the index that have the same value for the first two
   79339 ** columns.  The N-th integer (for N>1) is the average number of rows in
   79340 ** the index which have the same value for the first N-1 columns.  For
   79341 ** a K-column index, there will be K+1 integers in the stat column.  If
   79342 ** the index is unique, then the last integer will be 1.
   79343 **
   79344 ** The list of integers in the stat column can optionally be followed
   79345 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
   79346 ** must be separated from the last integer by a single space.  If the
   79347 ** "unordered" keyword is present, then the query planner assumes that
   79348 ** the index is unordered and will not use the index for a range query.
   79349 **
   79350 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
   79351 ** column contains a single integer which is the (estimated) number of
   79352 ** rows in the table identified by sqlite_stat1.tbl.
   79353 **
   79354 ** Format of sqlite_stat2:
   79355 **
   79356 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
   79357 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
   79358 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
   79359 ** about the distribution of keys within an index.  The index is identified by
   79360 ** the "idx" column and the "tbl" column is the name of the table to which
   79361 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
   79362 ** table for each index.
   79363 **
   79364 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
   79365 ** inclusive are samples of the left-most key value in the index taken at
   79366 ** evenly spaced points along the index.  Let the number of samples be S
   79367 ** (10 in the standard build) and let C be the number of rows in the index.
   79368 ** Then the sampled rows are given by:
   79369 **
   79370 **     rownumber = (i*C*2 + C)/(S*2)
   79371 **
   79372 ** For i between 0 and S-1.  Conceptually, the index space is divided into
   79373 ** S uniform buckets and the samples are the middle row from each bucket.
   79374 **
   79375 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
   79376 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
   79377 ** writes the sqlite_stat2 table.  This version of SQLite only supports
   79378 ** sqlite_stat3.
   79379 **
   79380 ** Format for sqlite_stat3:
   79381 **
   79382 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
   79383 ** used to avoid compatibility problems.
   79384 **
   79385 ** The format of the sqlite_stat3 table is similar to the format of
   79386 ** the sqlite_stat2 table.  There are multiple entries for each index.
   79387 ** The idx column names the index and the tbl column is the table of the
   79388 ** index.  If the idx and tbl columns are the same, then the sample is
   79389 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
   79390 ** the left-most column of the index.  The nEq column is the approximate
   79391 ** number of entires in the index whose left-most column exactly matches
   79392 ** the sample.  nLt is the approximate number of entires whose left-most
   79393 ** column is less than the sample.  The nDLt column is the approximate
   79394 ** number of distinct left-most entries in the index that are less than
   79395 ** the sample.
   79396 **
   79397 ** Future versions of SQLite might change to store a string containing
   79398 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
   79399 ** integer will be the number of prior index entires that are distinct in
   79400 ** the left-most column.  The second integer will be the number of prior index
   79401 ** entries that are distinct in the first two columns.  The third integer
   79402 ** will be the number of prior index entries that are distinct in the first
   79403 ** three columns.  And so forth.  With that extension, the nDLt field is
   79404 ** similar in function to the sqlite_stat1.stat field.
   79405 **
   79406 ** There can be an arbitrary number of sqlite_stat3 entries per index.
   79407 ** The ANALYZE command will typically generate sqlite_stat3 tables
   79408 ** that contain between 10 and 40 samples which are distributed across
   79409 ** the key space, though not uniformly, and which include samples with
   79410 ** largest possible nEq values.
   79411 */
   79412 #ifndef SQLITE_OMIT_ANALYZE
   79413 
   79414 /*
   79415 ** This routine generates code that opens the sqlite_stat1 table for
   79416 ** writing with cursor iStatCur. If the library was built with the
   79417 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
   79418 ** opened for writing using cursor (iStatCur+1)
   79419 **
   79420 ** If the sqlite_stat1 tables does not previously exist, it is created.
   79421 ** Similarly, if the sqlite_stat3 table does not exist and the library
   79422 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
   79423 **
   79424 ** Argument zWhere may be a pointer to a buffer containing a table name,
   79425 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   79426 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
   79427 ** with the named table are deleted. If zWhere==0, then code is generated
   79428 ** to delete all stat table entries.
   79429 */
   79430 static void openStatTable(
   79431   Parse *pParse,          /* Parsing context */
   79432   int iDb,                /* The database we are looking in */
   79433   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   79434   const char *zWhere,     /* Delete entries for this table or index */
   79435   const char *zWhereType  /* Either "tbl" or "idx" */
   79436 ){
   79437   static const struct {
   79438     const char *zName;
   79439     const char *zCols;
   79440   } aTable[] = {
   79441     { "sqlite_stat1", "tbl,idx,stat" },
   79442 #ifdef SQLITE_ENABLE_STAT3
   79443     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
   79444 #endif
   79445   };
   79446 
   79447   int aRoot[] = {0, 0};
   79448   u8 aCreateTbl[] = {0, 0};
   79449 
   79450   int i;
   79451   sqlite3 *db = pParse->db;
   79452   Db *pDb;
   79453   Vdbe *v = sqlite3GetVdbe(pParse);
   79454   if( v==0 ) return;
   79455   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79456   assert( sqlite3VdbeDb(v)==db );
   79457   pDb = &db->aDb[iDb];
   79458 
   79459   /* Create new statistic tables if they do not exist, or clear them
   79460   ** if they do already exist.
   79461   */
   79462   for(i=0; i<ArraySize(aTable); i++){
   79463     const char *zTab = aTable[i].zName;
   79464     Table *pStat;
   79465     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   79466       /* The sqlite_stat[12] table does not exist. Create it. Note that a
   79467       ** side-effect of the CREATE TABLE statement is to leave the rootpage
   79468       ** of the new table in register pParse->regRoot. This is important
   79469       ** because the OpenWrite opcode below will be needing it. */
   79470       sqlite3NestedParse(pParse,
   79471           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   79472       );
   79473       aRoot[i] = pParse->regRoot;
   79474       aCreateTbl[i] = 1;
   79475     }else{
   79476       /* The table already exists. If zWhere is not NULL, delete all entries
   79477       ** associated with the table zWhere. If zWhere is NULL, delete the
   79478       ** entire contents of the table. */
   79479       aRoot[i] = pStat->tnum;
   79480       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   79481       if( zWhere ){
   79482         sqlite3NestedParse(pParse,
   79483            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
   79484         );
   79485       }else{
   79486         /* The sqlite_stat[12] table already exists.  Delete all rows. */
   79487         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   79488       }
   79489     }
   79490   }
   79491 
   79492   /* Open the sqlite_stat[13] tables for writing. */
   79493   for(i=0; i<ArraySize(aTable); i++){
   79494     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
   79495     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
   79496     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   79497   }
   79498 }
   79499 
   79500 /*
   79501 ** Recommended number of samples for sqlite_stat3
   79502 */
   79503 #ifndef SQLITE_STAT3_SAMPLES
   79504 # define SQLITE_STAT3_SAMPLES 24
   79505 #endif
   79506 
   79507 /*
   79508 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
   79509 ** share an instance of the following structure to hold their state
   79510 ** information.
   79511 */
   79512 typedef struct Stat3Accum Stat3Accum;
   79513 struct Stat3Accum {
   79514   tRowcnt nRow;             /* Number of rows in the entire table */
   79515   tRowcnt nPSample;         /* How often to do a periodic sample */
   79516   int iMin;                 /* Index of entry with minimum nEq and hash */
   79517   int mxSample;             /* Maximum number of samples to accumulate */
   79518   int nSample;              /* Current number of samples */
   79519   u32 iPrn;                 /* Pseudo-random number used for sampling */
   79520   struct Stat3Sample {
   79521     i64 iRowid;                /* Rowid in main table of the key */
   79522     tRowcnt nEq;               /* sqlite_stat3.nEq */
   79523     tRowcnt nLt;               /* sqlite_stat3.nLt */
   79524     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
   79525     u8 isPSample;              /* True if a periodic sample */
   79526     u32 iHash;                 /* Tiebreaker hash */
   79527   } *a;                     /* An array of samples */
   79528 };
   79529 
   79530 #ifdef SQLITE_ENABLE_STAT3
   79531 /*
   79532 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
   79533 ** are the number of rows in the table or index (C) and the number of samples
   79534 ** to accumulate (S).
   79535 **
   79536 ** This routine allocates the Stat3Accum object.
   79537 **
   79538 ** The return value is the Stat3Accum object (P).
   79539 */
   79540 static void stat3Init(
   79541   sqlite3_context *context,
   79542   int argc,
   79543   sqlite3_value **argv
   79544 ){
   79545   Stat3Accum *p;
   79546   tRowcnt nRow;
   79547   int mxSample;
   79548   int n;
   79549 
   79550   UNUSED_PARAMETER(argc);
   79551   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
   79552   mxSample = sqlite3_value_int(argv[1]);
   79553   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
   79554   p = sqlite3_malloc( n );
   79555   if( p==0 ){
   79556     sqlite3_result_error_nomem(context);
   79557     return;
   79558   }
   79559   memset(p, 0, n);
   79560   p->a = (struct Stat3Sample*)&p[1];
   79561   p->nRow = nRow;
   79562   p->mxSample = mxSample;
   79563   p->nPSample = p->nRow/(mxSample/3+1) + 1;
   79564   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
   79565   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
   79566 }
   79567 static const FuncDef stat3InitFuncdef = {
   79568   2,                /* nArg */
   79569   SQLITE_UTF8,      /* iPrefEnc */
   79570   0,                /* flags */
   79571   0,                /* pUserData */
   79572   0,                /* pNext */
   79573   stat3Init,        /* xFunc */
   79574   0,                /* xStep */
   79575   0,                /* xFinalize */
   79576   "stat3_init",     /* zName */
   79577   0,                /* pHash */
   79578   0                 /* pDestructor */
   79579 };
   79580 
   79581 
   79582 /*
   79583 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
   79584 ** arguments describe a single key instance.  This routine makes the
   79585 ** decision about whether or not to retain this key for the sqlite_stat3
   79586 ** table.
   79587 **
   79588 ** The return value is NULL.
   79589 */
   79590 static void stat3Push(
   79591   sqlite3_context *context,
   79592   int argc,
   79593   sqlite3_value **argv
   79594 ){
   79595   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
   79596   tRowcnt nEq = sqlite3_value_int64(argv[0]);
   79597   tRowcnt nLt = sqlite3_value_int64(argv[1]);
   79598   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
   79599   i64 rowid = sqlite3_value_int64(argv[3]);
   79600   u8 isPSample = 0;
   79601   u8 doInsert = 0;
   79602   int iMin = p->iMin;
   79603   struct Stat3Sample *pSample;
   79604   int i;
   79605   u32 h;
   79606 
   79607   UNUSED_PARAMETER(context);
   79608   UNUSED_PARAMETER(argc);
   79609   if( nEq==0 ) return;
   79610   h = p->iPrn = p->iPrn*1103515245 + 12345;
   79611   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
   79612     doInsert = isPSample = 1;
   79613   }else if( p->nSample<p->mxSample ){
   79614     doInsert = 1;
   79615   }else{
   79616     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
   79617       doInsert = 1;
   79618     }
   79619   }
   79620   if( !doInsert ) return;
   79621   if( p->nSample==p->mxSample ){
   79622     assert( p->nSample - iMin - 1 >= 0 );
   79623     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
   79624     pSample = &p->a[p->nSample-1];
   79625   }else{
   79626     pSample = &p->a[p->nSample++];
   79627   }
   79628   pSample->iRowid = rowid;
   79629   pSample->nEq = nEq;
   79630   pSample->nLt = nLt;
   79631   pSample->nDLt = nDLt;
   79632   pSample->iHash = h;
   79633   pSample->isPSample = isPSample;
   79634 
   79635   /* Find the new minimum */
   79636   if( p->nSample==p->mxSample ){
   79637     pSample = p->a;
   79638     i = 0;
   79639     while( pSample->isPSample ){
   79640       i++;
   79641       pSample++;
   79642       assert( i<p->nSample );
   79643     }
   79644     nEq = pSample->nEq;
   79645     h = pSample->iHash;
   79646     iMin = i;
   79647     for(i++, pSample++; i<p->nSample; i++, pSample++){
   79648       if( pSample->isPSample ) continue;
   79649       if( pSample->nEq<nEq
   79650        || (pSample->nEq==nEq && pSample->iHash<h)
   79651       ){
   79652         iMin = i;
   79653         nEq = pSample->nEq;
   79654         h = pSample->iHash;
   79655       }
   79656     }
   79657     p->iMin = iMin;
   79658   }
   79659 }
   79660 static const FuncDef stat3PushFuncdef = {
   79661   5,                /* nArg */
   79662   SQLITE_UTF8,      /* iPrefEnc */
   79663   0,                /* flags */
   79664   0,                /* pUserData */
   79665   0,                /* pNext */
   79666   stat3Push,        /* xFunc */
   79667   0,                /* xStep */
   79668   0,                /* xFinalize */
   79669   "stat3_push",     /* zName */
   79670   0,                /* pHash */
   79671   0                 /* pDestructor */
   79672 };
   79673 
   79674 /*
   79675 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
   79676 ** used to query the results.  Content is returned for the Nth sqlite_stat3
   79677 ** row where N is between 0 and S-1 and S is the number of samples.  The
   79678 ** value returned depends on the number of arguments.
   79679 **
   79680 **   argc==2    result:  rowid
   79681 **   argc==3    result:  nEq
   79682 **   argc==4    result:  nLt
   79683 **   argc==5    result:  nDLt
   79684 */
   79685 static void stat3Get(
   79686   sqlite3_context *context,
   79687   int argc,
   79688   sqlite3_value **argv
   79689 ){
   79690   int n = sqlite3_value_int(argv[1]);
   79691   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
   79692 
   79693   assert( p!=0 );
   79694   if( p->nSample<=n ) return;
   79695   switch( argc ){
   79696     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
   79697     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
   79698     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
   79699     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
   79700   }
   79701 }
   79702 static const FuncDef stat3GetFuncdef = {
   79703   -1,               /* nArg */
   79704   SQLITE_UTF8,      /* iPrefEnc */
   79705   0,                /* flags */
   79706   0,                /* pUserData */
   79707   0,                /* pNext */
   79708   stat3Get,         /* xFunc */
   79709   0,                /* xStep */
   79710   0,                /* xFinalize */
   79711   "stat3_get",     /* zName */
   79712   0,                /* pHash */
   79713   0                 /* pDestructor */
   79714 };
   79715 #endif /* SQLITE_ENABLE_STAT3 */
   79716 
   79717 
   79718 
   79719 
   79720 /*
   79721 ** Generate code to do an analysis of all indices associated with
   79722 ** a single table.
   79723 */
   79724 static void analyzeOneTable(
   79725   Parse *pParse,   /* Parser context */
   79726   Table *pTab,     /* Table whose indices are to be analyzed */
   79727   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
   79728   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   79729   int iMem         /* Available memory locations begin here */
   79730 ){
   79731   sqlite3 *db = pParse->db;    /* Database handle */
   79732   Index *pIdx;                 /* An index to being analyzed */
   79733   int iIdxCur;                 /* Cursor open on index being analyzed */
   79734   Vdbe *v;                     /* The virtual machine being built up */
   79735   int i;                       /* Loop counter */
   79736   int topOfLoop;               /* The top of the loop */
   79737   int endOfLoop;               /* The end of the loop */
   79738   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   79739   int iDb;                     /* Index of database containing pTab */
   79740   int regTabname = iMem++;     /* Register containing table name */
   79741   int regIdxname = iMem++;     /* Register containing index name */
   79742   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
   79743 #ifdef SQLITE_ENABLE_STAT3
   79744   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
   79745   int regNumLt = iMem++;       /* Number of keys less than regSample */
   79746   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
   79747   int regSample = iMem++;      /* The next sample value */
   79748   int regRowid = regSample;    /* Rowid of a sample */
   79749   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
   79750   int regLoop = iMem++;        /* Loop counter */
   79751   int regCount = iMem++;       /* Number of rows in the table or index */
   79752   int regTemp1 = iMem++;       /* Intermediate register */
   79753   int regTemp2 = iMem++;       /* Intermediate register */
   79754   int once = 1;                /* One-time initialization */
   79755   int shortJump = 0;           /* Instruction address */
   79756   int iTabCur = pParse->nTab++; /* Table cursor */
   79757 #endif
   79758   int regCol = iMem++;         /* Content of a column in analyzed table */
   79759   int regRec = iMem++;         /* Register holding completed record */
   79760   int regTemp = iMem++;        /* Temporary use register */
   79761   int regNewRowid = iMem++;    /* Rowid for the inserted record */
   79762 
   79763 
   79764   v = sqlite3GetVdbe(pParse);
   79765   if( v==0 || NEVER(pTab==0) ){
   79766     return;
   79767   }
   79768   if( pTab->tnum==0 ){
   79769     /* Do not gather statistics on views or virtual tables */
   79770     return;
   79771   }
   79772   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
   79773     /* Do not gather statistics on system tables */
   79774     return;
   79775   }
   79776   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79777   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79778   assert( iDb>=0 );
   79779   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   79780 #ifndef SQLITE_OMIT_AUTHORIZATION
   79781   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   79782       db->aDb[iDb].zName ) ){
   79783     return;
   79784   }
   79785 #endif
   79786 
   79787   /* Establish a read-lock on the table at the shared-cache level. */
   79788   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   79789 
   79790   iIdxCur = pParse->nTab++;
   79791   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   79792   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   79793     int nCol;
   79794     KeyInfo *pKey;
   79795     int addrIfNot = 0;           /* address of OP_IfNot */
   79796     int *aChngAddr;              /* Array of jump instruction addresses */
   79797 
   79798     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
   79799     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
   79800     nCol = pIdx->nColumn;
   79801     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
   79802     if( aChngAddr==0 ) continue;
   79803     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   79804     if( iMem+1+(nCol*2)>pParse->nMem ){
   79805       pParse->nMem = iMem+1+(nCol*2);
   79806     }
   79807 
   79808     /* Open a cursor to the index to be analyzed. */
   79809     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   79810     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
   79811         (char *)pKey, P4_KEYINFO_HANDOFF);
   79812     VdbeComment((v, "%s", pIdx->zName));
   79813 
   79814     /* Populate the register containing the index name. */
   79815     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
   79816 
   79817 #ifdef SQLITE_ENABLE_STAT3
   79818     if( once ){
   79819       once = 0;
   79820       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   79821     }
   79822     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
   79823     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
   79824     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
   79825     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
   79826     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
   79827     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
   79828     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
   79829                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
   79830     sqlite3VdbeChangeP5(v, 2);
   79831 #endif /* SQLITE_ENABLE_STAT3 */
   79832 
   79833     /* The block of memory cells initialized here is used as follows.
   79834     **
   79835     **    iMem:
   79836     **        The total number of rows in the table.
   79837     **
   79838     **    iMem+1 .. iMem+nCol:
   79839     **        Number of distinct entries in index considering the
   79840     **        left-most N columns only, where N is between 1 and nCol,
   79841     **        inclusive.
   79842     **
   79843     **    iMem+nCol+1 .. Mem+2*nCol:
   79844     **        Previous value of indexed columns, from left to right.
   79845     **
   79846     ** Cells iMem through iMem+nCol are initialized to 0. The others are
   79847     ** initialized to contain an SQL NULL.
   79848     */
   79849     for(i=0; i<=nCol; i++){
   79850       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
   79851     }
   79852     for(i=0; i<nCol; i++){
   79853       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
   79854     }
   79855 
   79856     /* Start the analysis loop. This loop runs through all the entries in
   79857     ** the index b-tree.  */
   79858     endOfLoop = sqlite3VdbeMakeLabel(v);
   79859     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
   79860     topOfLoop = sqlite3VdbeCurrentAddr(v);
   79861     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
   79862 
   79863     for(i=0; i<nCol; i++){
   79864       CollSeq *pColl;
   79865       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
   79866       if( i==0 ){
   79867         /* Always record the very first row */
   79868         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
   79869       }
   79870       assert( pIdx->azColl!=0 );
   79871       assert( pIdx->azColl[i]!=0 );
   79872       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
   79873       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
   79874                                       (char*)pColl, P4_COLLSEQ);
   79875       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   79876       VdbeComment((v, "jump if column %d changed", i));
   79877 #ifdef SQLITE_ENABLE_STAT3
   79878       if( i==0 ){
   79879         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
   79880         VdbeComment((v, "incr repeat count"));
   79881       }
   79882 #endif
   79883     }
   79884     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
   79885     for(i=0; i<nCol; i++){
   79886       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
   79887       if( i==0 ){
   79888         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
   79889 #ifdef SQLITE_ENABLE_STAT3
   79890         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
   79891                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
   79892         sqlite3VdbeChangeP5(v, 5);
   79893         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
   79894         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
   79895         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
   79896         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
   79897 #endif
   79898       }
   79899       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
   79900       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
   79901     }
   79902     sqlite3DbFree(db, aChngAddr);
   79903 
   79904     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
   79905     sqlite3VdbeResolveLabel(v, endOfLoop);
   79906 
   79907     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
   79908     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   79909 #ifdef SQLITE_ENABLE_STAT3
   79910     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
   79911                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
   79912     sqlite3VdbeChangeP5(v, 5);
   79913     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
   79914     shortJump =
   79915     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
   79916     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
   79917                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79918     sqlite3VdbeChangeP5(v, 2);
   79919     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
   79920     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
   79921     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
   79922     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
   79923     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
   79924                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79925     sqlite3VdbeChangeP5(v, 3);
   79926     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
   79927                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79928     sqlite3VdbeChangeP5(v, 4);
   79929     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
   79930                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79931     sqlite3VdbeChangeP5(v, 5);
   79932     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
   79933     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
   79934     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
   79935     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
   79936     sqlite3VdbeJumpHere(v, shortJump+2);
   79937 #endif
   79938 
   79939     /* Store the results in sqlite_stat1.
   79940     **
   79941     ** The result is a single row of the sqlite_stat1 table.  The first
   79942     ** two columns are the names of the table and index.  The third column
   79943     ** is a string composed of a list of integer statistics about the
   79944     ** index.  The first integer in the list is the total number of entries
   79945     ** in the index.  There is one additional integer in the list for each
   79946     ** column of the table.  This additional integer is a guess of how many
   79947     ** rows of the table the index will select.  If D is the count of distinct
   79948     ** values and K is the total number of rows, then the integer is computed
   79949     ** as:
   79950     **
   79951     **        I = (K+D-1)/D
   79952     **
   79953     ** If K==0 then no entry is made into the sqlite_stat1 table.
   79954     ** If K>0 then it is always the case the D>0 so division by zero
   79955     ** is never possible.
   79956     */
   79957     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
   79958     if( jZeroRows<0 ){
   79959       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   79960     }
   79961     for(i=0; i<nCol; i++){
   79962       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
   79963       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   79964       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
   79965       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   79966       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
   79967       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
   79968       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   79969     }
   79970     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   79971     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   79972     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   79973     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   79974   }
   79975 
   79976   /* If the table has no indices, create a single sqlite_stat1 entry
   79977   ** containing NULL as the index name and the row count as the content.
   79978   */
   79979   if( pTab->pIndex==0 ){
   79980     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
   79981     VdbeComment((v, "%s", pTab->zName));
   79982     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
   79983     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   79984     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
   79985   }else{
   79986     sqlite3VdbeJumpHere(v, jZeroRows);
   79987     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
   79988   }
   79989   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   79990   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   79991   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   79992   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   79993   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   79994   if( pParse->nMem<regRec ) pParse->nMem = regRec;
   79995   sqlite3VdbeJumpHere(v, jZeroRows);
   79996 }
   79997 
   79998 
   79999 /*
   80000 ** Generate code that will cause the most recent index analysis to
   80001 ** be loaded into internal hash tables where is can be used.
   80002 */
   80003 static void loadAnalysis(Parse *pParse, int iDb){
   80004   Vdbe *v = sqlite3GetVdbe(pParse);
   80005   if( v ){
   80006     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   80007   }
   80008 }
   80009 
   80010 /*
   80011 ** Generate code that will do an analysis of an entire database
   80012 */
   80013 static void analyzeDatabase(Parse *pParse, int iDb){
   80014   sqlite3 *db = pParse->db;
   80015   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   80016   HashElem *k;
   80017   int iStatCur;
   80018   int iMem;
   80019 
   80020   sqlite3BeginWriteOperation(pParse, 0, iDb);
   80021   iStatCur = pParse->nTab;
   80022   pParse->nTab += 3;
   80023   openStatTable(pParse, iDb, iStatCur, 0, 0);
   80024   iMem = pParse->nMem+1;
   80025   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   80026   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   80027     Table *pTab = (Table*)sqliteHashData(k);
   80028     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
   80029   }
   80030   loadAnalysis(pParse, iDb);
   80031 }
   80032 
   80033 /*
   80034 ** Generate code that will do an analysis of a single table in
   80035 ** a database.  If pOnlyIdx is not NULL then it is a single index
   80036 ** in pTab that should be analyzed.
   80037 */
   80038 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
   80039   int iDb;
   80040   int iStatCur;
   80041 
   80042   assert( pTab!=0 );
   80043   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   80044   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   80045   sqlite3BeginWriteOperation(pParse, 0, iDb);
   80046   iStatCur = pParse->nTab;
   80047   pParse->nTab += 3;
   80048   if( pOnlyIdx ){
   80049     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
   80050   }else{
   80051     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
   80052   }
   80053   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
   80054   loadAnalysis(pParse, iDb);
   80055 }
   80056 
   80057 /*
   80058 ** Generate code for the ANALYZE command.  The parser calls this routine
   80059 ** when it recognizes an ANALYZE command.
   80060 **
   80061 **        ANALYZE                            -- 1
   80062 **        ANALYZE  <database>                -- 2
   80063 **        ANALYZE  ?<database>.?<tablename>  -- 3
   80064 **
   80065 ** Form 1 causes all indices in all attached databases to be analyzed.
   80066 ** Form 2 analyzes all indices the single database named.
   80067 ** Form 3 analyzes all indices associated with the named table.
   80068 */
   80069 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   80070   sqlite3 *db = pParse->db;
   80071   int iDb;
   80072   int i;
   80073   char *z, *zDb;
   80074   Table *pTab;
   80075   Index *pIdx;
   80076   Token *pTableName;
   80077 
   80078   /* Read the database schema. If an error occurs, leave an error message
   80079   ** and code in pParse and return NULL. */
   80080   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   80081   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   80082     return;
   80083   }
   80084 
   80085   assert( pName2!=0 || pName1==0 );
   80086   if( pName1==0 ){
   80087     /* Form 1:  Analyze everything */
   80088     for(i=0; i<db->nDb; i++){
   80089       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   80090       analyzeDatabase(pParse, i);
   80091     }
   80092   }else if( pName2->n==0 ){
   80093     /* Form 2:  Analyze the database or table named */
   80094     iDb = sqlite3FindDb(db, pName1);
   80095     if( iDb>=0 ){
   80096       analyzeDatabase(pParse, iDb);
   80097     }else{
   80098       z = sqlite3NameFromToken(db, pName1);
   80099       if( z ){
   80100         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
   80101           analyzeTable(pParse, pIdx->pTable, pIdx);
   80102         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
   80103           analyzeTable(pParse, pTab, 0);
   80104         }
   80105         sqlite3DbFree(db, z);
   80106       }
   80107     }
   80108   }else{
   80109     /* Form 3: Analyze the fully qualified table name */
   80110     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   80111     if( iDb>=0 ){
   80112       zDb = db->aDb[iDb].zName;
   80113       z = sqlite3NameFromToken(db, pTableName);
   80114       if( z ){
   80115         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
   80116           analyzeTable(pParse, pIdx->pTable, pIdx);
   80117         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
   80118           analyzeTable(pParse, pTab, 0);
   80119         }
   80120         sqlite3DbFree(db, z);
   80121       }
   80122     }
   80123   }
   80124 }
   80125 
   80126 /*
   80127 ** Used to pass information from the analyzer reader through to the
   80128 ** callback routine.
   80129 */
   80130 typedef struct analysisInfo analysisInfo;
   80131 struct analysisInfo {
   80132   sqlite3 *db;
   80133   const char *zDatabase;
   80134 };
   80135 
   80136 /*
   80137 ** This callback is invoked once for each index when reading the
   80138 ** sqlite_stat1 table.
   80139 **
   80140 **     argv[0] = name of the table
   80141 **     argv[1] = name of the index (might be NULL)
   80142 **     argv[2] = results of analysis - on integer for each column
   80143 **
   80144 ** Entries for which argv[1]==NULL simply record the number of rows in
   80145 ** the table.
   80146 */
   80147 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   80148   analysisInfo *pInfo = (analysisInfo*)pData;
   80149   Index *pIndex;
   80150   Table *pTable;
   80151   int i, c, n;
   80152   tRowcnt v;
   80153   const char *z;
   80154 
   80155   assert( argc==3 );
   80156   UNUSED_PARAMETER2(NotUsed, argc);
   80157 
   80158   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   80159     return 0;
   80160   }
   80161   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   80162   if( pTable==0 ){
   80163     return 0;
   80164   }
   80165   if( argv[1] ){
   80166     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   80167   }else{
   80168     pIndex = 0;
   80169   }
   80170   n = pIndex ? pIndex->nColumn : 0;
   80171   z = argv[2];
   80172   for(i=0; *z && i<=n; i++){
   80173     v = 0;
   80174     while( (c=z[0])>='0' && c<='9' ){
   80175       v = v*10 + c - '0';
   80176       z++;
   80177     }
   80178     if( i==0 ) pTable->nRowEst = v;
   80179     if( pIndex==0 ) break;
   80180     pIndex->aiRowEst[i] = v;
   80181     if( *z==' ' ) z++;
   80182     if( memcmp(z, "unordered", 10)==0 ){
   80183       pIndex->bUnordered = 1;
   80184       break;
   80185     }
   80186   }
   80187   return 0;
   80188 }
   80189 
   80190 /*
   80191 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   80192 ** and its contents.
   80193 */
   80194 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   80195 #ifdef SQLITE_ENABLE_STAT3
   80196   if( pIdx->aSample ){
   80197     int j;
   80198     for(j=0; j<pIdx->nSample; j++){
   80199       IndexSample *p = &pIdx->aSample[j];
   80200       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
   80201         sqlite3DbFree(db, p->u.z);
   80202       }
   80203     }
   80204     sqlite3DbFree(db, pIdx->aSample);
   80205   }
   80206   if( db && db->pnBytesFreed==0 ){
   80207     pIdx->nSample = 0;
   80208     pIdx->aSample = 0;
   80209   }
   80210 #else
   80211   UNUSED_PARAMETER(db);
   80212   UNUSED_PARAMETER(pIdx);
   80213 #endif
   80214 }
   80215 
   80216 #ifdef SQLITE_ENABLE_STAT3
   80217 /*
   80218 ** Load content from the sqlite_stat3 table into the Index.aSample[]
   80219 ** arrays of all indices.
   80220 */
   80221 static int loadStat3(sqlite3 *db, const char *zDb){
   80222   int rc;                       /* Result codes from subroutines */
   80223   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
   80224   char *zSql;                   /* Text of the SQL statement */
   80225   Index *pPrevIdx = 0;          /* Previous index in the loop */
   80226   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
   80227   int eType;                    /* Datatype of a sample */
   80228   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
   80229 
   80230   assert( db->lookaside.bEnabled==0 );
   80231   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
   80232     return SQLITE_OK;
   80233   }
   80234 
   80235   zSql = sqlite3MPrintf(db,
   80236       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
   80237       " GROUP BY idx", zDb);
   80238   if( !zSql ){
   80239     return SQLITE_NOMEM;
   80240   }
   80241   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   80242   sqlite3DbFree(db, zSql);
   80243   if( rc ) return rc;
   80244 
   80245   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   80246     char *zIndex;   /* Index name */
   80247     Index *pIdx;    /* Pointer to the index object */
   80248     int nSample;    /* Number of samples */
   80249 
   80250     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   80251     if( zIndex==0 ) continue;
   80252     nSample = sqlite3_column_int(pStmt, 1);
   80253     pIdx = sqlite3FindIndex(db, zIndex, zDb);
   80254     if( pIdx==0 ) continue;
   80255     assert( pIdx->nSample==0 );
   80256     pIdx->nSample = nSample;
   80257     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
   80258     pIdx->avgEq = pIdx->aiRowEst[1];
   80259     if( pIdx->aSample==0 ){
   80260       db->mallocFailed = 1;
   80261       sqlite3_finalize(pStmt);
   80262       return SQLITE_NOMEM;
   80263     }
   80264   }
   80265   rc = sqlite3_finalize(pStmt);
   80266   if( rc ) return rc;
   80267 
   80268   zSql = sqlite3MPrintf(db,
   80269       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
   80270   if( !zSql ){
   80271     return SQLITE_NOMEM;
   80272   }
   80273   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   80274   sqlite3DbFree(db, zSql);
   80275   if( rc ) return rc;
   80276 
   80277   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   80278     char *zIndex;   /* Index name */
   80279     Index *pIdx;    /* Pointer to the index object */
   80280     int i;          /* Loop counter */
   80281     tRowcnt sumEq;  /* Sum of the nEq values */
   80282 
   80283     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   80284     if( zIndex==0 ) continue;
   80285     pIdx = sqlite3FindIndex(db, zIndex, zDb);
   80286     if( pIdx==0 ) continue;
   80287     if( pIdx==pPrevIdx ){
   80288       idx++;
   80289     }else{
   80290       pPrevIdx = pIdx;
   80291       idx = 0;
   80292     }
   80293     assert( idx<pIdx->nSample );
   80294     pSample = &pIdx->aSample[idx];
   80295     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
   80296     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
   80297     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
   80298     if( idx==pIdx->nSample-1 ){
   80299       if( pSample->nDLt>0 ){
   80300         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
   80301         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
   80302       }
   80303       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
   80304     }
   80305     eType = sqlite3_column_type(pStmt, 4);
   80306     pSample->eType = (u8)eType;
   80307     switch( eType ){
   80308       case SQLITE_INTEGER: {
   80309         pSample->u.i = sqlite3_column_int64(pStmt, 4);
   80310         break;
   80311       }
   80312       case SQLITE_FLOAT: {
   80313         pSample->u.r = sqlite3_column_double(pStmt, 4);
   80314         break;
   80315       }
   80316       case SQLITE_NULL: {
   80317         break;
   80318       }
   80319       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
   80320         const char *z = (const char *)(
   80321               (eType==SQLITE_BLOB) ?
   80322               sqlite3_column_blob(pStmt, 4):
   80323               sqlite3_column_text(pStmt, 4)
   80324            );
   80325         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
   80326         pSample->nByte = n;
   80327         if( n < 1){
   80328           pSample->u.z = 0;
   80329         }else{
   80330           pSample->u.z = sqlite3DbMallocRaw(db, n);
   80331           if( pSample->u.z==0 ){
   80332             db->mallocFailed = 1;
   80333             sqlite3_finalize(pStmt);
   80334             return SQLITE_NOMEM;
   80335           }
   80336           memcpy(pSample->u.z, z, n);
   80337         }
   80338       }
   80339     }
   80340   }
   80341   return sqlite3_finalize(pStmt);
   80342 }
   80343 #endif /* SQLITE_ENABLE_STAT3 */
   80344 
   80345 /*
   80346 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
   80347 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   80348 ** arrays. The contents of sqlite_stat3 are used to populate the
   80349 ** Index.aSample[] arrays.
   80350 **
   80351 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   80352 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
   80353 ** during compilation and the sqlite_stat3 table is present, no data is
   80354 ** read from it.
   80355 **
   80356 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
   80357 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
   80358 ** returned. However, in this case, data is read from the sqlite_stat1
   80359 ** table (if it is present) before returning.
   80360 **
   80361 ** If an OOM error occurs, this function always sets db->mallocFailed.
   80362 ** This means if the caller does not care about other errors, the return
   80363 ** code may be ignored.
   80364 */
   80365 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   80366   analysisInfo sInfo;
   80367   HashElem *i;
   80368   char *zSql;
   80369   int rc;
   80370 
   80371   assert( iDb>=0 && iDb<db->nDb );
   80372   assert( db->aDb[iDb].pBt!=0 );
   80373 
   80374   /* Clear any prior statistics */
   80375   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   80376   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   80377     Index *pIdx = sqliteHashData(i);
   80378     sqlite3DefaultRowEst(pIdx);
   80379 #ifdef SQLITE_ENABLE_STAT3
   80380     sqlite3DeleteIndexSamples(db, pIdx);
   80381     pIdx->aSample = 0;
   80382 #endif
   80383   }
   80384 
   80385   /* Check to make sure the sqlite_stat1 table exists */
   80386   sInfo.db = db;
   80387   sInfo.zDatabase = db->aDb[iDb].zName;
   80388   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   80389     return SQLITE_ERROR;
   80390   }
   80391 
   80392   /* Load new statistics out of the sqlite_stat1 table */
   80393   zSql = sqlite3MPrintf(db,
   80394       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   80395   if( zSql==0 ){
   80396     rc = SQLITE_NOMEM;
   80397   }else{
   80398     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   80399     sqlite3DbFree(db, zSql);
   80400   }
   80401 
   80402 
   80403   /* Load the statistics from the sqlite_stat3 table. */
   80404 #ifdef SQLITE_ENABLE_STAT3
   80405   if( rc==SQLITE_OK ){
   80406     int lookasideEnabled = db->lookaside.bEnabled;
   80407     db->lookaside.bEnabled = 0;
   80408     rc = loadStat3(db, sInfo.zDatabase);
   80409     db->lookaside.bEnabled = lookasideEnabled;
   80410   }
   80411 #endif
   80412 
   80413   if( rc==SQLITE_NOMEM ){
   80414     db->mallocFailed = 1;
   80415   }
   80416   return rc;
   80417 }
   80418 
   80419 
   80420 #endif /* SQLITE_OMIT_ANALYZE */
   80421 
   80422 /************** End of analyze.c *********************************************/
   80423 /************** Begin file attach.c ******************************************/
   80424 /*
   80425 ** 2003 April 6
   80426 **
   80427 ** The author disclaims copyright to this source code.  In place of
   80428 ** a legal notice, here is a blessing:
   80429 **
   80430 **    May you do good and not evil.
   80431 **    May you find forgiveness for yourself and forgive others.
   80432 **    May you share freely, never taking more than you give.
   80433 **
   80434 *************************************************************************
   80435 ** This file contains code used to implement the ATTACH and DETACH commands.
   80436 */
   80437 
   80438 #ifndef SQLITE_OMIT_ATTACH
   80439 /*
   80440 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   80441 ** is slightly different from resolving a normal SQL expression, because simple
   80442 ** identifiers are treated as strings, not possible column names or aliases.
   80443 **
   80444 ** i.e. if the parser sees:
   80445 **
   80446 **     ATTACH DATABASE abc AS def
   80447 **
   80448 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   80449 ** looking for columns of the same name.
   80450 **
   80451 ** This only applies to the root node of pExpr, so the statement:
   80452 **
   80453 **     ATTACH DATABASE abc||def AS 'db2'
   80454 **
   80455 ** will fail because neither abc or def can be resolved.
   80456 */
   80457 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   80458 {
   80459   int rc = SQLITE_OK;
   80460   if( pExpr ){
   80461     if( pExpr->op!=TK_ID ){
   80462       rc = sqlite3ResolveExprNames(pName, pExpr);
   80463       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
   80464         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
   80465         return SQLITE_ERROR;
   80466       }
   80467     }else{
   80468       pExpr->op = TK_STRING;
   80469     }
   80470   }
   80471   return rc;
   80472 }
   80473 
   80474 /*
   80475 ** An SQL user-function registered to do the work of an ATTACH statement. The
   80476 ** three arguments to the function come directly from an attach statement:
   80477 **
   80478 **     ATTACH DATABASE x AS y KEY z
   80479 **
   80480 **     SELECT sqlite_attach(x, y, z)
   80481 **
   80482 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   80483 ** third argument.
   80484 */
   80485 static void attachFunc(
   80486   sqlite3_context *context,
   80487   int NotUsed,
   80488   sqlite3_value **argv
   80489 ){
   80490   int i;
   80491   int rc = 0;
   80492   sqlite3 *db = sqlite3_context_db_handle(context);
   80493   const char *zName;
   80494   const char *zFile;
   80495   char *zPath = 0;
   80496   char *zErr = 0;
   80497   unsigned int flags;
   80498   Db *aNew;
   80499   char *zErrDyn = 0;
   80500   sqlite3_vfs *pVfs;
   80501 
   80502   UNUSED_PARAMETER(NotUsed);
   80503 
   80504   zFile = (const char *)sqlite3_value_text(argv[0]);
   80505   zName = (const char *)sqlite3_value_text(argv[1]);
   80506   if( zFile==0 ) zFile = "";
   80507   if( zName==0 ) zName = "";
   80508 
   80509   /* Check for the following errors:
   80510   **
   80511   **     * Too many attached databases,
   80512   **     * Transaction currently open
   80513   **     * Specified database name already being used.
   80514   */
   80515   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   80516     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   80517       db->aLimit[SQLITE_LIMIT_ATTACHED]
   80518     );
   80519     goto attach_error;
   80520   }
   80521   if( !db->autoCommit ){
   80522     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   80523     goto attach_error;
   80524   }
   80525   for(i=0; i<db->nDb; i++){
   80526     char *z = db->aDb[i].zName;
   80527     assert( z && zName );
   80528     if( sqlite3StrICmp(z, zName)==0 ){
   80529       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   80530       goto attach_error;
   80531     }
   80532   }
   80533 
   80534   /* Allocate the new entry in the db->aDb[] array and initialise the schema
   80535   ** hash tables.
   80536   */
   80537   if( db->aDb==db->aDbStatic ){
   80538     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   80539     if( aNew==0 ) return;
   80540     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   80541   }else{
   80542     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   80543     if( aNew==0 ) return;
   80544   }
   80545   db->aDb = aNew;
   80546   aNew = &db->aDb[db->nDb];
   80547   memset(aNew, 0, sizeof(*aNew));
   80548 
   80549   /* Open the database file. If the btree is successfully opened, use
   80550   ** it to obtain the database schema. At this point the schema may
   80551   ** or may not be initialised.
   80552   */
   80553   flags = db->openFlags;
   80554   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   80555   if( rc!=SQLITE_OK ){
   80556     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   80557     sqlite3_result_error(context, zErr, -1);
   80558     sqlite3_free(zErr);
   80559     return;
   80560   }
   80561   assert( pVfs );
   80562   flags |= SQLITE_OPEN_MAIN_DB;
   80563   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
   80564   sqlite3_free( zPath );
   80565   db->nDb++;
   80566   if( rc==SQLITE_CONSTRAINT ){
   80567     rc = SQLITE_ERROR;
   80568     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   80569   }else if( rc==SQLITE_OK ){
   80570     Pager *pPager;
   80571     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   80572     if( !aNew->pSchema ){
   80573       rc = SQLITE_NOMEM;
   80574     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   80575       zErrDyn = sqlite3MPrintf(db,
   80576         "attached databases must use the same text encoding as main database");
   80577       rc = SQLITE_ERROR;
   80578     }
   80579     pPager = sqlite3BtreePager(aNew->pBt);
   80580     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   80581     sqlite3BtreeSecureDelete(aNew->pBt,
   80582                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   80583   }
   80584   aNew->safety_level = 3;
   80585   aNew->zName = sqlite3DbStrDup(db, zName);
   80586   if( rc==SQLITE_OK && aNew->zName==0 ){
   80587     rc = SQLITE_NOMEM;
   80588   }
   80589 
   80590 
   80591 #ifdef SQLITE_HAS_CODEC
   80592   if( rc==SQLITE_OK ){
   80593     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   80594     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   80595     int nKey;
   80596     char *zKey;
   80597     int t = sqlite3_value_type(argv[2]);
   80598     switch( t ){
   80599       case SQLITE_INTEGER:
   80600       case SQLITE_FLOAT:
   80601         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   80602         rc = SQLITE_ERROR;
   80603         break;
   80604 
   80605       case SQLITE_TEXT:
   80606       case SQLITE_BLOB:
   80607         nKey = sqlite3_value_bytes(argv[2]);
   80608         zKey = (char *)sqlite3_value_blob(argv[2]);
   80609         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   80610         break;
   80611 
   80612       case SQLITE_NULL:
   80613         /* No key specified.  Use the key from the main database */
   80614         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   80615         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
   80616           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   80617         }
   80618         break;
   80619     }
   80620   }
   80621 #endif
   80622 
   80623   /* If the file was opened successfully, read the schema for the new database.
   80624   ** If this fails, or if opening the file failed, then close the file and
   80625   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   80626   ** we found it.
   80627   */
   80628   if( rc==SQLITE_OK ){
   80629     sqlite3BtreeEnterAll(db);
   80630     rc = sqlite3Init(db, &zErrDyn);
   80631     sqlite3BtreeLeaveAll(db);
   80632   }
   80633   if( rc ){
   80634     int iDb = db->nDb - 1;
   80635     assert( iDb>=2 );
   80636     if( db->aDb[iDb].pBt ){
   80637       sqlite3BtreeClose(db->aDb[iDb].pBt);
   80638       db->aDb[iDb].pBt = 0;
   80639       db->aDb[iDb].pSchema = 0;
   80640     }
   80641     sqlite3ResetInternalSchema(db, -1);
   80642     db->nDb = iDb;
   80643     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   80644       db->mallocFailed = 1;
   80645       sqlite3DbFree(db, zErrDyn);
   80646       zErrDyn = sqlite3MPrintf(db, "out of memory");
   80647     }else if( zErrDyn==0 ){
   80648       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   80649     }
   80650     goto attach_error;
   80651   }
   80652 
   80653   return;
   80654 
   80655 attach_error:
   80656   /* Return an error if we get here */
   80657   if( zErrDyn ){
   80658     sqlite3_result_error(context, zErrDyn, -1);
   80659     sqlite3DbFree(db, zErrDyn);
   80660   }
   80661   if( rc ) sqlite3_result_error_code(context, rc);
   80662 }
   80663 
   80664 /*
   80665 ** An SQL user-function registered to do the work of an DETACH statement. The
   80666 ** three arguments to the function come directly from a detach statement:
   80667 **
   80668 **     DETACH DATABASE x
   80669 **
   80670 **     SELECT sqlite_detach(x)
   80671 */
   80672 static void detachFunc(
   80673   sqlite3_context *context,
   80674   int NotUsed,
   80675   sqlite3_value **argv
   80676 ){
   80677   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   80678   sqlite3 *db = sqlite3_context_db_handle(context);
   80679   int i;
   80680   Db *pDb = 0;
   80681   char zErr[128];
   80682 
   80683   UNUSED_PARAMETER(NotUsed);
   80684 
   80685   if( zName==0 ) zName = "";
   80686   for(i=0; i<db->nDb; i++){
   80687     pDb = &db->aDb[i];
   80688     if( pDb->pBt==0 ) continue;
   80689     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   80690   }
   80691 
   80692   if( i>=db->nDb ){
   80693     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   80694     goto detach_error;
   80695   }
   80696   if( i<2 ){
   80697     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   80698     goto detach_error;
   80699   }
   80700   if( !db->autoCommit ){
   80701     sqlite3_snprintf(sizeof(zErr), zErr,
   80702                      "cannot DETACH database within transaction");
   80703     goto detach_error;
   80704   }
   80705   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   80706     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   80707     goto detach_error;
   80708   }
   80709 
   80710   sqlite3BtreeClose(pDb->pBt);
   80711   pDb->pBt = 0;
   80712   pDb->pSchema = 0;
   80713   sqlite3ResetInternalSchema(db, -1);
   80714   return;
   80715 
   80716 detach_error:
   80717   sqlite3_result_error(context, zErr, -1);
   80718 }
   80719 
   80720 /*
   80721 ** This procedure generates VDBE code for a single invocation of either the
   80722 ** sqlite_detach() or sqlite_attach() SQL user functions.
   80723 */
   80724 static void codeAttach(
   80725   Parse *pParse,       /* The parser context */
   80726   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   80727   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   80728   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   80729   Expr *pFilename,     /* Name of database file */
   80730   Expr *pDbname,       /* Name of the database to use internally */
   80731   Expr *pKey           /* Database key for encryption extension */
   80732 ){
   80733   int rc;
   80734   NameContext sName;
   80735   Vdbe *v;
   80736   sqlite3* db = pParse->db;
   80737   int regArgs;
   80738 
   80739   memset(&sName, 0, sizeof(NameContext));
   80740   sName.pParse = pParse;
   80741 
   80742   if(
   80743       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   80744       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   80745       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   80746   ){
   80747     pParse->nErr++;
   80748     goto attach_end;
   80749   }
   80750 
   80751 #ifndef SQLITE_OMIT_AUTHORIZATION
   80752   if( pAuthArg ){
   80753     char *zAuthArg;
   80754     if( pAuthArg->op==TK_STRING ){
   80755       zAuthArg = pAuthArg->u.zToken;
   80756     }else{
   80757       zAuthArg = 0;
   80758     }
   80759     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   80760     if(rc!=SQLITE_OK ){
   80761       goto attach_end;
   80762     }
   80763   }
   80764 #endif /* SQLITE_OMIT_AUTHORIZATION */
   80765 
   80766 
   80767   v = sqlite3GetVdbe(pParse);
   80768   regArgs = sqlite3GetTempRange(pParse, 4);
   80769   sqlite3ExprCode(pParse, pFilename, regArgs);
   80770   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   80771   sqlite3ExprCode(pParse, pKey, regArgs+2);
   80772 
   80773   assert( v || db->mallocFailed );
   80774   if( v ){
   80775     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   80776     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   80777     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   80778     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   80779 
   80780     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   80781     ** statement only). For DETACH, set it to false (expire all existing
   80782     ** statements).
   80783     */
   80784     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   80785   }
   80786 
   80787 attach_end:
   80788   sqlite3ExprDelete(db, pFilename);
   80789   sqlite3ExprDelete(db, pDbname);
   80790   sqlite3ExprDelete(db, pKey);
   80791 }
   80792 
   80793 /*
   80794 ** Called by the parser to compile a DETACH statement.
   80795 **
   80796 **     DETACH pDbname
   80797 */
   80798 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   80799   static const FuncDef detach_func = {
   80800     1,                /* nArg */
   80801     SQLITE_UTF8,      /* iPrefEnc */
   80802     0,                /* flags */
   80803     0,                /* pUserData */
   80804     0,                /* pNext */
   80805     detachFunc,       /* xFunc */
   80806     0,                /* xStep */
   80807     0,                /* xFinalize */
   80808     "sqlite_detach",  /* zName */
   80809     0,                /* pHash */
   80810     0                 /* pDestructor */
   80811   };
   80812   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   80813 }
   80814 
   80815 /*
   80816 ** Called by the parser to compile an ATTACH statement.
   80817 **
   80818 **     ATTACH p AS pDbname KEY pKey
   80819 */
   80820 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   80821   static const FuncDef attach_func = {
   80822     3,                /* nArg */
   80823     SQLITE_UTF8,      /* iPrefEnc */
   80824     0,                /* flags */
   80825     0,                /* pUserData */
   80826     0,                /* pNext */
   80827     attachFunc,       /* xFunc */
   80828     0,                /* xStep */
   80829     0,                /* xFinalize */
   80830     "sqlite_attach",  /* zName */
   80831     0,                /* pHash */
   80832     0                 /* pDestructor */
   80833   };
   80834   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   80835 }
   80836 #endif /* SQLITE_OMIT_ATTACH */
   80837 
   80838 /*
   80839 ** Initialize a DbFixer structure.  This routine must be called prior
   80840 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   80841 **
   80842 ** The return value indicates whether or not fixation is required.  TRUE
   80843 ** means we do need to fix the database references, FALSE means we do not.
   80844 */
   80845 SQLITE_PRIVATE int sqlite3FixInit(
   80846   DbFixer *pFix,      /* The fixer to be initialized */
   80847   Parse *pParse,      /* Error messages will be written here */
   80848   int iDb,            /* This is the database that must be used */
   80849   const char *zType,  /* "view", "trigger", or "index" */
   80850   const Token *pName  /* Name of the view, trigger, or index */
   80851 ){
   80852   sqlite3 *db;
   80853 
   80854   if( NEVER(iDb<0) || iDb==1 ) return 0;
   80855   db = pParse->db;
   80856   assert( db->nDb>iDb );
   80857   pFix->pParse = pParse;
   80858   pFix->zDb = db->aDb[iDb].zName;
   80859   pFix->zType = zType;
   80860   pFix->pName = pName;
   80861   return 1;
   80862 }
   80863 
   80864 /*
   80865 ** The following set of routines walk through the parse tree and assign
   80866 ** a specific database to all table references where the database name
   80867 ** was left unspecified in the original SQL statement.  The pFix structure
   80868 ** must have been initialized by a prior call to sqlite3FixInit().
   80869 **
   80870 ** These routines are used to make sure that an index, trigger, or
   80871 ** view in one database does not refer to objects in a different database.
   80872 ** (Exception: indices, triggers, and views in the TEMP database are
   80873 ** allowed to refer to anything.)  If a reference is explicitly made
   80874 ** to an object in a different database, an error message is added to
   80875 ** pParse->zErrMsg and these routines return non-zero.  If everything
   80876 ** checks out, these routines return 0.
   80877 */
   80878 SQLITE_PRIVATE int sqlite3FixSrcList(
   80879   DbFixer *pFix,       /* Context of the fixation */
   80880   SrcList *pList       /* The Source list to check and modify */
   80881 ){
   80882   int i;
   80883   const char *zDb;
   80884   struct SrcList_item *pItem;
   80885 
   80886   if( NEVER(pList==0) ) return 0;
   80887   zDb = pFix->zDb;
   80888   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   80889     if( pItem->zDatabase==0 ){
   80890       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
   80891     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
   80892       sqlite3ErrorMsg(pFix->pParse,
   80893          "%s %T cannot reference objects in database %s",
   80894          pFix->zType, pFix->pName, pItem->zDatabase);
   80895       return 1;
   80896     }
   80897 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   80898     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   80899     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   80900 #endif
   80901   }
   80902   return 0;
   80903 }
   80904 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   80905 SQLITE_PRIVATE int sqlite3FixSelect(
   80906   DbFixer *pFix,       /* Context of the fixation */
   80907   Select *pSelect      /* The SELECT statement to be fixed to one database */
   80908 ){
   80909   while( pSelect ){
   80910     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   80911       return 1;
   80912     }
   80913     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   80914       return 1;
   80915     }
   80916     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   80917       return 1;
   80918     }
   80919     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   80920       return 1;
   80921     }
   80922     pSelect = pSelect->pPrior;
   80923   }
   80924   return 0;
   80925 }
   80926 SQLITE_PRIVATE int sqlite3FixExpr(
   80927   DbFixer *pFix,     /* Context of the fixation */
   80928   Expr *pExpr        /* The expression to be fixed to one database */
   80929 ){
   80930   while( pExpr ){
   80931     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
   80932     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   80933       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   80934     }else{
   80935       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   80936     }
   80937     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   80938       return 1;
   80939     }
   80940     pExpr = pExpr->pLeft;
   80941   }
   80942   return 0;
   80943 }
   80944 SQLITE_PRIVATE int sqlite3FixExprList(
   80945   DbFixer *pFix,     /* Context of the fixation */
   80946   ExprList *pList    /* The expression to be fixed to one database */
   80947 ){
   80948   int i;
   80949   struct ExprList_item *pItem;
   80950   if( pList==0 ) return 0;
   80951   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   80952     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   80953       return 1;
   80954     }
   80955   }
   80956   return 0;
   80957 }
   80958 #endif
   80959 
   80960 #ifndef SQLITE_OMIT_TRIGGER
   80961 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   80962   DbFixer *pFix,     /* Context of the fixation */
   80963   TriggerStep *pStep /* The trigger step be fixed to one database */
   80964 ){
   80965   while( pStep ){
   80966     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   80967       return 1;
   80968     }
   80969     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   80970       return 1;
   80971     }
   80972     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   80973       return 1;
   80974     }
   80975     pStep = pStep->pNext;
   80976   }
   80977   return 0;
   80978 }
   80979 #endif
   80980 
   80981 /************** End of attach.c **********************************************/
   80982 /************** Begin file auth.c ********************************************/
   80983 /*
   80984 ** 2003 January 11
   80985 **
   80986 ** The author disclaims copyright to this source code.  In place of
   80987 ** a legal notice, here is a blessing:
   80988 **
   80989 **    May you do good and not evil.
   80990 **    May you find forgiveness for yourself and forgive others.
   80991 **    May you share freely, never taking more than you give.
   80992 **
   80993 *************************************************************************
   80994 ** This file contains code used to implement the sqlite3_set_authorizer()
   80995 ** API.  This facility is an optional feature of the library.  Embedded
   80996 ** systems that do not need this facility may omit it by recompiling
   80997 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   80998 */
   80999 
   81000 /*
   81001 ** All of the code in this file may be omitted by defining a single
   81002 ** macro.
   81003 */
   81004 #ifndef SQLITE_OMIT_AUTHORIZATION
   81005 
   81006 /*
   81007 ** Set or clear the access authorization function.
   81008 **
   81009 ** The access authorization function is be called during the compilation
   81010 ** phase to verify that the user has read and/or write access permission on
   81011 ** various fields of the database.  The first argument to the auth function
   81012 ** is a copy of the 3rd argument to this routine.  The second argument
   81013 ** to the auth function is one of these constants:
   81014 **
   81015 **       SQLITE_CREATE_INDEX
   81016 **       SQLITE_CREATE_TABLE
   81017 **       SQLITE_CREATE_TEMP_INDEX
   81018 **       SQLITE_CREATE_TEMP_TABLE
   81019 **       SQLITE_CREATE_TEMP_TRIGGER
   81020 **       SQLITE_CREATE_TEMP_VIEW
   81021 **       SQLITE_CREATE_TRIGGER
   81022 **       SQLITE_CREATE_VIEW
   81023 **       SQLITE_DELETE
   81024 **       SQLITE_DROP_INDEX
   81025 **       SQLITE_DROP_TABLE
   81026 **       SQLITE_DROP_TEMP_INDEX
   81027 **       SQLITE_DROP_TEMP_TABLE
   81028 **       SQLITE_DROP_TEMP_TRIGGER
   81029 **       SQLITE_DROP_TEMP_VIEW
   81030 **       SQLITE_DROP_TRIGGER
   81031 **       SQLITE_DROP_VIEW
   81032 **       SQLITE_INSERT
   81033 **       SQLITE_PRAGMA
   81034 **       SQLITE_READ
   81035 **       SQLITE_SELECT
   81036 **       SQLITE_TRANSACTION
   81037 **       SQLITE_UPDATE
   81038 **
   81039 ** The third and fourth arguments to the auth function are the name of
   81040 ** the table and the column that are being accessed.  The auth function
   81041 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   81042 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   81043 ** means that the SQL statement will never-run - the sqlite3_exec() call
   81044 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   81045 ** should run but attempts to read the specified column will return NULL
   81046 ** and attempts to write the column will be ignored.
   81047 **
   81048 ** Setting the auth function to NULL disables this hook.  The default
   81049 ** setting of the auth function is NULL.
   81050 */
   81051 SQLITE_API int sqlite3_set_authorizer(
   81052   sqlite3 *db,
   81053   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   81054   void *pArg
   81055 ){
   81056   sqlite3_mutex_enter(db->mutex);
   81057   db->xAuth = xAuth;
   81058   db->pAuthArg = pArg;
   81059   sqlite3ExpirePreparedStatements(db);
   81060   sqlite3_mutex_leave(db->mutex);
   81061   return SQLITE_OK;
   81062 }
   81063 
   81064 /*
   81065 ** Write an error message into pParse->zErrMsg that explains that the
   81066 ** user-supplied authorization function returned an illegal value.
   81067 */
   81068 static void sqliteAuthBadReturnCode(Parse *pParse){
   81069   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   81070   pParse->rc = SQLITE_ERROR;
   81071 }
   81072 
   81073 /*
   81074 ** Invoke the authorization callback for permission to read column zCol from
   81075 ** table zTab in database zDb. This function assumes that an authorization
   81076 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   81077 **
   81078 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   81079 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   81080 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   81081 */
   81082 SQLITE_PRIVATE int sqlite3AuthReadCol(
   81083   Parse *pParse,                  /* The parser context */
   81084   const char *zTab,               /* Table name */
   81085   const char *zCol,               /* Column name */
   81086   int iDb                         /* Index of containing database. */
   81087 ){
   81088   sqlite3 *db = pParse->db;       /* Database handle */
   81089   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   81090   int rc;                         /* Auth callback return code */
   81091 
   81092   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   81093   if( rc==SQLITE_DENY ){
   81094     if( db->nDb>2 || iDb!=0 ){
   81095       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   81096     }else{
   81097       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   81098     }
   81099     pParse->rc = SQLITE_AUTH;
   81100   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   81101     sqliteAuthBadReturnCode(pParse);
   81102   }
   81103   return rc;
   81104 }
   81105 
   81106 /*
   81107 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   81108 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   81109 ** Check to see if it is OK to read this particular column.
   81110 **
   81111 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   81112 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   81113 ** then generate an error.
   81114 */
   81115 SQLITE_PRIVATE void sqlite3AuthRead(
   81116   Parse *pParse,        /* The parser context */
   81117   Expr *pExpr,          /* The expression to check authorization on */
   81118   Schema *pSchema,      /* The schema of the expression */
   81119   SrcList *pTabList     /* All table that pExpr might refer to */
   81120 ){
   81121   sqlite3 *db = pParse->db;
   81122   Table *pTab = 0;      /* The table being read */
   81123   const char *zCol;     /* Name of the column of the table */
   81124   int iSrc;             /* Index in pTabList->a[] of table being read */
   81125   int iDb;              /* The index of the database the expression refers to */
   81126   int iCol;             /* Index of column in table */
   81127 
   81128   if( db->xAuth==0 ) return;
   81129   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   81130   if( iDb<0 ){
   81131     /* An attempt to read a column out of a subquery or other
   81132     ** temporary table. */
   81133     return;
   81134   }
   81135 
   81136   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   81137   if( pExpr->op==TK_TRIGGER ){
   81138     pTab = pParse->pTriggerTab;
   81139   }else{
   81140     assert( pTabList );
   81141     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   81142       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   81143         pTab = pTabList->a[iSrc].pTab;
   81144         break;
   81145       }
   81146     }
   81147   }
   81148   iCol = pExpr->iColumn;
   81149   if( NEVER(pTab==0) ) return;
   81150 
   81151   if( iCol>=0 ){
   81152     assert( iCol<pTab->nCol );
   81153     zCol = pTab->aCol[iCol].zName;
   81154   }else if( pTab->iPKey>=0 ){
   81155     assert( pTab->iPKey<pTab->nCol );
   81156     zCol = pTab->aCol[pTab->iPKey].zName;
   81157   }else{
   81158     zCol = "ROWID";
   81159   }
   81160   assert( iDb>=0 && iDb<db->nDb );
   81161   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   81162     pExpr->op = TK_NULL;
   81163   }
   81164 }
   81165 
   81166 /*
   81167 ** Do an authorization check using the code and arguments given.  Return
   81168 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   81169 ** is returned, then the error count and error message in pParse are
   81170 ** modified appropriately.
   81171 */
   81172 SQLITE_PRIVATE int sqlite3AuthCheck(
   81173   Parse *pParse,
   81174   int code,
   81175   const char *zArg1,
   81176   const char *zArg2,
   81177   const char *zArg3
   81178 ){
   81179   sqlite3 *db = pParse->db;
   81180   int rc;
   81181 
   81182   /* Don't do any authorization checks if the database is initialising
   81183   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   81184   */
   81185   if( db->init.busy || IN_DECLARE_VTAB ){
   81186     return SQLITE_OK;
   81187   }
   81188 
   81189   if( db->xAuth==0 ){
   81190     return SQLITE_OK;
   81191   }
   81192   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   81193   if( rc==SQLITE_DENY ){
   81194     sqlite3ErrorMsg(pParse, "not authorized");
   81195     pParse->rc = SQLITE_AUTH;
   81196   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   81197     rc = SQLITE_DENY;
   81198     sqliteAuthBadReturnCode(pParse);
   81199   }
   81200   return rc;
   81201 }
   81202 
   81203 /*
   81204 ** Push an authorization context.  After this routine is called, the
   81205 ** zArg3 argument to authorization callbacks will be zContext until
   81206 ** popped.  Or if pParse==0, this routine is a no-op.
   81207 */
   81208 SQLITE_PRIVATE void sqlite3AuthContextPush(
   81209   Parse *pParse,
   81210   AuthContext *pContext,
   81211   const char *zContext
   81212 ){
   81213   assert( pParse );
   81214   pContext->pParse = pParse;
   81215   pContext->zAuthContext = pParse->zAuthContext;
   81216   pParse->zAuthContext = zContext;
   81217 }
   81218 
   81219 /*
   81220 ** Pop an authorization context that was previously pushed
   81221 ** by sqlite3AuthContextPush
   81222 */
   81223 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   81224   if( pContext->pParse ){
   81225     pContext->pParse->zAuthContext = pContext->zAuthContext;
   81226     pContext->pParse = 0;
   81227   }
   81228 }
   81229 
   81230 #endif /* SQLITE_OMIT_AUTHORIZATION */
   81231 
   81232 /************** End of auth.c ************************************************/
   81233 /************** Begin file build.c *******************************************/
   81234 /*
   81235 ** 2001 September 15
   81236 **
   81237 ** The author disclaims copyright to this source code.  In place of
   81238 ** a legal notice, here is a blessing:
   81239 **
   81240 **    May you do good and not evil.
   81241 **    May you find forgiveness for yourself and forgive others.
   81242 **    May you share freely, never taking more than you give.
   81243 **
   81244 *************************************************************************
   81245 ** This file contains C code routines that are called by the SQLite parser
   81246 ** when syntax rules are reduced.  The routines in this file handle the
   81247 ** following kinds of SQL syntax:
   81248 **
   81249 **     CREATE TABLE
   81250 **     DROP TABLE
   81251 **     CREATE INDEX
   81252 **     DROP INDEX
   81253 **     creating ID lists
   81254 **     BEGIN TRANSACTION
   81255 **     COMMIT
   81256 **     ROLLBACK
   81257 */
   81258 
   81259 /*
   81260 ** This routine is called when a new SQL statement is beginning to
   81261 ** be parsed.  Initialize the pParse structure as needed.
   81262 */
   81263 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   81264   pParse->explain = (u8)explainFlag;
   81265   pParse->nVar = 0;
   81266 }
   81267 
   81268 #ifndef SQLITE_OMIT_SHARED_CACHE
   81269 /*
   81270 ** The TableLock structure is only used by the sqlite3TableLock() and
   81271 ** codeTableLocks() functions.
   81272 */
   81273 struct TableLock {
   81274   int iDb;             /* The database containing the table to be locked */
   81275   int iTab;            /* The root page of the table to be locked */
   81276   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   81277   const char *zName;   /* Name of the table */
   81278 };
   81279 
   81280 /*
   81281 ** Record the fact that we want to lock a table at run-time.
   81282 **
   81283 ** The table to be locked has root page iTab and is found in database iDb.
   81284 ** A read or a write lock can be taken depending on isWritelock.
   81285 **
   81286 ** This routine just records the fact that the lock is desired.  The
   81287 ** code to make the lock occur is generated by a later call to
   81288 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   81289 */
   81290 SQLITE_PRIVATE void sqlite3TableLock(
   81291   Parse *pParse,     /* Parsing context */
   81292   int iDb,           /* Index of the database containing the table to lock */
   81293   int iTab,          /* Root page number of the table to be locked */
   81294   u8 isWriteLock,    /* True for a write lock */
   81295   const char *zName  /* Name of the table to be locked */
   81296 ){
   81297   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   81298   int i;
   81299   int nBytes;
   81300   TableLock *p;
   81301   assert( iDb>=0 );
   81302 
   81303   for(i=0; i<pToplevel->nTableLock; i++){
   81304     p = &pToplevel->aTableLock[i];
   81305     if( p->iDb==iDb && p->iTab==iTab ){
   81306       p->isWriteLock = (p->isWriteLock || isWriteLock);
   81307       return;
   81308     }
   81309   }
   81310 
   81311   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   81312   pToplevel->aTableLock =
   81313       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   81314   if( pToplevel->aTableLock ){
   81315     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   81316     p->iDb = iDb;
   81317     p->iTab = iTab;
   81318     p->isWriteLock = isWriteLock;
   81319     p->zName = zName;
   81320   }else{
   81321     pToplevel->nTableLock = 0;
   81322     pToplevel->db->mallocFailed = 1;
   81323   }
   81324 }
   81325 
   81326 /*
   81327 ** Code an OP_TableLock instruction for each table locked by the
   81328 ** statement (configured by calls to sqlite3TableLock()).
   81329 */
   81330 static void codeTableLocks(Parse *pParse){
   81331   int i;
   81332   Vdbe *pVdbe;
   81333 
   81334   pVdbe = sqlite3GetVdbe(pParse);
   81335   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   81336 
   81337   for(i=0; i<pParse->nTableLock; i++){
   81338     TableLock *p = &pParse->aTableLock[i];
   81339     int p1 = p->iDb;
   81340     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   81341                       p->zName, P4_STATIC);
   81342   }
   81343 }
   81344 #else
   81345   #define codeTableLocks(x)
   81346 #endif
   81347 
   81348 /*
   81349 ** This routine is called after a single SQL statement has been
   81350 ** parsed and a VDBE program to execute that statement has been
   81351 ** prepared.  This routine puts the finishing touches on the
   81352 ** VDBE program and resets the pParse structure for the next
   81353 ** parse.
   81354 **
   81355 ** Note that if an error occurred, it might be the case that
   81356 ** no VDBE code was generated.
   81357 */
   81358 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   81359   sqlite3 *db;
   81360   Vdbe *v;
   81361 
   81362   db = pParse->db;
   81363   if( db->mallocFailed ) return;
   81364   if( pParse->nested ) return;
   81365   if( pParse->nErr ) return;
   81366 
   81367   /* Begin by generating some termination code at the end of the
   81368   ** vdbe program
   81369   */
   81370   v = sqlite3GetVdbe(pParse);
   81371   assert( !pParse->isMultiWrite
   81372        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   81373   if( v ){
   81374     sqlite3VdbeAddOp0(v, OP_Halt);
   81375 
   81376     /* The cookie mask contains one bit for each database file open.
   81377     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   81378     ** set for each database that is used.  Generate code to start a
   81379     ** transaction on each used database and to verify the schema cookie
   81380     ** on each used database.
   81381     */
   81382     if( pParse->cookieGoto>0 ){
   81383       yDbMask mask;
   81384       int iDb;
   81385       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   81386       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   81387         if( (mask & pParse->cookieMask)==0 ) continue;
   81388         sqlite3VdbeUsesBtree(v, iDb);
   81389         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   81390         if( db->init.busy==0 ){
   81391           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81392           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
   81393                             iDb, pParse->cookieValue[iDb],
   81394                             db->aDb[iDb].pSchema->iGeneration);
   81395         }
   81396       }
   81397 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81398       {
   81399         int i;
   81400         for(i=0; i<pParse->nVtabLock; i++){
   81401           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   81402           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   81403         }
   81404         pParse->nVtabLock = 0;
   81405       }
   81406 #endif
   81407 
   81408       /* Once all the cookies have been verified and transactions opened,
   81409       ** obtain the required table-locks. This is a no-op unless the
   81410       ** shared-cache feature is enabled.
   81411       */
   81412       codeTableLocks(pParse);
   81413 
   81414       /* Initialize any AUTOINCREMENT data structures required.
   81415       */
   81416       sqlite3AutoincrementBegin(pParse);
   81417 
   81418       /* Finally, jump back to the beginning of the executable code. */
   81419       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
   81420     }
   81421   }
   81422 
   81423 
   81424   /* Get the VDBE program ready for execution
   81425   */
   81426   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   81427 #ifdef SQLITE_DEBUG
   81428     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   81429     sqlite3VdbeTrace(v, trace);
   81430 #endif
   81431     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   81432     /* A minimum of one cursor is required if autoincrement is used
   81433     *  See ticket [a696379c1f08866] */
   81434     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   81435     sqlite3VdbeMakeReady(v, pParse);
   81436     pParse->rc = SQLITE_DONE;
   81437     pParse->colNamesSet = 0;
   81438   }else{
   81439     pParse->rc = SQLITE_ERROR;
   81440   }
   81441   pParse->nTab = 0;
   81442   pParse->nMem = 0;
   81443   pParse->nSet = 0;
   81444   pParse->nVar = 0;
   81445   pParse->cookieMask = 0;
   81446   pParse->cookieGoto = 0;
   81447 }
   81448 
   81449 /*
   81450 ** Run the parser and code generator recursively in order to generate
   81451 ** code for the SQL statement given onto the end of the pParse context
   81452 ** currently under construction.  When the parser is run recursively
   81453 ** this way, the final OP_Halt is not appended and other initialization
   81454 ** and finalization steps are omitted because those are handling by the
   81455 ** outermost parser.
   81456 **
   81457 ** Not everything is nestable.  This facility is designed to permit
   81458 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   81459 ** care if you decide to try to use this routine for some other purposes.
   81460 */
   81461 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   81462   va_list ap;
   81463   char *zSql;
   81464   char *zErrMsg = 0;
   81465   sqlite3 *db = pParse->db;
   81466 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   81467   char saveBuf[SAVE_SZ];
   81468 
   81469   if( pParse->nErr ) return;
   81470   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   81471   va_start(ap, zFormat);
   81472   zSql = sqlite3VMPrintf(db, zFormat, ap);
   81473   va_end(ap);
   81474   if( zSql==0 ){
   81475     return;   /* A malloc must have failed */
   81476   }
   81477   pParse->nested++;
   81478   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   81479   memset(&pParse->nVar, 0, SAVE_SZ);
   81480   sqlite3RunParser(pParse, zSql, &zErrMsg);
   81481   sqlite3DbFree(db, zErrMsg);
   81482   sqlite3DbFree(db, zSql);
   81483   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   81484   pParse->nested--;
   81485 }
   81486 
   81487 /*
   81488 ** Locate the in-memory structure that describes a particular database
   81489 ** table given the name of that table and (optionally) the name of the
   81490 ** database containing the table.  Return NULL if not found.
   81491 **
   81492 ** If zDatabase is 0, all databases are searched for the table and the
   81493 ** first matching table is returned.  (No checking for duplicate table
   81494 ** names is done.)  The search order is TEMP first, then MAIN, then any
   81495 ** auxiliary databases added using the ATTACH command.
   81496 **
   81497 ** See also sqlite3LocateTable().
   81498 */
   81499 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   81500   Table *p = 0;
   81501   int i;
   81502   int nName;
   81503   assert( zName!=0 );
   81504   nName = sqlite3Strlen30(zName);
   81505   /* All mutexes are required for schema access.  Make sure we hold them. */
   81506   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   81507   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   81508     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   81509     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   81510     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   81511     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   81512     if( p ) break;
   81513   }
   81514   return p;
   81515 }
   81516 
   81517 /*
   81518 ** Locate the in-memory structure that describes a particular database
   81519 ** table given the name of that table and (optionally) the name of the
   81520 ** database containing the table.  Return NULL if not found.  Also leave an
   81521 ** error message in pParse->zErrMsg.
   81522 **
   81523 ** The difference between this routine and sqlite3FindTable() is that this
   81524 ** routine leaves an error message in pParse->zErrMsg where
   81525 ** sqlite3FindTable() does not.
   81526 */
   81527 SQLITE_PRIVATE Table *sqlite3LocateTable(
   81528   Parse *pParse,         /* context in which to report errors */
   81529   int isView,            /* True if looking for a VIEW rather than a TABLE */
   81530   const char *zName,     /* Name of the table we are looking for */
   81531   const char *zDbase     /* Name of the database.  Might be NULL */
   81532 ){
   81533   Table *p;
   81534 
   81535   /* Read the database schema. If an error occurs, leave an error message
   81536   ** and code in pParse and return NULL. */
   81537   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   81538     return 0;
   81539   }
   81540 
   81541   p = sqlite3FindTable(pParse->db, zName, zDbase);
   81542   if( p==0 ){
   81543     const char *zMsg = isView ? "no such view" : "no such table";
   81544     if( zDbase ){
   81545       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   81546     }else{
   81547       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   81548     }
   81549     pParse->checkSchema = 1;
   81550   }
   81551   return p;
   81552 }
   81553 
   81554 /*
   81555 ** Locate the in-memory structure that describes
   81556 ** a particular index given the name of that index
   81557 ** and the name of the database that contains the index.
   81558 ** Return NULL if not found.
   81559 **
   81560 ** If zDatabase is 0, all databases are searched for the
   81561 ** table and the first matching index is returned.  (No checking
   81562 ** for duplicate index names is done.)  The search order is
   81563 ** TEMP first, then MAIN, then any auxiliary databases added
   81564 ** using the ATTACH command.
   81565 */
   81566 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   81567   Index *p = 0;
   81568   int i;
   81569   int nName = sqlite3Strlen30(zName);
   81570   /* All mutexes are required for schema access.  Make sure we hold them. */
   81571   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   81572   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   81573     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   81574     Schema *pSchema = db->aDb[j].pSchema;
   81575     assert( pSchema );
   81576     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   81577     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   81578     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   81579     if( p ) break;
   81580   }
   81581   return p;
   81582 }
   81583 
   81584 /*
   81585 ** Reclaim the memory used by an index
   81586 */
   81587 static void freeIndex(sqlite3 *db, Index *p){
   81588 #ifndef SQLITE_OMIT_ANALYZE
   81589   sqlite3DeleteIndexSamples(db, p);
   81590 #endif
   81591   sqlite3DbFree(db, p->zColAff);
   81592   sqlite3DbFree(db, p);
   81593 }
   81594 
   81595 /*
   81596 ** For the index called zIdxName which is found in the database iDb,
   81597 ** unlike that index from its Table then remove the index from
   81598 ** the index hash table and free all memory structures associated
   81599 ** with the index.
   81600 */
   81601 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   81602   Index *pIndex;
   81603   int len;
   81604   Hash *pHash;
   81605 
   81606   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81607   pHash = &db->aDb[iDb].pSchema->idxHash;
   81608   len = sqlite3Strlen30(zIdxName);
   81609   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   81610   if( ALWAYS(pIndex) ){
   81611     if( pIndex->pTable->pIndex==pIndex ){
   81612       pIndex->pTable->pIndex = pIndex->pNext;
   81613     }else{
   81614       Index *p;
   81615       /* Justification of ALWAYS();  The index must be on the list of
   81616       ** indices. */
   81617       p = pIndex->pTable->pIndex;
   81618       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   81619       if( ALWAYS(p && p->pNext==pIndex) ){
   81620         p->pNext = pIndex->pNext;
   81621       }
   81622     }
   81623     freeIndex(db, pIndex);
   81624   }
   81625   db->flags |= SQLITE_InternChanges;
   81626 }
   81627 
   81628 /*
   81629 ** Erase all schema information from the in-memory hash tables of
   81630 ** a single database.  This routine is called to reclaim memory
   81631 ** before the database closes.  It is also called during a rollback
   81632 ** if there were schema changes during the transaction or if a
   81633 ** schema-cookie mismatch occurs.
   81634 **
   81635 ** If iDb<0 then reset the internal schema tables for all database
   81636 ** files.  If iDb>=0 then reset the internal schema for only the
   81637 ** single file indicated.
   81638 */
   81639 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   81640   int i, j;
   81641   assert( iDb<db->nDb );
   81642 
   81643   if( iDb>=0 ){
   81644     /* Case 1:  Reset the single schema identified by iDb */
   81645     Db *pDb = &db->aDb[iDb];
   81646     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81647     assert( pDb->pSchema!=0 );
   81648     sqlite3SchemaClear(pDb->pSchema);
   81649 
   81650     /* If any database other than TEMP is reset, then also reset TEMP
   81651     ** since TEMP might be holding triggers that reference tables in the
   81652     ** other database.
   81653     */
   81654     if( iDb!=1 ){
   81655       pDb = &db->aDb[1];
   81656       assert( pDb->pSchema!=0 );
   81657       sqlite3SchemaClear(pDb->pSchema);
   81658     }
   81659     return;
   81660   }
   81661   /* Case 2 (from here to the end): Reset all schemas for all attached
   81662   ** databases. */
   81663   assert( iDb<0 );
   81664   sqlite3BtreeEnterAll(db);
   81665   for(i=0; i<db->nDb; i++){
   81666     Db *pDb = &db->aDb[i];
   81667     if( pDb->pSchema ){
   81668       sqlite3SchemaClear(pDb->pSchema);
   81669     }
   81670   }
   81671   db->flags &= ~SQLITE_InternChanges;
   81672   sqlite3VtabUnlockList(db);
   81673   sqlite3BtreeLeaveAll(db);
   81674 
   81675   /* If one or more of the auxiliary database files has been closed,
   81676   ** then remove them from the auxiliary database list.  We take the
   81677   ** opportunity to do this here since we have just deleted all of the
   81678   ** schema hash tables and therefore do not have to make any changes
   81679   ** to any of those tables.
   81680   */
   81681   for(i=j=2; i<db->nDb; i++){
   81682     struct Db *pDb = &db->aDb[i];
   81683     if( pDb->pBt==0 ){
   81684       sqlite3DbFree(db, pDb->zName);
   81685       pDb->zName = 0;
   81686       continue;
   81687     }
   81688     if( j<i ){
   81689       db->aDb[j] = db->aDb[i];
   81690     }
   81691     j++;
   81692   }
   81693   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   81694   db->nDb = j;
   81695   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   81696     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   81697     sqlite3DbFree(db, db->aDb);
   81698     db->aDb = db->aDbStatic;
   81699   }
   81700 }
   81701 
   81702 /*
   81703 ** This routine is called when a commit occurs.
   81704 */
   81705 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   81706   db->flags &= ~SQLITE_InternChanges;
   81707 }
   81708 
   81709 /*
   81710 ** Delete memory allocated for the column names of a table or view (the
   81711 ** Table.aCol[] array).
   81712 */
   81713 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   81714   int i;
   81715   Column *pCol;
   81716   assert( pTable!=0 );
   81717   if( (pCol = pTable->aCol)!=0 ){
   81718     for(i=0; i<pTable->nCol; i++, pCol++){
   81719       sqlite3DbFree(db, pCol->zName);
   81720       sqlite3ExprDelete(db, pCol->pDflt);
   81721       sqlite3DbFree(db, pCol->zDflt);
   81722       sqlite3DbFree(db, pCol->zType);
   81723       sqlite3DbFree(db, pCol->zColl);
   81724     }
   81725     sqlite3DbFree(db, pTable->aCol);
   81726   }
   81727 }
   81728 
   81729 /*
   81730 ** Remove the memory data structures associated with the given
   81731 ** Table.  No changes are made to disk by this routine.
   81732 **
   81733 ** This routine just deletes the data structure.  It does not unlink
   81734 ** the table data structure from the hash table.  But it does destroy
   81735 ** memory structures of the indices and foreign keys associated with
   81736 ** the table.
   81737 */
   81738 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   81739   Index *pIndex, *pNext;
   81740 
   81741   assert( !pTable || pTable->nRef>0 );
   81742 
   81743   /* Do not delete the table until the reference count reaches zero. */
   81744   if( !pTable ) return;
   81745   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   81746 
   81747   /* Delete all indices associated with this table. */
   81748   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   81749     pNext = pIndex->pNext;
   81750     assert( pIndex->pSchema==pTable->pSchema );
   81751     if( !db || db->pnBytesFreed==0 ){
   81752       char *zName = pIndex->zName;
   81753       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   81754 	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
   81755       );
   81756       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   81757       assert( pOld==pIndex || pOld==0 );
   81758     }
   81759     freeIndex(db, pIndex);
   81760   }
   81761 
   81762   /* Delete any foreign keys attached to this table. */
   81763   sqlite3FkDelete(db, pTable);
   81764 
   81765   /* Delete the Table structure itself.
   81766   */
   81767   sqliteDeleteColumnNames(db, pTable);
   81768   sqlite3DbFree(db, pTable->zName);
   81769   sqlite3DbFree(db, pTable->zColAff);
   81770   sqlite3SelectDelete(db, pTable->pSelect);
   81771 #ifndef SQLITE_OMIT_CHECK
   81772   sqlite3ExprDelete(db, pTable->pCheck);
   81773 #endif
   81774 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81775   sqlite3VtabClear(db, pTable);
   81776 #endif
   81777   sqlite3DbFree(db, pTable);
   81778 }
   81779 
   81780 /*
   81781 ** Unlink the given table from the hash tables and the delete the
   81782 ** table structure with all its indices and foreign keys.
   81783 */
   81784 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   81785   Table *p;
   81786   Db *pDb;
   81787 
   81788   assert( db!=0 );
   81789   assert( iDb>=0 && iDb<db->nDb );
   81790   assert( zTabName );
   81791   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81792   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   81793   pDb = &db->aDb[iDb];
   81794   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   81795                         sqlite3Strlen30(zTabName),0);
   81796   sqlite3DeleteTable(db, p);
   81797   db->flags |= SQLITE_InternChanges;
   81798 }
   81799 
   81800 /*
   81801 ** Given a token, return a string that consists of the text of that
   81802 ** token.  Space to hold the returned string
   81803 ** is obtained from sqliteMalloc() and must be freed by the calling
   81804 ** function.
   81805 **
   81806 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   81807 ** surround the body of the token are removed.
   81808 **
   81809 ** Tokens are often just pointers into the original SQL text and so
   81810 ** are not \000 terminated and are not persistent.  The returned string
   81811 ** is \000 terminated and is persistent.
   81812 */
   81813 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   81814   char *zName;
   81815   if( pName ){
   81816     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   81817     sqlite3Dequote(zName);
   81818   }else{
   81819     zName = 0;
   81820   }
   81821   return zName;
   81822 }
   81823 
   81824 /*
   81825 ** Open the sqlite_master table stored in database number iDb for
   81826 ** writing. The table is opened using cursor 0.
   81827 */
   81828 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   81829   Vdbe *v = sqlite3GetVdbe(p);
   81830   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   81831   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
   81832   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
   81833   if( p->nTab==0 ){
   81834     p->nTab = 1;
   81835   }
   81836 }
   81837 
   81838 /*
   81839 ** Parameter zName points to a nul-terminated buffer containing the name
   81840 ** of a database ("main", "temp" or the name of an attached db). This
   81841 ** function returns the index of the named database in db->aDb[], or
   81842 ** -1 if the named db cannot be found.
   81843 */
   81844 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   81845   int i = -1;         /* Database number */
   81846   if( zName ){
   81847     Db *pDb;
   81848     int n = sqlite3Strlen30(zName);
   81849     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   81850       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   81851           0==sqlite3StrICmp(pDb->zName, zName) ){
   81852         break;
   81853       }
   81854     }
   81855   }
   81856   return i;
   81857 }
   81858 
   81859 /*
   81860 ** The token *pName contains the name of a database (either "main" or
   81861 ** "temp" or the name of an attached db). This routine returns the
   81862 ** index of the named database in db->aDb[], or -1 if the named db
   81863 ** does not exist.
   81864 */
   81865 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   81866   int i;                               /* Database number */
   81867   char *zName;                         /* Name we are searching for */
   81868   zName = sqlite3NameFromToken(db, pName);
   81869   i = sqlite3FindDbName(db, zName);
   81870   sqlite3DbFree(db, zName);
   81871   return i;
   81872 }
   81873 
   81874 /* The table or view or trigger name is passed to this routine via tokens
   81875 ** pName1 and pName2. If the table name was fully qualified, for example:
   81876 **
   81877 ** CREATE TABLE xxx.yyy (...);
   81878 **
   81879 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   81880 ** the table name is not fully qualified, i.e.:
   81881 **
   81882 ** CREATE TABLE yyy(...);
   81883 **
   81884 ** Then pName1 is set to "yyy" and pName2 is "".
   81885 **
   81886 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   81887 ** pName2) that stores the unqualified table name.  The index of the
   81888 ** database "xxx" is returned.
   81889 */
   81890 SQLITE_PRIVATE int sqlite3TwoPartName(
   81891   Parse *pParse,      /* Parsing and code generating context */
   81892   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   81893   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   81894   Token **pUnqual     /* Write the unqualified object name here */
   81895 ){
   81896   int iDb;                    /* Database holding the object */
   81897   sqlite3 *db = pParse->db;
   81898 
   81899   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   81900     if( db->init.busy ) {
   81901       sqlite3ErrorMsg(pParse, "corrupt database");
   81902       pParse->nErr++;
   81903       return -1;
   81904     }
   81905     *pUnqual = pName2;
   81906     iDb = sqlite3FindDb(db, pName1);
   81907     if( iDb<0 ){
   81908       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   81909       pParse->nErr++;
   81910       return -1;
   81911     }
   81912   }else{
   81913     assert( db->init.iDb==0 || db->init.busy );
   81914     iDb = db->init.iDb;
   81915     *pUnqual = pName1;
   81916   }
   81917   return iDb;
   81918 }
   81919 
   81920 /*
   81921 ** This routine is used to check if the UTF-8 string zName is a legal
   81922 ** unqualified name for a new schema object (table, index, view or
   81923 ** trigger). All names are legal except those that begin with the string
   81924 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   81925 ** is reserved for internal use.
   81926 */
   81927 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   81928   if( !pParse->db->init.busy && pParse->nested==0
   81929           && (pParse->db->flags & SQLITE_WriteSchema)==0
   81930           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   81931     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   81932     return SQLITE_ERROR;
   81933   }
   81934   return SQLITE_OK;
   81935 }
   81936 
   81937 /*
   81938 ** Begin constructing a new table representation in memory.  This is
   81939 ** the first of several action routines that get called in response
   81940 ** to a CREATE TABLE statement.  In particular, this routine is called
   81941 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   81942 ** flag is true if the table should be stored in the auxiliary database
   81943 ** file instead of in the main database file.  This is normally the case
   81944 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   81945 ** CREATE and TABLE.
   81946 **
   81947 ** The new table record is initialized and put in pParse->pNewTable.
   81948 ** As more of the CREATE TABLE statement is parsed, additional action
   81949 ** routines will be called to add more information to this record.
   81950 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   81951 ** is called to complete the construction of the new table record.
   81952 */
   81953 SQLITE_PRIVATE void sqlite3StartTable(
   81954   Parse *pParse,   /* Parser context */
   81955   Token *pName1,   /* First part of the name of the table or view */
   81956   Token *pName2,   /* Second part of the name of the table or view */
   81957   int isTemp,      /* True if this is a TEMP table */
   81958   int isView,      /* True if this is a VIEW */
   81959   int isVirtual,   /* True if this is a VIRTUAL table */
   81960   int noErr        /* Do nothing if table already exists */
   81961 ){
   81962   Table *pTable;
   81963   char *zName = 0; /* The name of the new table */
   81964   sqlite3 *db = pParse->db;
   81965   Vdbe *v;
   81966   int iDb;         /* Database number to create the table in */
   81967   Token *pName;    /* Unqualified name of the table to create */
   81968 
   81969   /* The table or view name to create is passed to this routine via tokens
   81970   ** pName1 and pName2. If the table name was fully qualified, for example:
   81971   **
   81972   ** CREATE TABLE xxx.yyy (...);
   81973   **
   81974   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   81975   ** the table name is not fully qualified, i.e.:
   81976   **
   81977   ** CREATE TABLE yyy(...);
   81978   **
   81979   ** Then pName1 is set to "yyy" and pName2 is "".
   81980   **
   81981   ** The call below sets the pName pointer to point at the token (pName1 or
   81982   ** pName2) that stores the unqualified table name. The variable iDb is
   81983   ** set to the index of the database that the table or view is to be
   81984   ** created in.
   81985   */
   81986   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   81987   if( iDb<0 ) return;
   81988   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   81989     /* If creating a temp table, the name may not be qualified. Unless
   81990     ** the database name is "temp" anyway.  */
   81991     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   81992     return;
   81993   }
   81994   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   81995 
   81996   pParse->sNameToken = *pName;
   81997   zName = sqlite3NameFromToken(db, pName);
   81998   if( zName==0 ) return;
   81999   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   82000     goto begin_table_error;
   82001   }
   82002   if( db->init.iDb==1 ) isTemp = 1;
   82003 #ifndef SQLITE_OMIT_AUTHORIZATION
   82004   assert( (isTemp & 1)==isTemp );
   82005   {
   82006     int code;
   82007     char *zDb = db->aDb[iDb].zName;
   82008     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   82009       goto begin_table_error;
   82010     }
   82011     if( isView ){
   82012       if( !OMIT_TEMPDB && isTemp ){
   82013         code = SQLITE_CREATE_TEMP_VIEW;
   82014       }else{
   82015         code = SQLITE_CREATE_VIEW;
   82016       }
   82017     }else{
   82018       if( !OMIT_TEMPDB && isTemp ){
   82019         code = SQLITE_CREATE_TEMP_TABLE;
   82020       }else{
   82021         code = SQLITE_CREATE_TABLE;
   82022       }
   82023     }
   82024     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   82025       goto begin_table_error;
   82026     }
   82027   }
   82028 #endif
   82029 
   82030   /* Make sure the new table name does not collide with an existing
   82031   ** index or table name in the same database.  Issue an error message if
   82032   ** it does. The exception is if the statement being parsed was passed
   82033   ** to an sqlite3_declare_vtab() call. In that case only the column names
   82034   ** and types will be used, so there is no need to test for namespace
   82035   ** collisions.
   82036   */
   82037   if( !IN_DECLARE_VTAB ){
   82038     char *zDb = db->aDb[iDb].zName;
   82039     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   82040       goto begin_table_error;
   82041     }
   82042     pTable = sqlite3FindTable(db, zName, zDb);
   82043     if( pTable ){
   82044       if( !noErr ){
   82045         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   82046       }else{
   82047         assert( !db->init.busy );
   82048         sqlite3CodeVerifySchema(pParse, iDb);
   82049       }
   82050       goto begin_table_error;
   82051     }
   82052     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   82053       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   82054       goto begin_table_error;
   82055     }
   82056   }
   82057 
   82058   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   82059   if( pTable==0 ){
   82060     db->mallocFailed = 1;
   82061     pParse->rc = SQLITE_NOMEM;
   82062     pParse->nErr++;
   82063     goto begin_table_error;
   82064   }
   82065   pTable->zName = zName;
   82066   pTable->iPKey = -1;
   82067   pTable->pSchema = db->aDb[iDb].pSchema;
   82068   pTable->nRef = 1;
   82069   pTable->nRowEst = 1000000;
   82070   assert( pParse->pNewTable==0 );
   82071   pParse->pNewTable = pTable;
   82072 
   82073   /* If this is the magic sqlite_sequence table used by autoincrement,
   82074   ** then record a pointer to this table in the main database structure
   82075   ** so that INSERT can find the table easily.
   82076   */
   82077 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82078   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   82079     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82080     pTable->pSchema->pSeqTab = pTable;
   82081   }
   82082 #endif
   82083 
   82084   /* Begin generating the code that will insert the table record into
   82085   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   82086   ** and allocate the record number for the table entry now.  Before any
   82087   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   82088   ** indices to be created and the table record must come before the
   82089   ** indices.  Hence, the record number for the table must be allocated
   82090   ** now.
   82091   */
   82092   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   82093     int j1;
   82094     int fileFormat;
   82095     int reg1, reg2, reg3;
   82096     sqlite3BeginWriteOperation(pParse, 0, iDb);
   82097 
   82098 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82099     if( isVirtual ){
   82100       sqlite3VdbeAddOp0(v, OP_VBegin);
   82101     }
   82102 #endif
   82103 
   82104     /* If the file format and encoding in the database have not been set,
   82105     ** set them now.
   82106     */
   82107     reg1 = pParse->regRowid = ++pParse->nMem;
   82108     reg2 = pParse->regRoot = ++pParse->nMem;
   82109     reg3 = ++pParse->nMem;
   82110     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   82111     sqlite3VdbeUsesBtree(v, iDb);
   82112     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
   82113     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   82114                   1 : SQLITE_MAX_FILE_FORMAT;
   82115     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   82116     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   82117     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   82118     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   82119     sqlite3VdbeJumpHere(v, j1);
   82120 
   82121     /* This just creates a place-holder record in the sqlite_master table.
   82122     ** The record created does not contain anything yet.  It will be replaced
   82123     ** by the real entry in code generated at sqlite3EndTable().
   82124     **
   82125     ** The rowid for the new entry is left in register pParse->regRowid.
   82126     ** The root page number of the new table is left in reg pParse->regRoot.
   82127     ** The rowid and root page number values are needed by the code that
   82128     ** sqlite3EndTable will generate.
   82129     */
   82130 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   82131     if( isView || isVirtual ){
   82132       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   82133     }else
   82134 #endif
   82135     {
   82136       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   82137     }
   82138     sqlite3OpenMasterTable(pParse, iDb);
   82139     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   82140     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   82141     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   82142     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   82143     sqlite3VdbeAddOp0(v, OP_Close);
   82144   }
   82145 
   82146   /* Normal (non-error) return. */
   82147   return;
   82148 
   82149   /* If an error occurs, we jump here */
   82150 begin_table_error:
   82151   sqlite3DbFree(db, zName);
   82152   return;
   82153 }
   82154 
   82155 /*
   82156 ** This macro is used to compare two strings in a case-insensitive manner.
   82157 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   82158 ** produces larger code.
   82159 **
   82160 ** WARNING: This macro is not compatible with the strcmp() family. It
   82161 ** returns true if the two strings are equal, otherwise false.
   82162 */
   82163 #define STRICMP(x, y) (\
   82164 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   82165 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   82166 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   82167 
   82168 /*
   82169 ** Add a new column to the table currently being constructed.
   82170 **
   82171 ** The parser calls this routine once for each column declaration
   82172 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   82173 ** first to get things going.  Then this routine is called for each
   82174 ** column.
   82175 */
   82176 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   82177   Table *p;
   82178   int i;
   82179   char *z;
   82180   Column *pCol;
   82181   sqlite3 *db = pParse->db;
   82182   if( (p = pParse->pNewTable)==0 ) return;
   82183 #if SQLITE_MAX_COLUMN
   82184   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   82185     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   82186     return;
   82187   }
   82188 #endif
   82189   z = sqlite3NameFromToken(db, pName);
   82190   if( z==0 ) return;
   82191   for(i=0; i<p->nCol; i++){
   82192     if( STRICMP(z, p->aCol[i].zName) ){
   82193       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   82194       sqlite3DbFree(db, z);
   82195       return;
   82196     }
   82197   }
   82198   if( (p->nCol & 0x7)==0 ){
   82199     Column *aNew;
   82200     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   82201     if( aNew==0 ){
   82202       sqlite3DbFree(db, z);
   82203       return;
   82204     }
   82205     p->aCol = aNew;
   82206   }
   82207   pCol = &p->aCol[p->nCol];
   82208   memset(pCol, 0, sizeof(p->aCol[0]));
   82209   pCol->zName = z;
   82210 
   82211   /* If there is no type specified, columns have the default affinity
   82212   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   82213   ** be called next to set pCol->affinity correctly.
   82214   */
   82215   pCol->affinity = SQLITE_AFF_NONE;
   82216   p->nCol++;
   82217 }
   82218 
   82219 /*
   82220 ** This routine is called by the parser while in the middle of
   82221 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   82222 ** been seen on a column.  This routine sets the notNull flag on
   82223 ** the column currently under construction.
   82224 */
   82225 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   82226   Table *p;
   82227   p = pParse->pNewTable;
   82228   if( p==0 || NEVER(p->nCol<1) ) return;
   82229   p->aCol[p->nCol-1].notNull = (u8)onError;
   82230 }
   82231 
   82232 /*
   82233 ** Scan the column type name zType (length nType) and return the
   82234 ** associated affinity type.
   82235 **
   82236 ** This routine does a case-independent search of zType for the
   82237 ** substrings in the following table. If one of the substrings is
   82238 ** found, the corresponding affinity is returned. If zType contains
   82239 ** more than one of the substrings, entries toward the top of
   82240 ** the table take priority. For example, if zType is 'BLOBINT',
   82241 ** SQLITE_AFF_INTEGER is returned.
   82242 **
   82243 ** Substring     | Affinity
   82244 ** --------------------------------
   82245 ** 'INT'         | SQLITE_AFF_INTEGER
   82246 ** 'CHAR'        | SQLITE_AFF_TEXT
   82247 ** 'CLOB'        | SQLITE_AFF_TEXT
   82248 ** 'TEXT'        | SQLITE_AFF_TEXT
   82249 ** 'BLOB'        | SQLITE_AFF_NONE
   82250 ** 'REAL'        | SQLITE_AFF_REAL
   82251 ** 'FLOA'        | SQLITE_AFF_REAL
   82252 ** 'DOUB'        | SQLITE_AFF_REAL
   82253 **
   82254 ** If none of the substrings in the above table are found,
   82255 ** SQLITE_AFF_NUMERIC is returned.
   82256 */
   82257 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
   82258   u32 h = 0;
   82259   char aff = SQLITE_AFF_NUMERIC;
   82260 
   82261   if( zIn ) while( zIn[0] ){
   82262     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   82263     zIn++;
   82264     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   82265       aff = SQLITE_AFF_TEXT;
   82266     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   82267       aff = SQLITE_AFF_TEXT;
   82268     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   82269       aff = SQLITE_AFF_TEXT;
   82270     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   82271         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   82272       aff = SQLITE_AFF_NONE;
   82273 #ifndef SQLITE_OMIT_FLOATING_POINT
   82274     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   82275         && aff==SQLITE_AFF_NUMERIC ){
   82276       aff = SQLITE_AFF_REAL;
   82277     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   82278         && aff==SQLITE_AFF_NUMERIC ){
   82279       aff = SQLITE_AFF_REAL;
   82280     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   82281         && aff==SQLITE_AFF_NUMERIC ){
   82282       aff = SQLITE_AFF_REAL;
   82283 #endif
   82284     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   82285       aff = SQLITE_AFF_INTEGER;
   82286       break;
   82287     }
   82288   }
   82289 
   82290   return aff;
   82291 }
   82292 
   82293 /*
   82294 ** This routine is called by the parser while in the middle of
   82295 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   82296 ** token in the sequence of tokens that describe the type of the
   82297 ** column currently under construction.   pLast is the last token
   82298 ** in the sequence.  Use this information to construct a string
   82299 ** that contains the typename of the column and store that string
   82300 ** in zType.
   82301 */
   82302 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   82303   Table *p;
   82304   Column *pCol;
   82305 
   82306   p = pParse->pNewTable;
   82307   if( p==0 || NEVER(p->nCol<1) ) return;
   82308   pCol = &p->aCol[p->nCol-1];
   82309   assert( pCol->zType==0 );
   82310   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   82311   pCol->affinity = sqlite3AffinityType(pCol->zType);
   82312 }
   82313 
   82314 /*
   82315 ** The expression is the default value for the most recently added column
   82316 ** of the table currently under construction.
   82317 **
   82318 ** Default value expressions must be constant.  Raise an exception if this
   82319 ** is not the case.
   82320 **
   82321 ** This routine is called by the parser while in the middle of
   82322 ** parsing a CREATE TABLE statement.
   82323 */
   82324 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   82325   Table *p;
   82326   Column *pCol;
   82327   sqlite3 *db = pParse->db;
   82328   p = pParse->pNewTable;
   82329   if( p!=0 ){
   82330     pCol = &(p->aCol[p->nCol-1]);
   82331     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   82332       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   82333           pCol->zName);
   82334     }else{
   82335       /* A copy of pExpr is used instead of the original, as pExpr contains
   82336       ** tokens that point to volatile memory. The 'span' of the expression
   82337       ** is required by pragma table_info.
   82338       */
   82339       sqlite3ExprDelete(db, pCol->pDflt);
   82340       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   82341       sqlite3DbFree(db, pCol->zDflt);
   82342       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   82343                                      (int)(pSpan->zEnd - pSpan->zStart));
   82344     }
   82345   }
   82346   sqlite3ExprDelete(db, pSpan->pExpr);
   82347 }
   82348 
   82349 /*
   82350 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   82351 ** of columns that form the primary key.  If pList is NULL, then the
   82352 ** most recently added column of the table is the primary key.
   82353 **
   82354 ** A table can have at most one primary key.  If the table already has
   82355 ** a primary key (and this is the second primary key) then create an
   82356 ** error.
   82357 **
   82358 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   82359 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   82360 ** field of the table under construction to be the index of the
   82361 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   82362 ** no INTEGER PRIMARY KEY.
   82363 **
   82364 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   82365 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   82366 */
   82367 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   82368   Parse *pParse,    /* Parsing context */
   82369   ExprList *pList,  /* List of field names to be indexed */
   82370   int onError,      /* What to do with a uniqueness conflict */
   82371   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   82372   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   82373 ){
   82374   Table *pTab = pParse->pNewTable;
   82375   char *zType = 0;
   82376   int iCol = -1, i;
   82377   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   82378   if( pTab->tabFlags & TF_HasPrimaryKey ){
   82379     sqlite3ErrorMsg(pParse,
   82380       "table \"%s\" has more than one primary key", pTab->zName);
   82381     goto primary_key_exit;
   82382   }
   82383   pTab->tabFlags |= TF_HasPrimaryKey;
   82384   if( pList==0 ){
   82385     iCol = pTab->nCol - 1;
   82386     pTab->aCol[iCol].isPrimKey = 1;
   82387   }else{
   82388     for(i=0; i<pList->nExpr; i++){
   82389       for(iCol=0; iCol<pTab->nCol; iCol++){
   82390         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   82391           break;
   82392         }
   82393       }
   82394       if( iCol<pTab->nCol ){
   82395         pTab->aCol[iCol].isPrimKey = 1;
   82396       }
   82397     }
   82398     if( pList->nExpr>1 ) iCol = -1;
   82399   }
   82400   if( iCol>=0 && iCol<pTab->nCol ){
   82401     zType = pTab->aCol[iCol].zType;
   82402   }
   82403   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
   82404         && sortOrder==SQLITE_SO_ASC ){
   82405     pTab->iPKey = iCol;
   82406     pTab->keyConf = (u8)onError;
   82407     assert( autoInc==0 || autoInc==1 );
   82408     pTab->tabFlags |= autoInc*TF_Autoincrement;
   82409   }else if( autoInc ){
   82410 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82411     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   82412        "INTEGER PRIMARY KEY");
   82413 #endif
   82414   }else{
   82415     Index *p;
   82416     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
   82417     if( p ){
   82418       p->autoIndex = 2;
   82419     }
   82420     pList = 0;
   82421   }
   82422 
   82423 primary_key_exit:
   82424   sqlite3ExprListDelete(pParse->db, pList);
   82425   return;
   82426 }
   82427 
   82428 /*
   82429 ** Add a new CHECK constraint to the table currently under construction.
   82430 */
   82431 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   82432   Parse *pParse,    /* Parsing context */
   82433   Expr *pCheckExpr  /* The check expression */
   82434 ){
   82435   sqlite3 *db = pParse->db;
   82436 #ifndef SQLITE_OMIT_CHECK
   82437   Table *pTab = pParse->pNewTable;
   82438   if( pTab && !IN_DECLARE_VTAB ){
   82439     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
   82440   }else
   82441 #endif
   82442   {
   82443     sqlite3ExprDelete(db, pCheckExpr);
   82444   }
   82445 }
   82446 
   82447 /*
   82448 ** Set the collation function of the most recently parsed table column
   82449 ** to the CollSeq given.
   82450 */
   82451 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   82452   Table *p;
   82453   int i;
   82454   char *zColl;              /* Dequoted name of collation sequence */
   82455   sqlite3 *db;
   82456 
   82457   if( (p = pParse->pNewTable)==0 ) return;
   82458   i = p->nCol-1;
   82459   db = pParse->db;
   82460   zColl = sqlite3NameFromToken(db, pToken);
   82461   if( !zColl ) return;
   82462 
   82463   if( sqlite3LocateCollSeq(pParse, zColl) ){
   82464     Index *pIdx;
   82465     p->aCol[i].zColl = zColl;
   82466 
   82467     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   82468     ** then an index may have been created on this column before the
   82469     ** collation type was added. Correct this if it is the case.
   82470     */
   82471     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   82472       assert( pIdx->nColumn==1 );
   82473       if( pIdx->aiColumn[0]==i ){
   82474         pIdx->azColl[0] = p->aCol[i].zColl;
   82475       }
   82476     }
   82477   }else{
   82478     sqlite3DbFree(db, zColl);
   82479   }
   82480 }
   82481 
   82482 /*
   82483 ** This function returns the collation sequence for database native text
   82484 ** encoding identified by the string zName, length nName.
   82485 **
   82486 ** If the requested collation sequence is not available, or not available
   82487 ** in the database native encoding, the collation factory is invoked to
   82488 ** request it. If the collation factory does not supply such a sequence,
   82489 ** and the sequence is available in another text encoding, then that is
   82490 ** returned instead.
   82491 **
   82492 ** If no versions of the requested collations sequence are available, or
   82493 ** another error occurs, NULL is returned and an error message written into
   82494 ** pParse.
   82495 **
   82496 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   82497 ** invokes the collation factory if the named collation cannot be found
   82498 ** and generates an error message.
   82499 **
   82500 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   82501 */
   82502 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   82503   sqlite3 *db = pParse->db;
   82504   u8 enc = ENC(db);
   82505   u8 initbusy = db->init.busy;
   82506   CollSeq *pColl;
   82507 
   82508   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   82509   if( !initbusy && (!pColl || !pColl->xCmp) ){
   82510     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
   82511     if( !pColl ){
   82512       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   82513     }
   82514   }
   82515 
   82516   return pColl;
   82517 }
   82518 
   82519 
   82520 /*
   82521 ** Generate code that will increment the schema cookie.
   82522 **
   82523 ** The schema cookie is used to determine when the schema for the
   82524 ** database changes.  After each schema change, the cookie value
   82525 ** changes.  When a process first reads the schema it records the
   82526 ** cookie.  Thereafter, whenever it goes to access the database,
   82527 ** it checks the cookie to make sure the schema has not changed
   82528 ** since it was last read.
   82529 **
   82530 ** This plan is not completely bullet-proof.  It is possible for
   82531 ** the schema to change multiple times and for the cookie to be
   82532 ** set back to prior value.  But schema changes are infrequent
   82533 ** and the probability of hitting the same cookie value is only
   82534 ** 1 chance in 2^32.  So we're safe enough.
   82535 */
   82536 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   82537   int r1 = sqlite3GetTempReg(pParse);
   82538   sqlite3 *db = pParse->db;
   82539   Vdbe *v = pParse->pVdbe;
   82540   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82541   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   82542   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   82543   sqlite3ReleaseTempReg(pParse, r1);
   82544 }
   82545 
   82546 /*
   82547 ** Measure the number of characters needed to output the given
   82548 ** identifier.  The number returned includes any quotes used
   82549 ** but does not include the null terminator.
   82550 **
   82551 ** The estimate is conservative.  It might be larger that what is
   82552 ** really needed.
   82553 */
   82554 static int identLength(const char *z){
   82555   int n;
   82556   for(n=0; *z; n++, z++){
   82557     if( *z=='"' ){ n++; }
   82558   }
   82559   return n + 2;
   82560 }
   82561 
   82562 /*
   82563 ** The first parameter is a pointer to an output buffer. The second
   82564 ** parameter is a pointer to an integer that contains the offset at
   82565 ** which to write into the output buffer. This function copies the
   82566 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   82567 ** to the specified offset in the buffer and updates *pIdx to refer
   82568 ** to the first byte after the last byte written before returning.
   82569 **
   82570 ** If the string zSignedIdent consists entirely of alpha-numeric
   82571 ** characters, does not begin with a digit and is not an SQL keyword,
   82572 ** then it is copied to the output buffer exactly as it is. Otherwise,
   82573 ** it is quoted using double-quotes.
   82574 */
   82575 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   82576   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   82577   int i, j, needQuote;
   82578   i = *pIdx;
   82579 
   82580   for(j=0; zIdent[j]; j++){
   82581     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   82582   }
   82583   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
   82584   if( !needQuote ){
   82585     needQuote = zIdent[j];
   82586   }
   82587 
   82588   if( needQuote ) z[i++] = '"';
   82589   for(j=0; zIdent[j]; j++){
   82590     z[i++] = zIdent[j];
   82591     if( zIdent[j]=='"' ) z[i++] = '"';
   82592   }
   82593   if( needQuote ) z[i++] = '"';
   82594   z[i] = 0;
   82595   *pIdx = i;
   82596 }
   82597 
   82598 /*
   82599 ** Generate a CREATE TABLE statement appropriate for the given
   82600 ** table.  Memory to hold the text of the statement is obtained
   82601 ** from sqliteMalloc() and must be freed by the calling function.
   82602 */
   82603 static char *createTableStmt(sqlite3 *db, Table *p){
   82604   int i, k, n;
   82605   char *zStmt;
   82606   char *zSep, *zSep2, *zEnd;
   82607   Column *pCol;
   82608   n = 0;
   82609   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   82610     n += identLength(pCol->zName) + 5;
   82611   }
   82612   n += identLength(p->zName);
   82613   if( n<50 ){
   82614     zSep = "";
   82615     zSep2 = ",";
   82616     zEnd = ")";
   82617   }else{
   82618     zSep = "\n  ";
   82619     zSep2 = ",\n  ";
   82620     zEnd = "\n)";
   82621   }
   82622   n += 35 + 6*p->nCol;
   82623   zStmt = sqlite3DbMallocRaw(0, n);
   82624   if( zStmt==0 ){
   82625     db->mallocFailed = 1;
   82626     return 0;
   82627   }
   82628   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   82629   k = sqlite3Strlen30(zStmt);
   82630   identPut(zStmt, &k, p->zName);
   82631   zStmt[k++] = '(';
   82632   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   82633     static const char * const azType[] = {
   82634         /* SQLITE_AFF_TEXT    */ " TEXT",
   82635         /* SQLITE_AFF_NONE    */ "",
   82636         /* SQLITE_AFF_NUMERIC */ " NUM",
   82637         /* SQLITE_AFF_INTEGER */ " INT",
   82638         /* SQLITE_AFF_REAL    */ " REAL"
   82639     };
   82640     int len;
   82641     const char *zType;
   82642 
   82643     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   82644     k += sqlite3Strlen30(&zStmt[k]);
   82645     zSep = zSep2;
   82646     identPut(zStmt, &k, pCol->zName);
   82647     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   82648     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
   82649     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   82650     testcase( pCol->affinity==SQLITE_AFF_NONE );
   82651     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   82652     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   82653     testcase( pCol->affinity==SQLITE_AFF_REAL );
   82654 
   82655     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   82656     len = sqlite3Strlen30(zType);
   82657     assert( pCol->affinity==SQLITE_AFF_NONE
   82658             || pCol->affinity==sqlite3AffinityType(zType) );
   82659     memcpy(&zStmt[k], zType, len);
   82660     k += len;
   82661     assert( k<=n );
   82662   }
   82663   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   82664   return zStmt;
   82665 }
   82666 
   82667 /*
   82668 ** This routine is called to report the final ")" that terminates
   82669 ** a CREATE TABLE statement.
   82670 **
   82671 ** The table structure that other action routines have been building
   82672 ** is added to the internal hash tables, assuming no errors have
   82673 ** occurred.
   82674 **
   82675 ** An entry for the table is made in the master table on disk, unless
   82676 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   82677 ** it means we are reading the sqlite_master table because we just
   82678 ** connected to the database or because the sqlite_master table has
   82679 ** recently changed, so the entry for this table already exists in
   82680 ** the sqlite_master table.  We do not want to create it again.
   82681 **
   82682 ** If the pSelect argument is not NULL, it means that this routine
   82683 ** was called to create a table generated from a
   82684 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   82685 ** the new table will match the result set of the SELECT.
   82686 */
   82687 SQLITE_PRIVATE void sqlite3EndTable(
   82688   Parse *pParse,          /* Parse context */
   82689   Token *pCons,           /* The ',' token after the last column defn. */
   82690   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
   82691   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   82692 ){
   82693   Table *p;
   82694   sqlite3 *db = pParse->db;
   82695   int iDb;
   82696 
   82697   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   82698     return;
   82699   }
   82700   p = pParse->pNewTable;
   82701   if( p==0 ) return;
   82702 
   82703   assert( !db->init.busy || !pSelect );
   82704 
   82705   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   82706 
   82707 #ifndef SQLITE_OMIT_CHECK
   82708   /* Resolve names in all CHECK constraint expressions.
   82709   */
   82710   if( p->pCheck ){
   82711     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   82712     NameContext sNC;                /* Name context for pParse->pNewTable */
   82713 
   82714     memset(&sNC, 0, sizeof(sNC));
   82715     memset(&sSrc, 0, sizeof(sSrc));
   82716     sSrc.nSrc = 1;
   82717     sSrc.a[0].zName = p->zName;
   82718     sSrc.a[0].pTab = p;
   82719     sSrc.a[0].iCursor = -1;
   82720     sNC.pParse = pParse;
   82721     sNC.pSrcList = &sSrc;
   82722     sNC.isCheck = 1;
   82723     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
   82724       return;
   82725     }
   82726   }
   82727 #endif /* !defined(SQLITE_OMIT_CHECK) */
   82728 
   82729   /* If the db->init.busy is 1 it means we are reading the SQL off the
   82730   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   82731   ** So do not write to the disk again.  Extract the root page number
   82732   ** for the table from the db->init.newTnum field.  (The page number
   82733   ** should have been put there by the sqliteOpenCb routine.)
   82734   */
   82735   if( db->init.busy ){
   82736     p->tnum = db->init.newTnum;
   82737   }
   82738 
   82739   /* If not initializing, then create a record for the new table
   82740   ** in the SQLITE_MASTER table of the database.
   82741   **
   82742   ** If this is a TEMPORARY table, write the entry into the auxiliary
   82743   ** file instead of into the main database file.
   82744   */
   82745   if( !db->init.busy ){
   82746     int n;
   82747     Vdbe *v;
   82748     char *zType;    /* "view" or "table" */
   82749     char *zType2;   /* "VIEW" or "TABLE" */
   82750     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   82751 
   82752     v = sqlite3GetVdbe(pParse);
   82753     if( NEVER(v==0) ) return;
   82754 
   82755     sqlite3VdbeAddOp1(v, OP_Close, 0);
   82756 
   82757     /*
   82758     ** Initialize zType for the new view or table.
   82759     */
   82760     if( p->pSelect==0 ){
   82761       /* A regular table */
   82762       zType = "table";
   82763       zType2 = "TABLE";
   82764 #ifndef SQLITE_OMIT_VIEW
   82765     }else{
   82766       /* A view */
   82767       zType = "view";
   82768       zType2 = "VIEW";
   82769 #endif
   82770     }
   82771 
   82772     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   82773     ** statement to populate the new table. The root-page number for the
   82774     ** new table is in register pParse->regRoot.
   82775     **
   82776     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   82777     ** suitable state to query for the column names and types to be used
   82778     ** by the new table.
   82779     **
   82780     ** A shared-cache write-lock is not required to write to the new table,
   82781     ** as a schema-lock must have already been obtained to create it. Since
   82782     ** a schema-lock excludes all other database users, the write-lock would
   82783     ** be redundant.
   82784     */
   82785     if( pSelect ){
   82786       SelectDest dest;
   82787       Table *pSelTab;
   82788 
   82789       assert(pParse->nTab==1);
   82790       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   82791       sqlite3VdbeChangeP5(v, 1);
   82792       pParse->nTab = 2;
   82793       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   82794       sqlite3Select(pParse, pSelect, &dest);
   82795       sqlite3VdbeAddOp1(v, OP_Close, 1);
   82796       if( pParse->nErr==0 ){
   82797         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   82798         if( pSelTab==0 ) return;
   82799         assert( p->aCol==0 );
   82800         p->nCol = pSelTab->nCol;
   82801         p->aCol = pSelTab->aCol;
   82802         pSelTab->nCol = 0;
   82803         pSelTab->aCol = 0;
   82804         sqlite3DeleteTable(db, pSelTab);
   82805       }
   82806     }
   82807 
   82808     /* Compute the complete text of the CREATE statement */
   82809     if( pSelect ){
   82810       zStmt = createTableStmt(db, p);
   82811     }else{
   82812       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
   82813       zStmt = sqlite3MPrintf(db,
   82814           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   82815       );
   82816     }
   82817 
   82818     /* A slot for the record has already been allocated in the
   82819     ** SQLITE_MASTER table.  We just need to update that slot with all
   82820     ** the information we've collected.
   82821     */
   82822     sqlite3NestedParse(pParse,
   82823       "UPDATE %Q.%s "
   82824          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   82825        "WHERE rowid=#%d",
   82826       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   82827       zType,
   82828       p->zName,
   82829       p->zName,
   82830       pParse->regRoot,
   82831       zStmt,
   82832       pParse->regRowid
   82833     );
   82834     sqlite3DbFree(db, zStmt);
   82835     sqlite3ChangeCookie(pParse, iDb);
   82836 
   82837 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82838     /* Check to see if we need to create an sqlite_sequence table for
   82839     ** keeping track of autoincrement keys.
   82840     */
   82841     if( p->tabFlags & TF_Autoincrement ){
   82842       Db *pDb = &db->aDb[iDb];
   82843       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82844       if( pDb->pSchema->pSeqTab==0 ){
   82845         sqlite3NestedParse(pParse,
   82846           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   82847           pDb->zName
   82848         );
   82849       }
   82850     }
   82851 #endif
   82852 
   82853     /* Reparse everything to update our internal data structures */
   82854     sqlite3VdbeAddParseSchemaOp(v, iDb,
   82855                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
   82856   }
   82857 
   82858 
   82859   /* Add the table to the in-memory representation of the database.
   82860   */
   82861   if( db->init.busy ){
   82862     Table *pOld;
   82863     Schema *pSchema = p->pSchema;
   82864     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82865     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   82866                              sqlite3Strlen30(p->zName),p);
   82867     if( pOld ){
   82868       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   82869       db->mallocFailed = 1;
   82870       return;
   82871     }
   82872     pParse->pNewTable = 0;
   82873     db->flags |= SQLITE_InternChanges;
   82874 
   82875 #ifndef SQLITE_OMIT_ALTERTABLE
   82876     if( !p->pSelect ){
   82877       const char *zName = (const char *)pParse->sNameToken.z;
   82878       int nName;
   82879       assert( !pSelect && pCons && pEnd );
   82880       if( pCons->z==0 ){
   82881         pCons = pEnd;
   82882       }
   82883       nName = (int)((const char *)pCons->z - zName);
   82884       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   82885     }
   82886 #endif
   82887   }
   82888 }
   82889 
   82890 #ifndef SQLITE_OMIT_VIEW
   82891 /*
   82892 ** The parser calls this routine in order to create a new VIEW
   82893 */
   82894 SQLITE_PRIVATE void sqlite3CreateView(
   82895   Parse *pParse,     /* The parsing context */
   82896   Token *pBegin,     /* The CREATE token that begins the statement */
   82897   Token *pName1,     /* The token that holds the name of the view */
   82898   Token *pName2,     /* The token that holds the name of the view */
   82899   Select *pSelect,   /* A SELECT statement that will become the new view */
   82900   int isTemp,        /* TRUE for a TEMPORARY view */
   82901   int noErr          /* Suppress error messages if VIEW already exists */
   82902 ){
   82903   Table *p;
   82904   int n;
   82905   const char *z;
   82906   Token sEnd;
   82907   DbFixer sFix;
   82908   Token *pName = 0;
   82909   int iDb;
   82910   sqlite3 *db = pParse->db;
   82911 
   82912   if( pParse->nVar>0 ){
   82913     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   82914     sqlite3SelectDelete(db, pSelect);
   82915     return;
   82916   }
   82917   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   82918   p = pParse->pNewTable;
   82919   if( p==0 || pParse->nErr ){
   82920     sqlite3SelectDelete(db, pSelect);
   82921     return;
   82922   }
   82923   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   82924   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   82925   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
   82926     && sqlite3FixSelect(&sFix, pSelect)
   82927   ){
   82928     sqlite3SelectDelete(db, pSelect);
   82929     return;
   82930   }
   82931 
   82932   /* Make a copy of the entire SELECT statement that defines the view.
   82933   ** This will force all the Expr.token.z values to be dynamically
   82934   ** allocated rather than point to the input string - which means that
   82935   ** they will persist after the current sqlite3_exec() call returns.
   82936   */
   82937   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   82938   sqlite3SelectDelete(db, pSelect);
   82939   if( db->mallocFailed ){
   82940     return;
   82941   }
   82942   if( !db->init.busy ){
   82943     sqlite3ViewGetColumnNames(pParse, p);
   82944   }
   82945 
   82946   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   82947   ** the end.
   82948   */
   82949   sEnd = pParse->sLastToken;
   82950   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   82951     sEnd.z += sEnd.n;
   82952   }
   82953   sEnd.n = 0;
   82954   n = (int)(sEnd.z - pBegin->z);
   82955   z = pBegin->z;
   82956   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   82957   sEnd.z = &z[n-1];
   82958   sEnd.n = 1;
   82959 
   82960   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   82961   sqlite3EndTable(pParse, 0, &sEnd, 0);
   82962   return;
   82963 }
   82964 #endif /* SQLITE_OMIT_VIEW */
   82965 
   82966 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   82967 /*
   82968 ** The Table structure pTable is really a VIEW.  Fill in the names of
   82969 ** the columns of the view in the pTable structure.  Return the number
   82970 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   82971 */
   82972 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   82973   Table *pSelTab;   /* A fake table from which we get the result set */
   82974   Select *pSel;     /* Copy of the SELECT that implements the view */
   82975   int nErr = 0;     /* Number of errors encountered */
   82976   int n;            /* Temporarily holds the number of cursors assigned */
   82977   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   82978   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   82979 
   82980   assert( pTable );
   82981 
   82982 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82983   if( sqlite3VtabCallConnect(pParse, pTable) ){
   82984     return SQLITE_ERROR;
   82985   }
   82986   if( IsVirtual(pTable) ) return 0;
   82987 #endif
   82988 
   82989 #ifndef SQLITE_OMIT_VIEW
   82990   /* A positive nCol means the columns names for this view are
   82991   ** already known.
   82992   */
   82993   if( pTable->nCol>0 ) return 0;
   82994 
   82995   /* A negative nCol is a special marker meaning that we are currently
   82996   ** trying to compute the column names.  If we enter this routine with
   82997   ** a negative nCol, it means two or more views form a loop, like this:
   82998   **
   82999   **     CREATE VIEW one AS SELECT * FROM two;
   83000   **     CREATE VIEW two AS SELECT * FROM one;
   83001   **
   83002   ** Actually, the error above is now caught prior to reaching this point.
   83003   ** But the following test is still important as it does come up
   83004   ** in the following:
   83005   **
   83006   **     CREATE TABLE main.ex1(a);
   83007   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   83008   **     SELECT * FROM temp.ex1;
   83009   */
   83010   if( pTable->nCol<0 ){
   83011     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   83012     return 1;
   83013   }
   83014   assert( pTable->nCol>=0 );
   83015 
   83016   /* If we get this far, it means we need to compute the table names.
   83017   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   83018   ** "*" elements in the results set of the view and will assign cursors
   83019   ** to the elements of the FROM clause.  But we do not want these changes
   83020   ** to be permanent.  So the computation is done on a copy of the SELECT
   83021   ** statement that defines the view.
   83022   */
   83023   assert( pTable->pSelect );
   83024   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   83025   if( pSel ){
   83026     u8 enableLookaside = db->lookaside.bEnabled;
   83027     n = pParse->nTab;
   83028     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   83029     pTable->nCol = -1;
   83030     db->lookaside.bEnabled = 0;
   83031 #ifndef SQLITE_OMIT_AUTHORIZATION
   83032     xAuth = db->xAuth;
   83033     db->xAuth = 0;
   83034     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   83035     db->xAuth = xAuth;
   83036 #else
   83037     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   83038 #endif
   83039     db->lookaside.bEnabled = enableLookaside;
   83040     pParse->nTab = n;
   83041     if( pSelTab ){
   83042       assert( pTable->aCol==0 );
   83043       pTable->nCol = pSelTab->nCol;
   83044       pTable->aCol = pSelTab->aCol;
   83045       pSelTab->nCol = 0;
   83046       pSelTab->aCol = 0;
   83047       sqlite3DeleteTable(db, pSelTab);
   83048       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
   83049       pTable->pSchema->flags |= DB_UnresetViews;
   83050     }else{
   83051       pTable->nCol = 0;
   83052       nErr++;
   83053     }
   83054     sqlite3SelectDelete(db, pSel);
   83055   } else {
   83056     nErr++;
   83057   }
   83058 #endif /* SQLITE_OMIT_VIEW */
   83059   return nErr;
   83060 }
   83061 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   83062 
   83063 #ifndef SQLITE_OMIT_VIEW
   83064 /*
   83065 ** Clear the column names from every VIEW in database idx.
   83066 */
   83067 static void sqliteViewResetAll(sqlite3 *db, int idx){
   83068   HashElem *i;
   83069   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
   83070   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   83071   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   83072     Table *pTab = sqliteHashData(i);
   83073     if( pTab->pSelect ){
   83074       sqliteDeleteColumnNames(db, pTab);
   83075       pTab->aCol = 0;
   83076       pTab->nCol = 0;
   83077     }
   83078   }
   83079   DbClearProperty(db, idx, DB_UnresetViews);
   83080 }
   83081 #else
   83082 # define sqliteViewResetAll(A,B)
   83083 #endif /* SQLITE_OMIT_VIEW */
   83084 
   83085 /*
   83086 ** This function is called by the VDBE to adjust the internal schema
   83087 ** used by SQLite when the btree layer moves a table root page. The
   83088 ** root-page of a table or index in database iDb has changed from iFrom
   83089 ** to iTo.
   83090 **
   83091 ** Ticket #1728:  The symbol table might still contain information
   83092 ** on tables and/or indices that are the process of being deleted.
   83093 ** If you are unlucky, one of those deleted indices or tables might
   83094 ** have the same rootpage number as the real table or index that is
   83095 ** being moved.  So we cannot stop searching after the first match
   83096 ** because the first match might be for one of the deleted indices
   83097 ** or tables and not the table/index that is actually being moved.
   83098 ** We must continue looping until all tables and indices with
   83099 ** rootpage==iFrom have been converted to have a rootpage of iTo
   83100 ** in order to be certain that we got the right one.
   83101 */
   83102 #ifndef SQLITE_OMIT_AUTOVACUUM
   83103 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
   83104   HashElem *pElem;
   83105   Hash *pHash;
   83106   Db *pDb;
   83107 
   83108   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   83109   pDb = &db->aDb[iDb];
   83110   pHash = &pDb->pSchema->tblHash;
   83111   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   83112     Table *pTab = sqliteHashData(pElem);
   83113     if( pTab->tnum==iFrom ){
   83114       pTab->tnum = iTo;
   83115     }
   83116   }
   83117   pHash = &pDb->pSchema->idxHash;
   83118   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   83119     Index *pIdx = sqliteHashData(pElem);
   83120     if( pIdx->tnum==iFrom ){
   83121       pIdx->tnum = iTo;
   83122     }
   83123   }
   83124 }
   83125 #endif
   83126 
   83127 /*
   83128 ** Write code to erase the table with root-page iTable from database iDb.
   83129 ** Also write code to modify the sqlite_master table and internal schema
   83130 ** if a root-page of another table is moved by the btree-layer whilst
   83131 ** erasing iTable (this can happen with an auto-vacuum database).
   83132 */
   83133 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   83134   Vdbe *v = sqlite3GetVdbe(pParse);
   83135   int r1 = sqlite3GetTempReg(pParse);
   83136   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   83137   sqlite3MayAbort(pParse);
   83138 #ifndef SQLITE_OMIT_AUTOVACUUM
   83139   /* OP_Destroy stores an in integer r1. If this integer
   83140   ** is non-zero, then it is the root page number of a table moved to
   83141   ** location iTable. The following code modifies the sqlite_master table to
   83142   ** reflect this.
   83143   **
   83144   ** The "#NNN" in the SQL is a special constant that means whatever value
   83145   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   83146   ** token for additional information.
   83147   */
   83148   sqlite3NestedParse(pParse,
   83149      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   83150      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   83151 #endif
   83152   sqlite3ReleaseTempReg(pParse, r1);
   83153 }
   83154 
   83155 /*
   83156 ** Write VDBE code to erase table pTab and all associated indices on disk.
   83157 ** Code to update the sqlite_master tables and internal schema definitions
   83158 ** in case a root-page belonging to another table is moved by the btree layer
   83159 ** is also added (this can happen with an auto-vacuum database).
   83160 */
   83161 static void destroyTable(Parse *pParse, Table *pTab){
   83162 #ifdef SQLITE_OMIT_AUTOVACUUM
   83163   Index *pIdx;
   83164   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83165   destroyRootPage(pParse, pTab->tnum, iDb);
   83166   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83167     destroyRootPage(pParse, pIdx->tnum, iDb);
   83168   }
   83169 #else
   83170   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   83171   ** is not defined), then it is important to call OP_Destroy on the
   83172   ** table and index root-pages in order, starting with the numerically
   83173   ** largest root-page number. This guarantees that none of the root-pages
   83174   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   83175   ** following were coded:
   83176   **
   83177   ** OP_Destroy 4 0
   83178   ** ...
   83179   ** OP_Destroy 5 0
   83180   **
   83181   ** and root page 5 happened to be the largest root-page number in the
   83182   ** database, then root page 5 would be moved to page 4 by the
   83183   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   83184   ** a free-list page.
   83185   */
   83186   int iTab = pTab->tnum;
   83187   int iDestroyed = 0;
   83188 
   83189   while( 1 ){
   83190     Index *pIdx;
   83191     int iLargest = 0;
   83192 
   83193     if( iDestroyed==0 || iTab<iDestroyed ){
   83194       iLargest = iTab;
   83195     }
   83196     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83197       int iIdx = pIdx->tnum;
   83198       assert( pIdx->pSchema==pTab->pSchema );
   83199       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   83200         iLargest = iIdx;
   83201       }
   83202     }
   83203     if( iLargest==0 ){
   83204       return;
   83205     }else{
   83206       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83207       destroyRootPage(pParse, iLargest, iDb);
   83208       iDestroyed = iLargest;
   83209     }
   83210   }
   83211 #endif
   83212 }
   83213 
   83214 /*
   83215 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
   83216 ** after a DROP INDEX or DROP TABLE command.
   83217 */
   83218 static void sqlite3ClearStatTables(
   83219   Parse *pParse,         /* The parsing context */
   83220   int iDb,               /* The database number */
   83221   const char *zType,     /* "idx" or "tbl" */
   83222   const char *zName      /* Name of index or table */
   83223 ){
   83224   int i;
   83225   const char *zDbName = pParse->db->aDb[iDb].zName;
   83226   for(i=1; i<=3; i++){
   83227     char zTab[24];
   83228     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
   83229     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
   83230       sqlite3NestedParse(pParse,
   83231         "DELETE FROM %Q.%s WHERE %s=%Q",
   83232         zDbName, zTab, zType, zName
   83233       );
   83234     }
   83235   }
   83236 }
   83237 
   83238 /*
   83239 ** Generate code to drop a table.
   83240 */
   83241 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
   83242   Vdbe *v;
   83243   sqlite3 *db = pParse->db;
   83244   Trigger *pTrigger;
   83245   Db *pDb = &db->aDb[iDb];
   83246 
   83247   v = sqlite3GetVdbe(pParse);
   83248   assert( v!=0 );
   83249   sqlite3BeginWriteOperation(pParse, 1, iDb);
   83250 
   83251 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83252   if( IsVirtual(pTab) ){
   83253     sqlite3VdbeAddOp0(v, OP_VBegin);
   83254   }
   83255 #endif
   83256 
   83257   /* Drop all triggers associated with the table being dropped. Code
   83258   ** is generated to remove entries from sqlite_master and/or
   83259   ** sqlite_temp_master if required.
   83260   */
   83261   pTrigger = sqlite3TriggerList(pParse, pTab);
   83262   while( pTrigger ){
   83263     assert( pTrigger->pSchema==pTab->pSchema ||
   83264         pTrigger->pSchema==db->aDb[1].pSchema );
   83265     sqlite3DropTriggerPtr(pParse, pTrigger);
   83266     pTrigger = pTrigger->pNext;
   83267   }
   83268 
   83269 #ifndef SQLITE_OMIT_AUTOINCREMENT
   83270   /* Remove any entries of the sqlite_sequence table associated with
   83271   ** the table being dropped. This is done before the table is dropped
   83272   ** at the btree level, in case the sqlite_sequence table needs to
   83273   ** move as a result of the drop (can happen in auto-vacuum mode).
   83274   */
   83275   if( pTab->tabFlags & TF_Autoincrement ){
   83276     sqlite3NestedParse(pParse,
   83277       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
   83278       pDb->zName, pTab->zName
   83279     );
   83280   }
   83281 #endif
   83282 
   83283   /* Drop all SQLITE_MASTER table and index entries that refer to the
   83284   ** table. The program name loops through the master table and deletes
   83285   ** every row that refers to a table of the same name as the one being
   83286   ** dropped. Triggers are handled seperately because a trigger can be
   83287   ** created in the temp database that refers to a table in another
   83288   ** database.
   83289   */
   83290   sqlite3NestedParse(pParse,
   83291       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   83292       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   83293   if( !isView && !IsVirtual(pTab) ){
   83294     destroyTable(pParse, pTab);
   83295   }
   83296 
   83297   /* Remove the table entry from SQLite's internal schema and modify
   83298   ** the schema cookie.
   83299   */
   83300   if( IsVirtual(pTab) ){
   83301     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   83302   }
   83303   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   83304   sqlite3ChangeCookie(pParse, iDb);
   83305   sqliteViewResetAll(db, iDb);
   83306 }
   83307 
   83308 /*
   83309 ** This routine is called to do the work of a DROP TABLE statement.
   83310 ** pName is the name of the table to be dropped.
   83311 */
   83312 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   83313   Table *pTab;
   83314   Vdbe *v;
   83315   sqlite3 *db = pParse->db;
   83316   int iDb;
   83317 
   83318   if( db->mallocFailed ){
   83319     goto exit_drop_table;
   83320   }
   83321   assert( pParse->nErr==0 );
   83322   assert( pName->nSrc==1 );
   83323   if( noErr ) db->suppressErr++;
   83324   pTab = sqlite3LocateTable(pParse, isView,
   83325                             pName->a[0].zName, pName->a[0].zDatabase);
   83326   if( noErr ) db->suppressErr--;
   83327 
   83328   if( pTab==0 ){
   83329     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   83330     goto exit_drop_table;
   83331   }
   83332   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83333   assert( iDb>=0 && iDb<db->nDb );
   83334 
   83335   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   83336   ** it is initialized.
   83337   */
   83338   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   83339     goto exit_drop_table;
   83340   }
   83341 #ifndef SQLITE_OMIT_AUTHORIZATION
   83342   {
   83343     int code;
   83344     const char *zTab = SCHEMA_TABLE(iDb);
   83345     const char *zDb = db->aDb[iDb].zName;
   83346     const char *zArg2 = 0;
   83347     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   83348       goto exit_drop_table;
   83349     }
   83350     if( isView ){
   83351       if( !OMIT_TEMPDB && iDb==1 ){
   83352         code = SQLITE_DROP_TEMP_VIEW;
   83353       }else{
   83354         code = SQLITE_DROP_VIEW;
   83355       }
   83356 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83357     }else if( IsVirtual(pTab) ){
   83358       code = SQLITE_DROP_VTABLE;
   83359       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   83360 #endif
   83361     }else{
   83362       if( !OMIT_TEMPDB && iDb==1 ){
   83363         code = SQLITE_DROP_TEMP_TABLE;
   83364       }else{
   83365         code = SQLITE_DROP_TABLE;
   83366       }
   83367     }
   83368     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   83369       goto exit_drop_table;
   83370     }
   83371     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   83372       goto exit_drop_table;
   83373     }
   83374   }
   83375 #endif
   83376   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   83377     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
   83378     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   83379     goto exit_drop_table;
   83380   }
   83381 
   83382 #ifndef SQLITE_OMIT_VIEW
   83383   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   83384   ** on a table.
   83385   */
   83386   if( isView && pTab->pSelect==0 ){
   83387     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   83388     goto exit_drop_table;
   83389   }
   83390   if( !isView && pTab->pSelect ){
   83391     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   83392     goto exit_drop_table;
   83393   }
   83394 #endif
   83395 
   83396   /* Generate code to remove the table from the master table
   83397   ** on disk.
   83398   */
   83399   v = sqlite3GetVdbe(pParse);
   83400   if( v ){
   83401     sqlite3BeginWriteOperation(pParse, 1, iDb);
   83402     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
   83403     sqlite3FkDropTable(pParse, pName, pTab);
   83404     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
   83405   }
   83406 
   83407 exit_drop_table:
   83408   sqlite3SrcListDelete(db, pName);
   83409 }
   83410 
   83411 /*
   83412 ** This routine is called to create a new foreign key on the table
   83413 ** currently under construction.  pFromCol determines which columns
   83414 ** in the current table point to the foreign key.  If pFromCol==0 then
   83415 ** connect the key to the last column inserted.  pTo is the name of
   83416 ** the table referred to.  pToCol is a list of tables in the other
   83417 ** pTo table that the foreign key points to.  flags contains all
   83418 ** information about the conflict resolution algorithms specified
   83419 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   83420 **
   83421 ** An FKey structure is created and added to the table currently
   83422 ** under construction in the pParse->pNewTable field.
   83423 **
   83424 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   83425 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   83426 */
   83427 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   83428   Parse *pParse,       /* Parsing context */
   83429   ExprList *pFromCol,  /* Columns in this table that point to other table */
   83430   Token *pTo,          /* Name of the other table */
   83431   ExprList *pToCol,    /* Columns in the other table */
   83432   int flags            /* Conflict resolution algorithms. */
   83433 ){
   83434   sqlite3 *db = pParse->db;
   83435 #ifndef SQLITE_OMIT_FOREIGN_KEY
   83436   FKey *pFKey = 0;
   83437   FKey *pNextTo;
   83438   Table *p = pParse->pNewTable;
   83439   int nByte;
   83440   int i;
   83441   int nCol;
   83442   char *z;
   83443 
   83444   assert( pTo!=0 );
   83445   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   83446   if( pFromCol==0 ){
   83447     int iCol = p->nCol-1;
   83448     if( NEVER(iCol<0) ) goto fk_end;
   83449     if( pToCol && pToCol->nExpr!=1 ){
   83450       sqlite3ErrorMsg(pParse, "foreign key on %s"
   83451          " should reference only one column of table %T",
   83452          p->aCol[iCol].zName, pTo);
   83453       goto fk_end;
   83454     }
   83455     nCol = 1;
   83456   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   83457     sqlite3ErrorMsg(pParse,
   83458         "number of columns in foreign key does not match the number of "
   83459         "columns in the referenced table");
   83460     goto fk_end;
   83461   }else{
   83462     nCol = pFromCol->nExpr;
   83463   }
   83464   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   83465   if( pToCol ){
   83466     for(i=0; i<pToCol->nExpr; i++){
   83467       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   83468     }
   83469   }
   83470   pFKey = sqlite3DbMallocZero(db, nByte );
   83471   if( pFKey==0 ){
   83472     goto fk_end;
   83473   }
   83474   pFKey->pFrom = p;
   83475   pFKey->pNextFrom = p->pFKey;
   83476   z = (char*)&pFKey->aCol[nCol];
   83477   pFKey->zTo = z;
   83478   memcpy(z, pTo->z, pTo->n);
   83479   z[pTo->n] = 0;
   83480   sqlite3Dequote(z);
   83481   z += pTo->n+1;
   83482   pFKey->nCol = nCol;
   83483   if( pFromCol==0 ){
   83484     pFKey->aCol[0].iFrom = p->nCol-1;
   83485   }else{
   83486     for(i=0; i<nCol; i++){
   83487       int j;
   83488       for(j=0; j<p->nCol; j++){
   83489         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   83490           pFKey->aCol[i].iFrom = j;
   83491           break;
   83492         }
   83493       }
   83494       if( j>=p->nCol ){
   83495         sqlite3ErrorMsg(pParse,
   83496           "unknown column \"%s\" in foreign key definition",
   83497           pFromCol->a[i].zName);
   83498         goto fk_end;
   83499       }
   83500     }
   83501   }
   83502   if( pToCol ){
   83503     for(i=0; i<nCol; i++){
   83504       int n = sqlite3Strlen30(pToCol->a[i].zName);
   83505       pFKey->aCol[i].zCol = z;
   83506       memcpy(z, pToCol->a[i].zName, n);
   83507       z[n] = 0;
   83508       z += n+1;
   83509     }
   83510   }
   83511   pFKey->isDeferred = 0;
   83512   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   83513   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   83514 
   83515   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   83516   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   83517       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   83518   );
   83519   if( pNextTo==pFKey ){
   83520     db->mallocFailed = 1;
   83521     goto fk_end;
   83522   }
   83523   if( pNextTo ){
   83524     assert( pNextTo->pPrevTo==0 );
   83525     pFKey->pNextTo = pNextTo;
   83526     pNextTo->pPrevTo = pFKey;
   83527   }
   83528 
   83529   /* Link the foreign key to the table as the last step.
   83530   */
   83531   p->pFKey = pFKey;
   83532   pFKey = 0;
   83533 
   83534 fk_end:
   83535   sqlite3DbFree(db, pFKey);
   83536 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   83537   sqlite3ExprListDelete(db, pFromCol);
   83538   sqlite3ExprListDelete(db, pToCol);
   83539 }
   83540 
   83541 /*
   83542 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   83543 ** clause is seen as part of a foreign key definition.  The isDeferred
   83544 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   83545 ** The behavior of the most recently created foreign key is adjusted
   83546 ** accordingly.
   83547 */
   83548 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   83549 #ifndef SQLITE_OMIT_FOREIGN_KEY
   83550   Table *pTab;
   83551   FKey *pFKey;
   83552   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   83553   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   83554   pFKey->isDeferred = (u8)isDeferred;
   83555 #endif
   83556 }
   83557 
   83558 /*
   83559 ** Generate code that will erase and refill index *pIdx.  This is
   83560 ** used to initialize a newly created index or to recompute the
   83561 ** content of an index in response to a REINDEX command.
   83562 **
   83563 ** if memRootPage is not negative, it means that the index is newly
   83564 ** created.  The register specified by memRootPage contains the
   83565 ** root page number of the index.  If memRootPage is negative, then
   83566 ** the index already exists and must be cleared before being refilled and
   83567 ** the root page number of the index is taken from pIndex->tnum.
   83568 */
   83569 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   83570   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   83571   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   83572   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   83573   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   83574   int addr1;                     /* Address of top of loop */
   83575   int addr2;                     /* Address to jump to for next iteration */
   83576   int tnum;                      /* Root page of index */
   83577   Vdbe *v;                       /* Generate code into this virtual machine */
   83578   KeyInfo *pKey;                 /* KeyInfo for index */
   83579 #ifdef SQLITE_OMIT_MERGE_SORT
   83580   int regIdxKey;                 /* Registers containing the index key */
   83581 #endif
   83582   int regRecord;                 /* Register holding assemblied index record */
   83583   sqlite3 *db = pParse->db;      /* The database connection */
   83584   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   83585 
   83586 #ifndef SQLITE_OMIT_AUTHORIZATION
   83587   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   83588       db->aDb[iDb].zName ) ){
   83589     return;
   83590   }
   83591 #endif
   83592 
   83593   /* Require a write-lock on the table to perform this operation */
   83594   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   83595 
   83596   v = sqlite3GetVdbe(pParse);
   83597   if( v==0 ) return;
   83598   if( memRootPage>=0 ){
   83599     tnum = memRootPage;
   83600   }else{
   83601     tnum = pIndex->tnum;
   83602     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   83603   }
   83604   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
   83605   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   83606                     (char *)pKey, P4_KEYINFO_HANDOFF);
   83607   if( memRootPage>=0 ){
   83608     sqlite3VdbeChangeP5(v, 1);
   83609   }
   83610 
   83611 #ifndef SQLITE_OMIT_MERGE_SORT
   83612   /* Open the sorter cursor if we are to use one. */
   83613   iSorter = pParse->nTab++;
   83614   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
   83615 #else
   83616   iSorter = iTab;
   83617 #endif
   83618 
   83619   /* Open the table. Loop through all rows of the table, inserting index
   83620   ** records into the sorter. */
   83621   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   83622   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   83623   regRecord = sqlite3GetTempReg(pParse);
   83624 
   83625 #ifndef SQLITE_OMIT_MERGE_SORT
   83626   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   83627   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
   83628   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
   83629   sqlite3VdbeJumpHere(v, addr1);
   83630   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
   83631   if( pIndex->onError!=OE_None ){
   83632     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
   83633     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
   83634     addr2 = sqlite3VdbeCurrentAddr(v);
   83635     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
   83636     sqlite3HaltConstraint(
   83637         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
   83638     );
   83639   }else{
   83640     addr2 = sqlite3VdbeCurrentAddr(v);
   83641   }
   83642   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
   83643   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
   83644   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   83645 #else
   83646   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   83647   addr2 = addr1 + 1;
   83648   if( pIndex->onError!=OE_None ){
   83649     const int regRowid = regIdxKey + pIndex->nColumn;
   83650     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
   83651     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
   83652 
   83653     /* The registers accessed by the OP_IsUnique opcode were allocated
   83654     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
   83655     ** call above. Just before that function was freed they were released
   83656     ** (made available to the compiler for reuse) using
   83657     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
   83658     ** opcode use the values stored within seems dangerous. However, since
   83659     ** we can be sure that no other temp registers have been allocated
   83660     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
   83661     */
   83662     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
   83663     sqlite3HaltConstraint(
   83664         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
   83665   }
   83666   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
   83667   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   83668 #endif
   83669   sqlite3ReleaseTempReg(pParse, regRecord);
   83670   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
   83671   sqlite3VdbeJumpHere(v, addr1);
   83672 
   83673   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   83674   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   83675   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
   83676 }
   83677 
   83678 /*
   83679 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   83680 ** and pTblList is the name of the table that is to be indexed.  Both will
   83681 ** be NULL for a primary key or an index that is created to satisfy a
   83682 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   83683 ** as the table to be indexed.  pParse->pNewTable is a table that is
   83684 ** currently being constructed by a CREATE TABLE statement.
   83685 **
   83686 ** pList is a list of columns to be indexed.  pList will be NULL if this
   83687 ** is a primary key or unique-constraint on the most recent column added
   83688 ** to the table currently under construction.
   83689 **
   83690 ** If the index is created successfully, return a pointer to the new Index
   83691 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   83692 ** as the tables primary key (Index.autoIndex==2).
   83693 */
   83694 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   83695   Parse *pParse,     /* All information about this parse */
   83696   Token *pName1,     /* First part of index name. May be NULL */
   83697   Token *pName2,     /* Second part of index name. May be NULL */
   83698   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   83699   ExprList *pList,   /* A list of columns to be indexed */
   83700   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   83701   Token *pStart,     /* The CREATE token that begins this statement */
   83702   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
   83703   int sortOrder,     /* Sort order of primary key when pList==NULL */
   83704   int ifNotExist     /* Omit error if index already exists */
   83705 ){
   83706   Index *pRet = 0;     /* Pointer to return */
   83707   Table *pTab = 0;     /* Table to be indexed */
   83708   Index *pIndex = 0;   /* The index to be created */
   83709   char *zName = 0;     /* Name of the index */
   83710   int nName;           /* Number of characters in zName */
   83711   int i, j;
   83712   Token nullId;        /* Fake token for an empty ID list */
   83713   DbFixer sFix;        /* For assigning database names to pTable */
   83714   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   83715   sqlite3 *db = pParse->db;
   83716   Db *pDb;             /* The specific table containing the indexed database */
   83717   int iDb;             /* Index of the database that is being written */
   83718   Token *pName = 0;    /* Unqualified name of the index to create */
   83719   struct ExprList_item *pListItem; /* For looping over pList */
   83720   int nCol;
   83721   int nExtra = 0;
   83722   char *zExtra;
   83723 
   83724   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
   83725   assert( pParse->nErr==0 );      /* Never called with prior errors */
   83726   if( db->mallocFailed || IN_DECLARE_VTAB ){
   83727     goto exit_create_index;
   83728   }
   83729   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   83730     goto exit_create_index;
   83731   }
   83732 
   83733   /*
   83734   ** Find the table that is to be indexed.  Return early if not found.
   83735   */
   83736   if( pTblName!=0 ){
   83737 
   83738     /* Use the two-part index name to determine the database
   83739     ** to search for the table. 'Fix' the table name to this db
   83740     ** before looking up the table.
   83741     */
   83742     assert( pName1 && pName2 );
   83743     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   83744     if( iDb<0 ) goto exit_create_index;
   83745     assert( pName && pName->z );
   83746 
   83747 #ifndef SQLITE_OMIT_TEMPDB
   83748     /* If the index name was unqualified, check if the the table
   83749     ** is a temp table. If so, set the database to 1. Do not do this
   83750     ** if initialising a database schema.
   83751     */
   83752     if( !db->init.busy ){
   83753       pTab = sqlite3SrcListLookup(pParse, pTblName);
   83754       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   83755         iDb = 1;
   83756       }
   83757     }
   83758 #endif
   83759 
   83760     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
   83761         sqlite3FixSrcList(&sFix, pTblName)
   83762     ){
   83763       /* Because the parser constructs pTblName from a single identifier,
   83764       ** sqlite3FixSrcList can never fail. */
   83765       assert(0);
   83766     }
   83767     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
   83768         pTblName->a[0].zDatabase);
   83769     if( !pTab || db->mallocFailed ) goto exit_create_index;
   83770     assert( db->aDb[iDb].pSchema==pTab->pSchema );
   83771   }else{
   83772     assert( pName==0 );
   83773     assert( pStart==0 );
   83774     pTab = pParse->pNewTable;
   83775     if( !pTab ) goto exit_create_index;
   83776     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83777   }
   83778   pDb = &db->aDb[iDb];
   83779 
   83780   assert( pTab!=0 );
   83781   assert( pParse->nErr==0 );
   83782   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   83783        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
   83784     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   83785     goto exit_create_index;
   83786   }
   83787 #ifndef SQLITE_OMIT_VIEW
   83788   if( pTab->pSelect ){
   83789     sqlite3ErrorMsg(pParse, "views may not be indexed");
   83790     goto exit_create_index;
   83791   }
   83792 #endif
   83793 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83794   if( IsVirtual(pTab) ){
   83795     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   83796     goto exit_create_index;
   83797   }
   83798 #endif
   83799 
   83800   /*
   83801   ** Find the name of the index.  Make sure there is not already another
   83802   ** index or table with the same name.
   83803   **
   83804   ** Exception:  If we are reading the names of permanent indices from the
   83805   ** sqlite_master table (because some other process changed the schema) and
   83806   ** one of the index names collides with the name of a temporary table or
   83807   ** index, then we will continue to process this index.
   83808   **
   83809   ** If pName==0 it means that we are
   83810   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   83811   ** own name.
   83812   */
   83813   if( pName ){
   83814     zName = sqlite3NameFromToken(db, pName);
   83815     if( zName==0 ) goto exit_create_index;
   83816     assert( pName->z!=0 );
   83817     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   83818       goto exit_create_index;
   83819     }
   83820     if( !db->init.busy ){
   83821       if( sqlite3FindTable(db, zName, 0)!=0 ){
   83822         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   83823         goto exit_create_index;
   83824       }
   83825     }
   83826     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   83827       if( !ifNotExist ){
   83828         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   83829       }else{
   83830         assert( !db->init.busy );
   83831         sqlite3CodeVerifySchema(pParse, iDb);
   83832       }
   83833       goto exit_create_index;
   83834     }
   83835   }else{
   83836     int n;
   83837     Index *pLoop;
   83838     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   83839     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   83840     if( zName==0 ){
   83841       goto exit_create_index;
   83842     }
   83843   }
   83844 
   83845   /* Check for authorization to create an index.
   83846   */
   83847 #ifndef SQLITE_OMIT_AUTHORIZATION
   83848   {
   83849     const char *zDb = pDb->zName;
   83850     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   83851       goto exit_create_index;
   83852     }
   83853     i = SQLITE_CREATE_INDEX;
   83854     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   83855     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   83856       goto exit_create_index;
   83857     }
   83858   }
   83859 #endif
   83860 
   83861   /* If pList==0, it means this routine was called to make a primary
   83862   ** key out of the last column added to the table under construction.
   83863   ** So create a fake list to simulate this.
   83864   */
   83865   if( pList==0 ){
   83866     nullId.z = pTab->aCol[pTab->nCol-1].zName;
   83867     nullId.n = sqlite3Strlen30((char*)nullId.z);
   83868     pList = sqlite3ExprListAppend(pParse, 0, 0);
   83869     if( pList==0 ) goto exit_create_index;
   83870     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
   83871     pList->a[0].sortOrder = (u8)sortOrder;
   83872   }
   83873 
   83874   /* Figure out how many bytes of space are required to store explicitly
   83875   ** specified collation sequence names.
   83876   */
   83877   for(i=0; i<pList->nExpr; i++){
   83878     Expr *pExpr = pList->a[i].pExpr;
   83879     if( pExpr ){
   83880       CollSeq *pColl = pExpr->pColl;
   83881       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
   83882       ** failure we have quit before reaching this point. */
   83883       if( ALWAYS(pColl) ){
   83884         nExtra += (1 + sqlite3Strlen30(pColl->zName));
   83885       }
   83886     }
   83887   }
   83888 
   83889   /*
   83890   ** Allocate the index structure.
   83891   */
   83892   nName = sqlite3Strlen30(zName);
   83893   nCol = pList->nExpr;
   83894   pIndex = sqlite3DbMallocZero(db,
   83895       ROUND8(sizeof(Index)) +              /* Index structure  */
   83896       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
   83897       sizeof(char *)*nCol +                /* Index.azColl     */
   83898       sizeof(int)*nCol +                   /* Index.aiColumn   */
   83899       sizeof(u8)*nCol +                    /* Index.aSortOrder */
   83900       nName + 1 +                          /* Index.zName      */
   83901       nExtra                               /* Collation sequence names */
   83902   );
   83903   if( db->mallocFailed ){
   83904     goto exit_create_index;
   83905   }
   83906   zExtra = (char*)pIndex;
   83907   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
   83908   pIndex->azColl = (char**)
   83909      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
   83910   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
   83911   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
   83912   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
   83913   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
   83914   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
   83915   zExtra = (char *)(&pIndex->zName[nName+1]);
   83916   memcpy(pIndex->zName, zName, nName+1);
   83917   pIndex->pTable = pTab;
   83918   pIndex->nColumn = pList->nExpr;
   83919   pIndex->onError = (u8)onError;
   83920   pIndex->autoIndex = (u8)(pName==0);
   83921   pIndex->pSchema = db->aDb[iDb].pSchema;
   83922   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   83923 
   83924   /* Check to see if we should honor DESC requests on index columns
   83925   */
   83926   if( pDb->pSchema->file_format>=4 ){
   83927     sortOrderMask = -1;   /* Honor DESC */
   83928   }else{
   83929     sortOrderMask = 0;    /* Ignore DESC */
   83930   }
   83931 
   83932   /* Scan the names of the columns of the table to be indexed and
   83933   ** load the column indices into the Index structure.  Report an error
   83934   ** if any column is not found.
   83935   **
   83936   ** TODO:  Add a test to make sure that the same column is not named
   83937   ** more than once within the same index.  Only the first instance of
   83938   ** the column will ever be used by the optimizer.  Note that using the
   83939   ** same column more than once cannot be an error because that would
   83940   ** break backwards compatibility - it needs to be a warning.
   83941   */
   83942   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   83943     const char *zColName = pListItem->zName;
   83944     Column *pTabCol;
   83945     int requestedSortOrder;
   83946     char *zColl;                   /* Collation sequence name */
   83947 
   83948     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   83949       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   83950     }
   83951     if( j>=pTab->nCol ){
   83952       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   83953         pTab->zName, zColName);
   83954       pParse->checkSchema = 1;
   83955       goto exit_create_index;
   83956     }
   83957     pIndex->aiColumn[i] = j;
   83958     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
   83959     ** the way the "idxlist" non-terminal is constructed by the parser,
   83960     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
   83961     ** must exist or else there must have been an OOM error.  But if there
   83962     ** was an OOM error, we would never reach this point. */
   83963     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
   83964       int nColl;
   83965       zColl = pListItem->pExpr->pColl->zName;
   83966       nColl = sqlite3Strlen30(zColl) + 1;
   83967       assert( nExtra>=nColl );
   83968       memcpy(zExtra, zColl, nColl);
   83969       zColl = zExtra;
   83970       zExtra += nColl;
   83971       nExtra -= nColl;
   83972     }else{
   83973       zColl = pTab->aCol[j].zColl;
   83974       if( !zColl ){
   83975         zColl = db->pDfltColl->zName;
   83976       }
   83977     }
   83978     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   83979       goto exit_create_index;
   83980     }
   83981     pIndex->azColl[i] = zColl;
   83982     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   83983     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   83984   }
   83985   sqlite3DefaultRowEst(pIndex);
   83986 
   83987   if( pTab==pParse->pNewTable ){
   83988     /* This routine has been called to create an automatic index as a
   83989     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   83990     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   83991     ** i.e. one of:
   83992     **
   83993     ** CREATE TABLE t(x PRIMARY KEY, y);
   83994     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   83995     **
   83996     ** Either way, check to see if the table already has such an index. If
   83997     ** so, don't bother creating this one. This only applies to
   83998     ** automatically created indices. Users can do as they wish with
   83999     ** explicit indices.
   84000     **
   84001     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   84002     ** (and thus suppressing the second one) even if they have different
   84003     ** sort orders.
   84004     **
   84005     ** If there are different collating sequences or if the columns of
   84006     ** the constraint occur in different orders, then the constraints are
   84007     ** considered distinct and both result in separate indices.
   84008     */
   84009     Index *pIdx;
   84010     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   84011       int k;
   84012       assert( pIdx->onError!=OE_None );
   84013       assert( pIdx->autoIndex );
   84014       assert( pIndex->onError!=OE_None );
   84015 
   84016       if( pIdx->nColumn!=pIndex->nColumn ) continue;
   84017       for(k=0; k<pIdx->nColumn; k++){
   84018         const char *z1;
   84019         const char *z2;
   84020         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   84021         z1 = pIdx->azColl[k];
   84022         z2 = pIndex->azColl[k];
   84023         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   84024       }
   84025       if( k==pIdx->nColumn ){
   84026         if( pIdx->onError!=pIndex->onError ){
   84027           /* This constraint creates the same index as a previous
   84028           ** constraint specified somewhere in the CREATE TABLE statement.
   84029           ** However the ON CONFLICT clauses are different. If both this
   84030           ** constraint and the previous equivalent constraint have explicit
   84031           ** ON CONFLICT clauses this is an error. Otherwise, use the
   84032           ** explicitly specified behaviour for the index.
   84033           */
   84034           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   84035             sqlite3ErrorMsg(pParse,
   84036                 "conflicting ON CONFLICT clauses specified", 0);
   84037           }
   84038           if( pIdx->onError==OE_Default ){
   84039             pIdx->onError = pIndex->onError;
   84040           }
   84041         }
   84042         goto exit_create_index;
   84043       }
   84044     }
   84045   }
   84046 
   84047   /* Link the new Index structure to its table and to the other
   84048   ** in-memory database structures.
   84049   */
   84050   if( db->init.busy ){
   84051     Index *p;
   84052     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   84053     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   84054                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   84055                           pIndex);
   84056     if( p ){
   84057       assert( p==pIndex );  /* Malloc must have failed */
   84058       db->mallocFailed = 1;
   84059       goto exit_create_index;
   84060     }
   84061     db->flags |= SQLITE_InternChanges;
   84062     if( pTblName!=0 ){
   84063       pIndex->tnum = db->init.newTnum;
   84064     }
   84065   }
   84066 
   84067   /* If the db->init.busy is 0 then create the index on disk.  This
   84068   ** involves writing the index into the master table and filling in the
   84069   ** index with the current table contents.
   84070   **
   84071   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
   84072   ** command.  db->init.busy is 1 when a database is opened and
   84073   ** CREATE INDEX statements are read out of the master table.  In
   84074   ** the latter case the index already exists on disk, which is why
   84075   ** we don't want to recreate it.
   84076   **
   84077   ** If pTblName==0 it means this index is generated as a primary key
   84078   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
   84079   ** has just been created, it contains no data and the index initialization
   84080   ** step can be skipped.
   84081   */
   84082   else{ /* if( db->init.busy==0 ) */
   84083     Vdbe *v;
   84084     char *zStmt;
   84085     int iMem = ++pParse->nMem;
   84086 
   84087     v = sqlite3GetVdbe(pParse);
   84088     if( v==0 ) goto exit_create_index;
   84089 
   84090 
   84091     /* Create the rootpage for the index
   84092     */
   84093     sqlite3BeginWriteOperation(pParse, 1, iDb);
   84094     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   84095 
   84096     /* Gather the complete text of the CREATE INDEX statement into
   84097     ** the zStmt variable
   84098     */
   84099     if( pStart ){
   84100       assert( pEnd!=0 );
   84101       /* A named index with an explicit CREATE INDEX statement */
   84102       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   84103         onError==OE_None ? "" : " UNIQUE",
   84104         (int)(pEnd->z - pName->z) + 1,
   84105         pName->z);
   84106     }else{
   84107       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   84108       /* zStmt = sqlite3MPrintf(""); */
   84109       zStmt = 0;
   84110     }
   84111 
   84112     /* Add an entry in sqlite_master for this index
   84113     */
   84114     sqlite3NestedParse(pParse,
   84115         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   84116         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   84117         pIndex->zName,
   84118         pTab->zName,
   84119         iMem,
   84120         zStmt
   84121     );
   84122     sqlite3DbFree(db, zStmt);
   84123 
   84124     /* Fill the index with data and reparse the schema. Code an OP_Expire
   84125     ** to invalidate all pre-compiled statements.
   84126     */
   84127     if( pTblName ){
   84128       sqlite3RefillIndex(pParse, pIndex, iMem);
   84129       sqlite3ChangeCookie(pParse, iDb);
   84130       sqlite3VdbeAddParseSchemaOp(v, iDb,
   84131          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
   84132       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   84133     }
   84134   }
   84135 
   84136   /* When adding an index to the list of indices for a table, make
   84137   ** sure all indices labeled OE_Replace come after all those labeled
   84138   ** OE_Ignore.  This is necessary for the correct constraint check
   84139   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   84140   ** UPDATE and INSERT statements.
   84141   */
   84142   if( db->init.busy || pTblName==0 ){
   84143     if( onError!=OE_Replace || pTab->pIndex==0
   84144          || pTab->pIndex->onError==OE_Replace){
   84145       pIndex->pNext = pTab->pIndex;
   84146       pTab->pIndex = pIndex;
   84147     }else{
   84148       Index *pOther = pTab->pIndex;
   84149       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   84150         pOther = pOther->pNext;
   84151       }
   84152       pIndex->pNext = pOther->pNext;
   84153       pOther->pNext = pIndex;
   84154     }
   84155     pRet = pIndex;
   84156     pIndex = 0;
   84157   }
   84158 
   84159   /* Clean up before exiting */
   84160 exit_create_index:
   84161   if( pIndex ){
   84162     sqlite3DbFree(db, pIndex->zColAff);
   84163     sqlite3DbFree(db, pIndex);
   84164   }
   84165   sqlite3ExprListDelete(db, pList);
   84166   sqlite3SrcListDelete(db, pTblName);
   84167   sqlite3DbFree(db, zName);
   84168   return pRet;
   84169 }
   84170 
   84171 /*
   84172 ** Fill the Index.aiRowEst[] array with default information - information
   84173 ** to be used when we have not run the ANALYZE command.
   84174 **
   84175 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   84176 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   84177 ** number of rows in the table that match any particular value of the
   84178 ** first column of the index.  aiRowEst[2] is an estimate of the number
   84179 ** of rows that match any particular combiniation of the first 2 columns
   84180 ** of the index.  And so forth.  It must always be the case that
   84181 *
   84182 **           aiRowEst[N]<=aiRowEst[N-1]
   84183 **           aiRowEst[N]>=1
   84184 **
   84185 ** Apart from that, we have little to go on besides intuition as to
   84186 ** how aiRowEst[] should be initialized.  The numbers generated here
   84187 ** are based on typical values found in actual indices.
   84188 */
   84189 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   84190   tRowcnt *a = pIdx->aiRowEst;
   84191   int i;
   84192   tRowcnt n;
   84193   assert( a!=0 );
   84194   a[0] = pIdx->pTable->nRowEst;
   84195   if( a[0]<10 ) a[0] = 10;
   84196   n = 10;
   84197   for(i=1; i<=pIdx->nColumn; i++){
   84198     a[i] = n;
   84199     if( n>5 ) n--;
   84200   }
   84201   if( pIdx->onError!=OE_None ){
   84202     a[pIdx->nColumn] = 1;
   84203   }
   84204 }
   84205 
   84206 /*
   84207 ** This routine will drop an existing named index.  This routine
   84208 ** implements the DROP INDEX statement.
   84209 */
   84210 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   84211   Index *pIndex;
   84212   Vdbe *v;
   84213   sqlite3 *db = pParse->db;
   84214   int iDb;
   84215 
   84216   assert( pParse->nErr==0 );   /* Never called with prior errors */
   84217   if( db->mallocFailed ){
   84218     goto exit_drop_index;
   84219   }
   84220   assert( pName->nSrc==1 );
   84221   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84222     goto exit_drop_index;
   84223   }
   84224   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   84225   if( pIndex==0 ){
   84226     if( !ifExists ){
   84227       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   84228     }else{
   84229       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   84230     }
   84231     pParse->checkSchema = 1;
   84232     goto exit_drop_index;
   84233   }
   84234   if( pIndex->autoIndex ){
   84235     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   84236       "or PRIMARY KEY constraint cannot be dropped", 0);
   84237     goto exit_drop_index;
   84238   }
   84239   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   84240 #ifndef SQLITE_OMIT_AUTHORIZATION
   84241   {
   84242     int code = SQLITE_DROP_INDEX;
   84243     Table *pTab = pIndex->pTable;
   84244     const char *zDb = db->aDb[iDb].zName;
   84245     const char *zTab = SCHEMA_TABLE(iDb);
   84246     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   84247       goto exit_drop_index;
   84248     }
   84249     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   84250     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   84251       goto exit_drop_index;
   84252     }
   84253   }
   84254 #endif
   84255 
   84256   /* Generate code to remove the index and from the master table */
   84257   v = sqlite3GetVdbe(pParse);
   84258   if( v ){
   84259     sqlite3BeginWriteOperation(pParse, 1, iDb);
   84260     sqlite3NestedParse(pParse,
   84261        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   84262        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
   84263     );
   84264     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
   84265     sqlite3ChangeCookie(pParse, iDb);
   84266     destroyRootPage(pParse, pIndex->tnum, iDb);
   84267     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   84268   }
   84269 
   84270 exit_drop_index:
   84271   sqlite3SrcListDelete(db, pName);
   84272 }
   84273 
   84274 /*
   84275 ** pArray is a pointer to an array of objects.  Each object in the
   84276 ** array is szEntry bytes in size.  This routine allocates a new
   84277 ** object on the end of the array.
   84278 **
   84279 ** *pnEntry is the number of entries already in use.  *pnAlloc is
   84280 ** the previously allocated size of the array.  initSize is the
   84281 ** suggested initial array size allocation.
   84282 **
   84283 ** The index of the new entry is returned in *pIdx.
   84284 **
   84285 ** This routine returns a pointer to the array of objects.  This
   84286 ** might be the same as the pArray parameter or it might be a different
   84287 ** pointer if the array was resized.
   84288 */
   84289 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   84290   sqlite3 *db,      /* Connection to notify of malloc failures */
   84291   void *pArray,     /* Array of objects.  Might be reallocated */
   84292   int szEntry,      /* Size of each object in the array */
   84293   int *pnEntry,     /* Number of objects currently in use */
   84294   int *pIdx         /* Write the index of a new slot here */
   84295 ){
   84296   char *z;
   84297   int n = *pnEntry;
   84298   if( (n & (n-1))==0 ){
   84299     int sz = (n==0) ? 1 : 2*n;
   84300     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
   84301     if( pNew==0 ){
   84302       *pIdx = -1;
   84303       return pArray;
   84304     }
   84305     pArray = pNew;
   84306   }
   84307   z = (char*)pArray;
   84308   memset(&z[n * szEntry], 0, szEntry);
   84309   *pIdx = n;
   84310   ++*pnEntry;
   84311   return pArray;
   84312 }
   84313 
   84314 /*
   84315 ** Append a new element to the given IdList.  Create a new IdList if
   84316 ** need be.
   84317 **
   84318 ** A new IdList is returned, or NULL if malloc() fails.
   84319 */
   84320 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   84321   int i;
   84322   if( pList==0 ){
   84323     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   84324     if( pList==0 ) return 0;
   84325   }
   84326   pList->a = sqlite3ArrayAllocate(
   84327       db,
   84328       pList->a,
   84329       sizeof(pList->a[0]),
   84330       &pList->nId,
   84331       &i
   84332   );
   84333   if( i<0 ){
   84334     sqlite3IdListDelete(db, pList);
   84335     return 0;
   84336   }
   84337   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   84338   return pList;
   84339 }
   84340 
   84341 /*
   84342 ** Delete an IdList.
   84343 */
   84344 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   84345   int i;
   84346   if( pList==0 ) return;
   84347   for(i=0; i<pList->nId; i++){
   84348     sqlite3DbFree(db, pList->a[i].zName);
   84349   }
   84350   sqlite3DbFree(db, pList->a);
   84351   sqlite3DbFree(db, pList);
   84352 }
   84353 
   84354 /*
   84355 ** Return the index in pList of the identifier named zId.  Return -1
   84356 ** if not found.
   84357 */
   84358 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   84359   int i;
   84360   if( pList==0 ) return -1;
   84361   for(i=0; i<pList->nId; i++){
   84362     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   84363   }
   84364   return -1;
   84365 }
   84366 
   84367 /*
   84368 ** Expand the space allocated for the given SrcList object by
   84369 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   84370 ** New slots are zeroed.
   84371 **
   84372 ** For example, suppose a SrcList initially contains two entries: A,B.
   84373 ** To append 3 new entries onto the end, do this:
   84374 **
   84375 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   84376 **
   84377 ** After the call above it would contain:  A, B, nil, nil, nil.
   84378 ** If the iStart argument had been 1 instead of 2, then the result
   84379 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   84380 ** the iStart value would be 0.  The result then would
   84381 ** be: nil, nil, nil, A, B.
   84382 **
   84383 ** If a memory allocation fails the SrcList is unchanged.  The
   84384 ** db->mallocFailed flag will be set to true.
   84385 */
   84386 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   84387   sqlite3 *db,       /* Database connection to notify of OOM errors */
   84388   SrcList *pSrc,     /* The SrcList to be enlarged */
   84389   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   84390   int iStart         /* Index in pSrc->a[] of first new slot */
   84391 ){
   84392   int i;
   84393 
   84394   /* Sanity checking on calling parameters */
   84395   assert( iStart>=0 );
   84396   assert( nExtra>=1 );
   84397   assert( pSrc!=0 );
   84398   assert( iStart<=pSrc->nSrc );
   84399 
   84400   /* Allocate additional space if needed */
   84401   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
   84402     SrcList *pNew;
   84403     int nAlloc = pSrc->nSrc+nExtra;
   84404     int nGot;
   84405     pNew = sqlite3DbRealloc(db, pSrc,
   84406                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   84407     if( pNew==0 ){
   84408       assert( db->mallocFailed );
   84409       return pSrc;
   84410     }
   84411     pSrc = pNew;
   84412     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   84413     pSrc->nAlloc = (u16)nGot;
   84414   }
   84415 
   84416   /* Move existing slots that come after the newly inserted slots
   84417   ** out of the way */
   84418   for(i=pSrc->nSrc-1; i>=iStart; i--){
   84419     pSrc->a[i+nExtra] = pSrc->a[i];
   84420   }
   84421   pSrc->nSrc += (i16)nExtra;
   84422 
   84423   /* Zero the newly allocated slots */
   84424   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   84425   for(i=iStart; i<iStart+nExtra; i++){
   84426     pSrc->a[i].iCursor = -1;
   84427   }
   84428 
   84429   /* Return a pointer to the enlarged SrcList */
   84430   return pSrc;
   84431 }
   84432 
   84433 
   84434 /*
   84435 ** Append a new table name to the given SrcList.  Create a new SrcList if
   84436 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   84437 **
   84438 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   84439 ** SrcList might be the same as the SrcList that was input or it might be
   84440 ** a new one.  If an OOM error does occurs, then the prior value of pList
   84441 ** that is input to this routine is automatically freed.
   84442 **
   84443 ** If pDatabase is not null, it means that the table has an optional
   84444 ** database name prefix.  Like this:  "database.table".  The pDatabase
   84445 ** points to the table name and the pTable points to the database name.
   84446 ** The SrcList.a[].zName field is filled with the table name which might
   84447 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   84448 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   84449 ** or with NULL if no database is specified.
   84450 **
   84451 ** In other words, if call like this:
   84452 **
   84453 **         sqlite3SrcListAppend(D,A,B,0);
   84454 **
   84455 ** Then B is a table name and the database name is unspecified.  If called
   84456 ** like this:
   84457 **
   84458 **         sqlite3SrcListAppend(D,A,B,C);
   84459 **
   84460 ** Then C is the table name and B is the database name.  If C is defined
   84461 ** then so is B.  In other words, we never have a case where:
   84462 **
   84463 **         sqlite3SrcListAppend(D,A,0,C);
   84464 **
   84465 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   84466 ** before being added to the SrcList.
   84467 */
   84468 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   84469   sqlite3 *db,        /* Connection to notify of malloc failures */
   84470   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   84471   Token *pTable,      /* Table to append */
   84472   Token *pDatabase    /* Database of the table */
   84473 ){
   84474   struct SrcList_item *pItem;
   84475   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   84476   if( pList==0 ){
   84477     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   84478     if( pList==0 ) return 0;
   84479     pList->nAlloc = 1;
   84480   }
   84481   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   84482   if( db->mallocFailed ){
   84483     sqlite3SrcListDelete(db, pList);
   84484     return 0;
   84485   }
   84486   pItem = &pList->a[pList->nSrc-1];
   84487   if( pDatabase && pDatabase->z==0 ){
   84488     pDatabase = 0;
   84489   }
   84490   if( pDatabase ){
   84491     Token *pTemp = pDatabase;
   84492     pDatabase = pTable;
   84493     pTable = pTemp;
   84494   }
   84495   pItem->zName = sqlite3NameFromToken(db, pTable);
   84496   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   84497   return pList;
   84498 }
   84499 
   84500 /*
   84501 ** Assign VdbeCursor index numbers to all tables in a SrcList
   84502 */
   84503 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   84504   int i;
   84505   struct SrcList_item *pItem;
   84506   assert(pList || pParse->db->mallocFailed );
   84507   if( pList ){
   84508     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   84509       if( pItem->iCursor>=0 ) break;
   84510       pItem->iCursor = pParse->nTab++;
   84511       if( pItem->pSelect ){
   84512         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   84513       }
   84514     }
   84515   }
   84516 }
   84517 
   84518 /*
   84519 ** Delete an entire SrcList including all its substructure.
   84520 */
   84521 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   84522   int i;
   84523   struct SrcList_item *pItem;
   84524   if( pList==0 ) return;
   84525   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   84526     sqlite3DbFree(db, pItem->zDatabase);
   84527     sqlite3DbFree(db, pItem->zName);
   84528     sqlite3DbFree(db, pItem->zAlias);
   84529     sqlite3DbFree(db, pItem->zIndex);
   84530     sqlite3DeleteTable(db, pItem->pTab);
   84531     sqlite3SelectDelete(db, pItem->pSelect);
   84532     sqlite3ExprDelete(db, pItem->pOn);
   84533     sqlite3IdListDelete(db, pItem->pUsing);
   84534   }
   84535   sqlite3DbFree(db, pList);
   84536 }
   84537 
   84538 /*
   84539 ** This routine is called by the parser to add a new term to the
   84540 ** end of a growing FROM clause.  The "p" parameter is the part of
   84541 ** the FROM clause that has already been constructed.  "p" is NULL
   84542 ** if this is the first term of the FROM clause.  pTable and pDatabase
   84543 ** are the name of the table and database named in the FROM clause term.
   84544 ** pDatabase is NULL if the database name qualifier is missing - the
   84545 ** usual case.  If the term has a alias, then pAlias points to the
   84546 ** alias token.  If the term is a subquery, then pSubquery is the
   84547 ** SELECT statement that the subquery encodes.  The pTable and
   84548 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   84549 ** parameters are the content of the ON and USING clauses.
   84550 **
   84551 ** Return a new SrcList which encodes is the FROM with the new
   84552 ** term added.
   84553 */
   84554 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   84555   Parse *pParse,          /* Parsing context */
   84556   SrcList *p,             /* The left part of the FROM clause already seen */
   84557   Token *pTable,          /* Name of the table to add to the FROM clause */
   84558   Token *pDatabase,       /* Name of the database containing pTable */
   84559   Token *pAlias,          /* The right-hand side of the AS subexpression */
   84560   Select *pSubquery,      /* A subquery used in place of a table name */
   84561   Expr *pOn,              /* The ON clause of a join */
   84562   IdList *pUsing          /* The USING clause of a join */
   84563 ){
   84564   struct SrcList_item *pItem;
   84565   sqlite3 *db = pParse->db;
   84566   if( !p && (pOn || pUsing) ){
   84567     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   84568       (pOn ? "ON" : "USING")
   84569     );
   84570     goto append_from_error;
   84571   }
   84572   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   84573   if( p==0 || NEVER(p->nSrc==0) ){
   84574     goto append_from_error;
   84575   }
   84576   pItem = &p->a[p->nSrc-1];
   84577   assert( pAlias!=0 );
   84578   if( pAlias->n ){
   84579     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   84580   }
   84581   pItem->pSelect = pSubquery;
   84582   pItem->pOn = pOn;
   84583   pItem->pUsing = pUsing;
   84584   return p;
   84585 
   84586  append_from_error:
   84587   assert( p==0 );
   84588   sqlite3ExprDelete(db, pOn);
   84589   sqlite3IdListDelete(db, pUsing);
   84590   sqlite3SelectDelete(db, pSubquery);
   84591   return 0;
   84592 }
   84593 
   84594 /*
   84595 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   84596 ** element of the source-list passed as the second argument.
   84597 */
   84598 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   84599   assert( pIndexedBy!=0 );
   84600   if( p && ALWAYS(p->nSrc>0) ){
   84601     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   84602     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   84603     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   84604       /* A "NOT INDEXED" clause was supplied. See parse.y
   84605       ** construct "indexed_opt" for details. */
   84606       pItem->notIndexed = 1;
   84607     }else{
   84608       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   84609     }
   84610   }
   84611 }
   84612 
   84613 /*
   84614 ** When building up a FROM clause in the parser, the join operator
   84615 ** is initially attached to the left operand.  But the code generator
   84616 ** expects the join operator to be on the right operand.  This routine
   84617 ** Shifts all join operators from left to right for an entire FROM
   84618 ** clause.
   84619 **
   84620 ** Example: Suppose the join is like this:
   84621 **
   84622 **           A natural cross join B
   84623 **
   84624 ** The operator is "natural cross join".  The A and B operands are stored
   84625 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   84626 ** operator with A.  This routine shifts that operator over to B.
   84627 */
   84628 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   84629   if( p ){
   84630     int i;
   84631     assert( p->a || p->nSrc==0 );
   84632     for(i=p->nSrc-1; i>0; i--){
   84633       p->a[i].jointype = p->a[i-1].jointype;
   84634     }
   84635     p->a[0].jointype = 0;
   84636   }
   84637 }
   84638 
   84639 /*
   84640 ** Begin a transaction
   84641 */
   84642 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   84643   sqlite3 *db;
   84644   Vdbe *v;
   84645   int i;
   84646 
   84647   assert( pParse!=0 );
   84648   db = pParse->db;
   84649   assert( db!=0 );
   84650 /*  if( db->aDb[0].pBt==0 ) return; */
   84651   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   84652     return;
   84653   }
   84654   v = sqlite3GetVdbe(pParse);
   84655   if( !v ) return;
   84656   if( type!=TK_DEFERRED ){
   84657     for(i=0; i<db->nDb; i++){
   84658       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   84659       sqlite3VdbeUsesBtree(v, i);
   84660     }
   84661   }
   84662   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   84663 }
   84664 
   84665 /*
   84666 ** Commit a transaction
   84667 */
   84668 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   84669   Vdbe *v;
   84670 
   84671   assert( pParse!=0 );
   84672   assert( pParse->db!=0 );
   84673   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   84674     return;
   84675   }
   84676   v = sqlite3GetVdbe(pParse);
   84677   if( v ){
   84678     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   84679   }
   84680 }
   84681 
   84682 /*
   84683 ** Rollback a transaction
   84684 */
   84685 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   84686   Vdbe *v;
   84687 
   84688   assert( pParse!=0 );
   84689   assert( pParse->db!=0 );
   84690   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   84691     return;
   84692   }
   84693   v = sqlite3GetVdbe(pParse);
   84694   if( v ){
   84695     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   84696   }
   84697 }
   84698 
   84699 /*
   84700 ** This function is called by the parser when it parses a command to create,
   84701 ** release or rollback an SQL savepoint.
   84702 */
   84703 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   84704   char *zName = sqlite3NameFromToken(pParse->db, pName);
   84705   if( zName ){
   84706     Vdbe *v = sqlite3GetVdbe(pParse);
   84707 #ifndef SQLITE_OMIT_AUTHORIZATION
   84708     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   84709     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   84710 #endif
   84711     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   84712       sqlite3DbFree(pParse->db, zName);
   84713       return;
   84714     }
   84715     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   84716   }
   84717 }
   84718 
   84719 /*
   84720 ** Make sure the TEMP database is open and available for use.  Return
   84721 ** the number of errors.  Leave any error messages in the pParse structure.
   84722 */
   84723 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   84724   sqlite3 *db = pParse->db;
   84725   if( db->aDb[1].pBt==0 && !pParse->explain ){
   84726     int rc;
   84727     Btree *pBt;
   84728     static const int flags =
   84729           SQLITE_OPEN_READWRITE |
   84730           SQLITE_OPEN_CREATE |
   84731           SQLITE_OPEN_EXCLUSIVE |
   84732           SQLITE_OPEN_DELETEONCLOSE |
   84733           SQLITE_OPEN_TEMP_DB;
   84734 
   84735     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
   84736     if( rc!=SQLITE_OK ){
   84737       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   84738         "file for storing temporary tables");
   84739       pParse->rc = rc;
   84740       return 1;
   84741     }
   84742     db->aDb[1].pBt = pBt;
   84743     assert( db->aDb[1].pSchema );
   84744     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   84745       db->mallocFailed = 1;
   84746       return 1;
   84747     }
   84748   }
   84749   return 0;
   84750 }
   84751 
   84752 /*
   84753 ** Generate VDBE code that will verify the schema cookie and start
   84754 ** a read-transaction for all named database files.
   84755 **
   84756 ** It is important that all schema cookies be verified and all
   84757 ** read transactions be started before anything else happens in
   84758 ** the VDBE program.  But this routine can be called after much other
   84759 ** code has been generated.  So here is what we do:
   84760 **
   84761 ** The first time this routine is called, we code an OP_Goto that
   84762 ** will jump to a subroutine at the end of the program.  Then we
   84763 ** record every database that needs its schema verified in the
   84764 ** pParse->cookieMask field.  Later, after all other code has been
   84765 ** generated, the subroutine that does the cookie verifications and
   84766 ** starts the transactions will be coded and the OP_Goto P2 value
   84767 ** will be made to point to that subroutine.  The generation of the
   84768 ** cookie verification subroutine code happens in sqlite3FinishCoding().
   84769 **
   84770 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
   84771 ** schema on any databases.  This can be used to position the OP_Goto
   84772 ** early in the code, before we know if any database tables will be used.
   84773 */
   84774 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   84775   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84776 
   84777   if( pToplevel->cookieGoto==0 ){
   84778     Vdbe *v = sqlite3GetVdbe(pToplevel);
   84779     if( v==0 ) return;  /* This only happens if there was a prior error */
   84780     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
   84781   }
   84782   if( iDb>=0 ){
   84783     sqlite3 *db = pToplevel->db;
   84784     yDbMask mask;
   84785 
   84786     assert( iDb<db->nDb );
   84787     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   84788     assert( iDb<SQLITE_MAX_ATTACHED+2 );
   84789     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84790     mask = ((yDbMask)1)<<iDb;
   84791     if( (pToplevel->cookieMask & mask)==0 ){
   84792       pToplevel->cookieMask |= mask;
   84793       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   84794       if( !OMIT_TEMPDB && iDb==1 ){
   84795         sqlite3OpenTempDatabase(pToplevel);
   84796       }
   84797     }
   84798   }
   84799 }
   84800 
   84801 /*
   84802 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
   84803 ** attached database. Otherwise, invoke it for the database named zDb only.
   84804 */
   84805 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
   84806   sqlite3 *db = pParse->db;
   84807   int i;
   84808   for(i=0; i<db->nDb; i++){
   84809     Db *pDb = &db->aDb[i];
   84810     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
   84811       sqlite3CodeVerifySchema(pParse, i);
   84812     }
   84813   }
   84814 }
   84815 
   84816 /*
   84817 ** Generate VDBE code that prepares for doing an operation that
   84818 ** might change the database.
   84819 **
   84820 ** This routine starts a new transaction if we are not already within
   84821 ** a transaction.  If we are already within a transaction, then a checkpoint
   84822 ** is set if the setStatement parameter is true.  A checkpoint should
   84823 ** be set for operations that might fail (due to a constraint) part of
   84824 ** the way through and which will need to undo some writes without having to
   84825 ** rollback the whole transaction.  For operations where all constraints
   84826 ** can be checked before any changes are made to the database, it is never
   84827 ** necessary to undo a write and the checkpoint should not be set.
   84828 */
   84829 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   84830   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84831   sqlite3CodeVerifySchema(pParse, iDb);
   84832   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
   84833   pToplevel->isMultiWrite |= setStatement;
   84834 }
   84835 
   84836 /*
   84837 ** Indicate that the statement currently under construction might write
   84838 ** more than one entry (example: deleting one row then inserting another,
   84839 ** inserting multiple rows in a table, or inserting a row and index entries.)
   84840 ** If an abort occurs after some of these writes have completed, then it will
   84841 ** be necessary to undo the completed writes.
   84842 */
   84843 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   84844   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84845   pToplevel->isMultiWrite = 1;
   84846 }
   84847 
   84848 /*
   84849 ** The code generator calls this routine if is discovers that it is
   84850 ** possible to abort a statement prior to completion.  In order to
   84851 ** perform this abort without corrupting the database, we need to make
   84852 ** sure that the statement is protected by a statement transaction.
   84853 **
   84854 ** Technically, we only need to set the mayAbort flag if the
   84855 ** isMultiWrite flag was previously set.  There is a time dependency
   84856 ** such that the abort must occur after the multiwrite.  This makes
   84857 ** some statements involving the REPLACE conflict resolution algorithm
   84858 ** go a little faster.  But taking advantage of this time dependency
   84859 ** makes it more difficult to prove that the code is correct (in
   84860 ** particular, it prevents us from writing an effective
   84861 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   84862 ** to take the safe route and skip the optimization.
   84863 */
   84864 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   84865   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84866   pToplevel->mayAbort = 1;
   84867 }
   84868 
   84869 /*
   84870 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   84871 ** error. The onError parameter determines which (if any) of the statement
   84872 ** and/or current transaction is rolled back.
   84873 */
   84874 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
   84875   Vdbe *v = sqlite3GetVdbe(pParse);
   84876   if( onError==OE_Abort ){
   84877     sqlite3MayAbort(pParse);
   84878   }
   84879   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
   84880 }
   84881 
   84882 /*
   84883 ** Check to see if pIndex uses the collating sequence pColl.  Return
   84884 ** true if it does and false if it does not.
   84885 */
   84886 #ifndef SQLITE_OMIT_REINDEX
   84887 static int collationMatch(const char *zColl, Index *pIndex){
   84888   int i;
   84889   assert( zColl!=0 );
   84890   for(i=0; i<pIndex->nColumn; i++){
   84891     const char *z = pIndex->azColl[i];
   84892     assert( z!=0 );
   84893     if( 0==sqlite3StrICmp(z, zColl) ){
   84894       return 1;
   84895     }
   84896   }
   84897   return 0;
   84898 }
   84899 #endif
   84900 
   84901 /*
   84902 ** Recompute all indices of pTab that use the collating sequence pColl.
   84903 ** If pColl==0 then recompute all indices of pTab.
   84904 */
   84905 #ifndef SQLITE_OMIT_REINDEX
   84906 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   84907   Index *pIndex;              /* An index associated with pTab */
   84908 
   84909   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   84910     if( zColl==0 || collationMatch(zColl, pIndex) ){
   84911       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   84912       sqlite3BeginWriteOperation(pParse, 0, iDb);
   84913       sqlite3RefillIndex(pParse, pIndex, -1);
   84914     }
   84915   }
   84916 }
   84917 #endif
   84918 
   84919 /*
   84920 ** Recompute all indices of all tables in all databases where the
   84921 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   84922 ** all indices everywhere.
   84923 */
   84924 #ifndef SQLITE_OMIT_REINDEX
   84925 static void reindexDatabases(Parse *pParse, char const *zColl){
   84926   Db *pDb;                    /* A single database */
   84927   int iDb;                    /* The database index number */
   84928   sqlite3 *db = pParse->db;   /* The database connection */
   84929   HashElem *k;                /* For looping over tables in pDb */
   84930   Table *pTab;                /* A table in the database */
   84931 
   84932   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
   84933   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   84934     assert( pDb!=0 );
   84935     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   84936       pTab = (Table*)sqliteHashData(k);
   84937       reindexTable(pParse, pTab, zColl);
   84938     }
   84939   }
   84940 }
   84941 #endif
   84942 
   84943 /*
   84944 ** Generate code for the REINDEX command.
   84945 **
   84946 **        REINDEX                            -- 1
   84947 **        REINDEX  <collation>               -- 2
   84948 **        REINDEX  ?<database>.?<tablename>  -- 3
   84949 **        REINDEX  ?<database>.?<indexname>  -- 4
   84950 **
   84951 ** Form 1 causes all indices in all attached databases to be rebuilt.
   84952 ** Form 2 rebuilds all indices in all databases that use the named
   84953 ** collating function.  Forms 3 and 4 rebuild the named index or all
   84954 ** indices associated with the named table.
   84955 */
   84956 #ifndef SQLITE_OMIT_REINDEX
   84957 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   84958   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   84959   char *z;                    /* Name of a table or index */
   84960   const char *zDb;            /* Name of the database */
   84961   Table *pTab;                /* A table in the database */
   84962   Index *pIndex;              /* An index associated with pTab */
   84963   int iDb;                    /* The database index number */
   84964   sqlite3 *db = pParse->db;   /* The database connection */
   84965   Token *pObjName;            /* Name of the table or index to be reindexed */
   84966 
   84967   /* Read the database schema. If an error occurs, leave an error message
   84968   ** and code in pParse and return NULL. */
   84969   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84970     return;
   84971   }
   84972 
   84973   if( pName1==0 ){
   84974     reindexDatabases(pParse, 0);
   84975     return;
   84976   }else if( NEVER(pName2==0) || pName2->z==0 ){
   84977     char *zColl;
   84978     assert( pName1->z );
   84979     zColl = sqlite3NameFromToken(pParse->db, pName1);
   84980     if( !zColl ) return;
   84981     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   84982     if( pColl ){
   84983       reindexDatabases(pParse, zColl);
   84984       sqlite3DbFree(db, zColl);
   84985       return;
   84986     }
   84987     sqlite3DbFree(db, zColl);
   84988   }
   84989   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   84990   if( iDb<0 ) return;
   84991   z = sqlite3NameFromToken(db, pObjName);
   84992   if( z==0 ) return;
   84993   zDb = db->aDb[iDb].zName;
   84994   pTab = sqlite3FindTable(db, z, zDb);
   84995   if( pTab ){
   84996     reindexTable(pParse, pTab, 0);
   84997     sqlite3DbFree(db, z);
   84998     return;
   84999   }
   85000   pIndex = sqlite3FindIndex(db, z, zDb);
   85001   sqlite3DbFree(db, z);
   85002   if( pIndex ){
   85003     sqlite3BeginWriteOperation(pParse, 0, iDb);
   85004     sqlite3RefillIndex(pParse, pIndex, -1);
   85005     return;
   85006   }
   85007   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   85008 }
   85009 #endif
   85010 
   85011 /*
   85012 ** Return a dynamicly allocated KeyInfo structure that can be used
   85013 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
   85014 **
   85015 ** If successful, a pointer to the new structure is returned. In this case
   85016 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
   85017 ** pointer. If an error occurs (out of memory or missing collation
   85018 ** sequence), NULL is returned and the state of pParse updated to reflect
   85019 ** the error.
   85020 */
   85021 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
   85022   int i;
   85023   int nCol = pIdx->nColumn;
   85024   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
   85025   sqlite3 *db = pParse->db;
   85026   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
   85027 
   85028   if( pKey ){
   85029     pKey->db = pParse->db;
   85030     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
   85031     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
   85032     for(i=0; i<nCol; i++){
   85033       char *zColl = pIdx->azColl[i];
   85034       assert( zColl );
   85035       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
   85036       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   85037     }
   85038     pKey->nField = (u16)nCol;
   85039   }
   85040 
   85041   if( pParse->nErr ){
   85042     sqlite3DbFree(db, pKey);
   85043     pKey = 0;
   85044   }
   85045   return pKey;
   85046 }
   85047 
   85048 /************** End of build.c ***********************************************/
   85049 /************** Begin file callback.c ****************************************/
   85050 /*
   85051 ** 2005 May 23
   85052 **
   85053 ** The author disclaims copyright to this source code.  In place of
   85054 ** a legal notice, here is a blessing:
   85055 **
   85056 **    May you do good and not evil.
   85057 **    May you find forgiveness for yourself and forgive others.
   85058 **    May you share freely, never taking more than you give.
   85059 **
   85060 *************************************************************************
   85061 **
   85062 ** This file contains functions used to access the internal hash tables
   85063 ** of user defined functions and collation sequences.
   85064 */
   85065 
   85066 
   85067 /*
   85068 ** Invoke the 'collation needed' callback to request a collation sequence
   85069 ** in the encoding enc of name zName, length nName.
   85070 */
   85071 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   85072   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   85073   if( db->xCollNeeded ){
   85074     char *zExternal = sqlite3DbStrDup(db, zName);
   85075     if( !zExternal ) return;
   85076     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   85077     sqlite3DbFree(db, zExternal);
   85078   }
   85079 #ifndef SQLITE_OMIT_UTF16
   85080   if( db->xCollNeeded16 ){
   85081     char const *zExternal;
   85082     sqlite3_value *pTmp = sqlite3ValueNew(db);
   85083     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   85084     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   85085     if( zExternal ){
   85086       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   85087     }
   85088     sqlite3ValueFree(pTmp);
   85089   }
   85090 #endif
   85091 }
   85092 
   85093 /*
   85094 ** This routine is called if the collation factory fails to deliver a
   85095 ** collation function in the best encoding but there may be other versions
   85096 ** of this collation function (for other text encodings) available. Use one
   85097 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   85098 ** possible.
   85099 */
   85100 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   85101   CollSeq *pColl2;
   85102   char *z = pColl->zName;
   85103   int i;
   85104   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   85105   for(i=0; i<3; i++){
   85106     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   85107     if( pColl2->xCmp!=0 ){
   85108       memcpy(pColl, pColl2, sizeof(CollSeq));
   85109       pColl->xDel = 0;         /* Do not copy the destructor */
   85110       return SQLITE_OK;
   85111     }
   85112   }
   85113   return SQLITE_ERROR;
   85114 }
   85115 
   85116 /*
   85117 ** This function is responsible for invoking the collation factory callback
   85118 ** or substituting a collation sequence of a different encoding when the
   85119 ** requested collation sequence is not available in the desired encoding.
   85120 **
   85121 ** If it is not NULL, then pColl must point to the database native encoding
   85122 ** collation sequence with name zName, length nName.
   85123 **
   85124 ** The return value is either the collation sequence to be used in database
   85125 ** db for collation type name zName, length nName, or NULL, if no collation
   85126 ** sequence can be found.
   85127 **
   85128 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   85129 */
   85130 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   85131   sqlite3* db,          /* The database connection */
   85132   u8 enc,               /* The desired encoding for the collating sequence */
   85133   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   85134   const char *zName     /* Collating sequence name */
   85135 ){
   85136   CollSeq *p;
   85137 
   85138   p = pColl;
   85139   if( !p ){
   85140     p = sqlite3FindCollSeq(db, enc, zName, 0);
   85141   }
   85142   if( !p || !p->xCmp ){
   85143     /* No collation sequence of this type for this encoding is registered.
   85144     ** Call the collation factory to see if it can supply us with one.
   85145     */
   85146     callCollNeeded(db, enc, zName);
   85147     p = sqlite3FindCollSeq(db, enc, zName, 0);
   85148   }
   85149   if( p && !p->xCmp && synthCollSeq(db, p) ){
   85150     p = 0;
   85151   }
   85152   assert( !p || p->xCmp );
   85153   return p;
   85154 }
   85155 
   85156 /*
   85157 ** This routine is called on a collation sequence before it is used to
   85158 ** check that it is defined. An undefined collation sequence exists when
   85159 ** a database is loaded that contains references to collation sequences
   85160 ** that have not been defined by sqlite3_create_collation() etc.
   85161 **
   85162 ** If required, this routine calls the 'collation needed' callback to
   85163 ** request a definition of the collating sequence. If this doesn't work,
   85164 ** an equivalent collating sequence that uses a text encoding different
   85165 ** from the main database is substituted, if one is available.
   85166 */
   85167 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   85168   if( pColl ){
   85169     const char *zName = pColl->zName;
   85170     sqlite3 *db = pParse->db;
   85171     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
   85172     if( !p ){
   85173       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   85174       pParse->nErr++;
   85175       return SQLITE_ERROR;
   85176     }
   85177     assert( p==pColl );
   85178   }
   85179   return SQLITE_OK;
   85180 }
   85181 
   85182 
   85183 
   85184 /*
   85185 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   85186 ** specified by zName and nName is not found and parameter 'create' is
   85187 ** true, then create a new entry. Otherwise return NULL.
   85188 **
   85189 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   85190 ** array of three CollSeq structures. The first is the collation sequence
   85191 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   85192 **
   85193 ** Stored immediately after the three collation sequences is a copy of
   85194 ** the collation sequence name. A pointer to this string is stored in
   85195 ** each collation sequence structure.
   85196 */
   85197 static CollSeq *findCollSeqEntry(
   85198   sqlite3 *db,          /* Database connection */
   85199   const char *zName,    /* Name of the collating sequence */
   85200   int create            /* Create a new entry if true */
   85201 ){
   85202   CollSeq *pColl;
   85203   int nName = sqlite3Strlen30(zName);
   85204   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   85205 
   85206   if( 0==pColl && create ){
   85207     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   85208     if( pColl ){
   85209       CollSeq *pDel = 0;
   85210       pColl[0].zName = (char*)&pColl[3];
   85211       pColl[0].enc = SQLITE_UTF8;
   85212       pColl[1].zName = (char*)&pColl[3];
   85213       pColl[1].enc = SQLITE_UTF16LE;
   85214       pColl[2].zName = (char*)&pColl[3];
   85215       pColl[2].enc = SQLITE_UTF16BE;
   85216       memcpy(pColl[0].zName, zName, nName);
   85217       pColl[0].zName[nName] = 0;
   85218       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   85219 
   85220       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   85221       ** return the pColl pointer to be deleted (because it wasn't added
   85222       ** to the hash table).
   85223       */
   85224       assert( pDel==0 || pDel==pColl );
   85225       if( pDel!=0 ){
   85226         db->mallocFailed = 1;
   85227         sqlite3DbFree(db, pDel);
   85228         pColl = 0;
   85229       }
   85230     }
   85231   }
   85232   return pColl;
   85233 }
   85234 
   85235 /*
   85236 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   85237 ** Return the CollSeq* pointer for the collation sequence named zName
   85238 ** for the encoding 'enc' from the database 'db'.
   85239 **
   85240 ** If the entry specified is not found and 'create' is true, then create a
   85241 ** new entry.  Otherwise return NULL.
   85242 **
   85243 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   85244 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   85245 ** if necessary and generates an error message if the collating sequence
   85246 ** cannot be found.
   85247 **
   85248 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   85249 */
   85250 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   85251   sqlite3 *db,
   85252   u8 enc,
   85253   const char *zName,
   85254   int create
   85255 ){
   85256   CollSeq *pColl;
   85257   if( zName ){
   85258     pColl = findCollSeqEntry(db, zName, create);
   85259   }else{
   85260     pColl = db->pDfltColl;
   85261   }
   85262   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   85263   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   85264   if( pColl ) pColl += enc-1;
   85265   return pColl;
   85266 }
   85267 
   85268 /* During the search for the best function definition, this procedure
   85269 ** is called to test how well the function passed as the first argument
   85270 ** matches the request for a function with nArg arguments in a system
   85271 ** that uses encoding enc. The value returned indicates how well the
   85272 ** request is matched. A higher value indicates a better match.
   85273 **
   85274 ** The returned value is always between 0 and 6, as follows:
   85275 **
   85276 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
   85277 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
   85278 **    encoding is requested, or vice versa.
   85279 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
   85280 **    requested, or vice versa.
   85281 ** 3: A variable arguments function using the same text encoding.
   85282 ** 4: A function with the exact number of arguments requested that
   85283 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
   85284 ** 5: A function with the exact number of arguments requested that
   85285 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
   85286 ** 6: An exact match.
   85287 **
   85288 */
   85289 static int matchQuality(FuncDef *p, int nArg, u8 enc){
   85290   int match = 0;
   85291   if( p->nArg==-1 || p->nArg==nArg
   85292    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
   85293   ){
   85294     match = 1;
   85295     if( p->nArg==nArg || nArg==-1 ){
   85296       match = 4;
   85297     }
   85298     if( enc==p->iPrefEnc ){
   85299       match += 2;
   85300     }
   85301     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
   85302              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
   85303       match += 1;
   85304     }
   85305   }
   85306   return match;
   85307 }
   85308 
   85309 /*
   85310 ** Search a FuncDefHash for a function with the given name.  Return
   85311 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   85312 */
   85313 static FuncDef *functionSearch(
   85314   FuncDefHash *pHash,  /* Hash table to search */
   85315   int h,               /* Hash of the name */
   85316   const char *zFunc,   /* Name of function */
   85317   int nFunc            /* Number of bytes in zFunc */
   85318 ){
   85319   FuncDef *p;
   85320   for(p=pHash->a[h]; p; p=p->pHash){
   85321     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   85322       return p;
   85323     }
   85324   }
   85325   return 0;
   85326 }
   85327 
   85328 /*
   85329 ** Insert a new FuncDef into a FuncDefHash hash table.
   85330 */
   85331 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   85332   FuncDefHash *pHash,  /* The hash table into which to insert */
   85333   FuncDef *pDef        /* The function definition to insert */
   85334 ){
   85335   FuncDef *pOther;
   85336   int nName = sqlite3Strlen30(pDef->zName);
   85337   u8 c1 = (u8)pDef->zName[0];
   85338   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   85339   pOther = functionSearch(pHash, h, pDef->zName, nName);
   85340   if( pOther ){
   85341     assert( pOther!=pDef && pOther->pNext!=pDef );
   85342     pDef->pNext = pOther->pNext;
   85343     pOther->pNext = pDef;
   85344   }else{
   85345     pDef->pNext = 0;
   85346     pDef->pHash = pHash->a[h];
   85347     pHash->a[h] = pDef;
   85348   }
   85349 }
   85350 
   85351 
   85352 
   85353 /*
   85354 ** Locate a user function given a name, a number of arguments and a flag
   85355 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   85356 ** pointer to the FuncDef structure that defines that function, or return
   85357 ** NULL if the function does not exist.
   85358 **
   85359 ** If the createFlag argument is true, then a new (blank) FuncDef
   85360 ** structure is created and liked into the "db" structure if a
   85361 ** no matching function previously existed.  When createFlag is true
   85362 ** and the nArg parameter is -1, then only a function that accepts
   85363 ** any number of arguments will be returned.
   85364 **
   85365 ** If createFlag is false and nArg is -1, then the first valid
   85366 ** function found is returned.  A function is valid if either xFunc
   85367 ** or xStep is non-zero.
   85368 **
   85369 ** If createFlag is false, then a function with the required name and
   85370 ** number of arguments may be returned even if the eTextRep flag does not
   85371 ** match that requested.
   85372 */
   85373 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   85374   sqlite3 *db,       /* An open database */
   85375   const char *zName, /* Name of the function.  Not null-terminated */
   85376   int nName,         /* Number of characters in the name */
   85377   int nArg,          /* Number of arguments.  -1 means any number */
   85378   u8 enc,            /* Preferred text encoding */
   85379   int createFlag     /* Create new entry if true and does not otherwise exist */
   85380 ){
   85381   FuncDef *p;         /* Iterator variable */
   85382   FuncDef *pBest = 0; /* Best match found so far */
   85383   int bestScore = 0;  /* Score of best match */
   85384   int h;              /* Hash value */
   85385 
   85386 
   85387   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   85388   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   85389 
   85390   /* First search for a match amongst the application-defined functions.
   85391   */
   85392   p = functionSearch(&db->aFunc, h, zName, nName);
   85393   while( p ){
   85394     int score = matchQuality(p, nArg, enc);
   85395     if( score>bestScore ){
   85396       pBest = p;
   85397       bestScore = score;
   85398     }
   85399     p = p->pNext;
   85400   }
   85401 
   85402   /* If no match is found, search the built-in functions.
   85403   **
   85404   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
   85405   ** functions even if a prior app-defined function was found.  And give
   85406   ** priority to built-in functions.
   85407   **
   85408   ** Except, if createFlag is true, that means that we are trying to
   85409   ** install a new function.  Whatever FuncDef structure is returned it will
   85410   ** have fields overwritten with new information appropriate for the
   85411   ** new function.  But the FuncDefs for built-in functions are read-only.
   85412   ** So we must not search for built-ins when creating a new function.
   85413   */
   85414   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
   85415     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   85416     bestScore = 0;
   85417     p = functionSearch(pHash, h, zName, nName);
   85418     while( p ){
   85419       int score = matchQuality(p, nArg, enc);
   85420       if( score>bestScore ){
   85421         pBest = p;
   85422         bestScore = score;
   85423       }
   85424       p = p->pNext;
   85425     }
   85426   }
   85427 
   85428   /* If the createFlag parameter is true and the search did not reveal an
   85429   ** exact match for the name, number of arguments and encoding, then add a
   85430   ** new entry to the hash table and return it.
   85431   */
   85432   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
   85433       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   85434     pBest->zName = (char *)&pBest[1];
   85435     pBest->nArg = (u16)nArg;
   85436     pBest->iPrefEnc = enc;
   85437     memcpy(pBest->zName, zName, nName);
   85438     pBest->zName[nName] = 0;
   85439     sqlite3FuncDefInsert(&db->aFunc, pBest);
   85440   }
   85441 
   85442   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   85443     return pBest;
   85444   }
   85445   return 0;
   85446 }
   85447 
   85448 /*
   85449 ** Free all resources held by the schema structure. The void* argument points
   85450 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   85451 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
   85452 ** of the schema hash tables).
   85453 **
   85454 ** The Schema.cache_size variable is not cleared.
   85455 */
   85456 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
   85457   Hash temp1;
   85458   Hash temp2;
   85459   HashElem *pElem;
   85460   Schema *pSchema = (Schema *)p;
   85461 
   85462   temp1 = pSchema->tblHash;
   85463   temp2 = pSchema->trigHash;
   85464   sqlite3HashInit(&pSchema->trigHash);
   85465   sqlite3HashClear(&pSchema->idxHash);
   85466   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   85467     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   85468   }
   85469   sqlite3HashClear(&temp2);
   85470   sqlite3HashInit(&pSchema->tblHash);
   85471   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   85472     Table *pTab = sqliteHashData(pElem);
   85473     sqlite3DeleteTable(0, pTab);
   85474   }
   85475   sqlite3HashClear(&temp1);
   85476   sqlite3HashClear(&pSchema->fkeyHash);
   85477   pSchema->pSeqTab = 0;
   85478   if( pSchema->flags & DB_SchemaLoaded ){
   85479     pSchema->iGeneration++;
   85480     pSchema->flags &= ~DB_SchemaLoaded;
   85481   }
   85482 }
   85483 
   85484 /*
   85485 ** Find and return the schema associated with a BTree.  Create
   85486 ** a new one if necessary.
   85487 */
   85488 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   85489   Schema * p;
   85490   if( pBt ){
   85491     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   85492   }else{
   85493     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   85494   }
   85495   if( !p ){
   85496     db->mallocFailed = 1;
   85497   }else if ( 0==p->file_format ){
   85498     sqlite3HashInit(&p->tblHash);
   85499     sqlite3HashInit(&p->idxHash);
   85500     sqlite3HashInit(&p->trigHash);
   85501     sqlite3HashInit(&p->fkeyHash);
   85502     p->enc = SQLITE_UTF8;
   85503   }
   85504   return p;
   85505 }
   85506 
   85507 /************** End of callback.c ********************************************/
   85508 /************** Begin file delete.c ******************************************/
   85509 /*
   85510 ** 2001 September 15
   85511 **
   85512 ** The author disclaims copyright to this source code.  In place of
   85513 ** a legal notice, here is a blessing:
   85514 **
   85515 **    May you do good and not evil.
   85516 **    May you find forgiveness for yourself and forgive others.
   85517 **    May you share freely, never taking more than you give.
   85518 **
   85519 *************************************************************************
   85520 ** This file contains C code routines that are called by the parser
   85521 ** in order to generate code for DELETE FROM statements.
   85522 */
   85523 
   85524 /*
   85525 ** While a SrcList can in general represent multiple tables and subqueries
   85526 ** (as in the FROM clause of a SELECT statement) in this case it contains
   85527 ** the name of a single table, as one might find in an INSERT, DELETE,
   85528 ** or UPDATE statement.  Look up that table in the symbol table and
   85529 ** return a pointer.  Set an error message and return NULL if the table
   85530 ** name is not found or if any other error occurs.
   85531 **
   85532 ** The following fields are initialized appropriate in pSrc:
   85533 **
   85534 **    pSrc->a[0].pTab       Pointer to the Table object
   85535 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
   85536 **
   85537 */
   85538 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   85539   struct SrcList_item *pItem = pSrc->a;
   85540   Table *pTab;
   85541   assert( pItem && pSrc->nSrc==1 );
   85542   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   85543   sqlite3DeleteTable(pParse->db, pItem->pTab);
   85544   pItem->pTab = pTab;
   85545   if( pTab ){
   85546     pTab->nRef++;
   85547   }
   85548   if( sqlite3IndexedByLookup(pParse, pItem) ){
   85549     pTab = 0;
   85550   }
   85551   return pTab;
   85552 }
   85553 
   85554 /*
   85555 ** Check to make sure the given table is writable.  If it is not
   85556 ** writable, generate an error message and return 1.  If it is
   85557 ** writable return 0;
   85558 */
   85559 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   85560   /* A table is not writable under the following circumstances:
   85561   **
   85562   **   1) It is a virtual table and no implementation of the xUpdate method
   85563   **      has been provided, or
   85564   **   2) It is a system table (i.e. sqlite_master), this call is not
   85565   **      part of a nested parse and writable_schema pragma has not
   85566   **      been specified.
   85567   **
   85568   ** In either case leave an error message in pParse and return non-zero.
   85569   */
   85570   if( ( IsVirtual(pTab)
   85571      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   85572    || ( (pTab->tabFlags & TF_Readonly)!=0
   85573      && (pParse->db->flags & SQLITE_WriteSchema)==0
   85574      && pParse->nested==0 )
   85575   ){
   85576     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   85577     return 1;
   85578   }
   85579 
   85580 #ifndef SQLITE_OMIT_VIEW
   85581   if( !viewOk && pTab->pSelect ){
   85582     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   85583     return 1;
   85584   }
   85585 #endif
   85586   return 0;
   85587 }
   85588 
   85589 
   85590 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   85591 /*
   85592 ** Evaluate a view and store its result in an ephemeral table.  The
   85593 ** pWhere argument is an optional WHERE clause that restricts the
   85594 ** set of rows in the view that are to be added to the ephemeral table.
   85595 */
   85596 SQLITE_PRIVATE void sqlite3MaterializeView(
   85597   Parse *pParse,       /* Parsing context */
   85598   Table *pView,        /* View definition */
   85599   Expr *pWhere,        /* Optional WHERE clause to be added */
   85600   int iCur             /* Cursor number for ephemerial table */
   85601 ){
   85602   SelectDest dest;
   85603   Select *pDup;
   85604   sqlite3 *db = pParse->db;
   85605 
   85606   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
   85607   if( pWhere ){
   85608     SrcList *pFrom;
   85609 
   85610     pWhere = sqlite3ExprDup(db, pWhere, 0);
   85611     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   85612     if( pFrom ){
   85613       assert( pFrom->nSrc==1 );
   85614       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
   85615       pFrom->a[0].pSelect = pDup;
   85616       assert( pFrom->a[0].pOn==0 );
   85617       assert( pFrom->a[0].pUsing==0 );
   85618     }else{
   85619       sqlite3SelectDelete(db, pDup);
   85620     }
   85621     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   85622   }
   85623   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   85624   sqlite3Select(pParse, pDup, &dest);
   85625   sqlite3SelectDelete(db, pDup);
   85626 }
   85627 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   85628 
   85629 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   85630 /*
   85631 ** Generate an expression tree to implement the WHERE, ORDER BY,
   85632 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   85633 **
   85634 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   85635 **                            \__________________________/
   85636 **                               pLimitWhere (pInClause)
   85637 */
   85638 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   85639   Parse *pParse,               /* The parser context */
   85640   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   85641   Expr *pWhere,                /* The WHERE clause.  May be null */
   85642   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   85643   Expr *pLimit,                /* The LIMIT clause.  May be null */
   85644   Expr *pOffset,               /* The OFFSET clause.  May be null */
   85645   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
   85646 ){
   85647   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   85648   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   85649   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   85650   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   85651   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   85652   Select *pSelect = NULL;      /* Complete SELECT tree */
   85653 
   85654   /* Check that there isn't an ORDER BY without a LIMIT clause.
   85655   */
   85656   if( pOrderBy && (pLimit == 0) ) {
   85657     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   85658     goto limit_where_cleanup_2;
   85659   }
   85660 
   85661   /* We only need to generate a select expression if there
   85662   ** is a limit/offset term to enforce.
   85663   */
   85664   if( pLimit == 0 ) {
   85665     /* if pLimit is null, pOffset will always be null as well. */
   85666     assert( pOffset == 0 );
   85667     return pWhere;
   85668   }
   85669 
   85670   /* Generate a select expression tree to enforce the limit/offset
   85671   ** term for the DELETE or UPDATE statement.  For example:
   85672   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   85673   ** becomes:
   85674   **   DELETE FROM table_a WHERE rowid IN (
   85675   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   85676   **   );
   85677   */
   85678 
   85679   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   85680   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   85681   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   85682   if( pEList == 0 ) goto limit_where_cleanup_2;
   85683 
   85684   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   85685   ** and the SELECT subtree. */
   85686   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   85687   if( pSelectSrc == 0 ) {
   85688     sqlite3ExprListDelete(pParse->db, pEList);
   85689     goto limit_where_cleanup_2;
   85690   }
   85691 
   85692   /* generate the SELECT expression tree. */
   85693   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   85694                              pOrderBy,0,pLimit,pOffset);
   85695   if( pSelect == 0 ) return 0;
   85696 
   85697   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   85698   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   85699   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   85700   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   85701   if( pInClause == 0 ) goto limit_where_cleanup_1;
   85702 
   85703   pInClause->x.pSelect = pSelect;
   85704   pInClause->flags |= EP_xIsSelect;
   85705   sqlite3ExprSetHeight(pParse, pInClause);
   85706   return pInClause;
   85707 
   85708   /* something went wrong. clean up anything allocated. */
   85709 limit_where_cleanup_1:
   85710   sqlite3SelectDelete(pParse->db, pSelect);
   85711   return 0;
   85712 
   85713 limit_where_cleanup_2:
   85714   sqlite3ExprDelete(pParse->db, pWhere);
   85715   sqlite3ExprListDelete(pParse->db, pOrderBy);
   85716   sqlite3ExprDelete(pParse->db, pLimit);
   85717   sqlite3ExprDelete(pParse->db, pOffset);
   85718   return 0;
   85719 }
   85720 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   85721 
   85722 /*
   85723 ** Generate code for a DELETE FROM statement.
   85724 **
   85725 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   85726 **                 \________/       \________________/
   85727 **                  pTabList              pWhere
   85728 */
   85729 SQLITE_PRIVATE void sqlite3DeleteFrom(
   85730   Parse *pParse,         /* The parser context */
   85731   SrcList *pTabList,     /* The table from which we should delete things */
   85732   Expr *pWhere           /* The WHERE clause.  May be null */
   85733 ){
   85734   Vdbe *v;               /* The virtual database engine */
   85735   Table *pTab;           /* The table from which records will be deleted */
   85736   const char *zDb;       /* Name of database holding pTab */
   85737   int end, addr = 0;     /* A couple addresses of generated code */
   85738   int i;                 /* Loop counter */
   85739   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   85740   Index *pIdx;           /* For looping over indices of the table */
   85741   int iCur;              /* VDBE Cursor number for pTab */
   85742   sqlite3 *db;           /* Main database structure */
   85743   AuthContext sContext;  /* Authorization context */
   85744   NameContext sNC;       /* Name context to resolve expressions in */
   85745   int iDb;               /* Database number */
   85746   int memCnt = -1;       /* Memory cell used for change counting */
   85747   int rcauth;            /* Value returned by authorization callback */
   85748 
   85749 #ifndef SQLITE_OMIT_TRIGGER
   85750   int isView;                  /* True if attempting to delete from a view */
   85751   Trigger *pTrigger;           /* List of table triggers, if required */
   85752 #endif
   85753 
   85754   memset(&sContext, 0, sizeof(sContext));
   85755   db = pParse->db;
   85756   if( pParse->nErr || db->mallocFailed ){
   85757     goto delete_from_cleanup;
   85758   }
   85759   assert( pTabList->nSrc==1 );
   85760 
   85761   /* Locate the table which we want to delete.  This table has to be
   85762   ** put in an SrcList structure because some of the subroutines we
   85763   ** will be calling are designed to work with multiple tables and expect
   85764   ** an SrcList* parameter instead of just a Table* parameter.
   85765   */
   85766   pTab = sqlite3SrcListLookup(pParse, pTabList);
   85767   if( pTab==0 )  goto delete_from_cleanup;
   85768 
   85769   /* Figure out if we have any triggers and if the table being
   85770   ** deleted from is a view
   85771   */
   85772 #ifndef SQLITE_OMIT_TRIGGER
   85773   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   85774   isView = pTab->pSelect!=0;
   85775 #else
   85776 # define pTrigger 0
   85777 # define isView 0
   85778 #endif
   85779 #ifdef SQLITE_OMIT_VIEW
   85780 # undef isView
   85781 # define isView 0
   85782 #endif
   85783 
   85784   /* If pTab is really a view, make sure it has been initialized.
   85785   */
   85786   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   85787     goto delete_from_cleanup;
   85788   }
   85789 
   85790   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   85791     goto delete_from_cleanup;
   85792   }
   85793   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   85794   assert( iDb<db->nDb );
   85795   zDb = db->aDb[iDb].zName;
   85796   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   85797   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   85798   if( rcauth==SQLITE_DENY ){
   85799     goto delete_from_cleanup;
   85800   }
   85801   assert(!isView || pTrigger);
   85802 
   85803   /* Assign  cursor number to the table and all its indices.
   85804   */
   85805   assert( pTabList->nSrc==1 );
   85806   iCur = pTabList->a[0].iCursor = pParse->nTab++;
   85807   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   85808     pParse->nTab++;
   85809   }
   85810 
   85811   /* Start the view context
   85812   */
   85813   if( isView ){
   85814     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   85815   }
   85816 
   85817   /* Begin generating code.
   85818   */
   85819   v = sqlite3GetVdbe(pParse);
   85820   if( v==0 ){
   85821     goto delete_from_cleanup;
   85822   }
   85823   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   85824   sqlite3BeginWriteOperation(pParse, 1, iDb);
   85825 
   85826   /* If we are trying to delete from a view, realize that view into
   85827   ** a ephemeral table.
   85828   */
   85829 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   85830   if( isView ){
   85831     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   85832   }
   85833 #endif
   85834 
   85835   /* Resolve the column names in the WHERE clause.
   85836   */
   85837   memset(&sNC, 0, sizeof(sNC));
   85838   sNC.pParse = pParse;
   85839   sNC.pSrcList = pTabList;
   85840   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   85841     goto delete_from_cleanup;
   85842   }
   85843 
   85844   /* Initialize the counter of the number of rows deleted, if
   85845   ** we are counting rows.
   85846   */
   85847   if( db->flags & SQLITE_CountRows ){
   85848     memCnt = ++pParse->nMem;
   85849     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   85850   }
   85851 
   85852 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   85853   /* Special case: A DELETE without a WHERE clause deletes everything.
   85854   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   85855   ** this optimization caused the row change count (the value returned by
   85856   ** API function sqlite3_count_changes) to be set incorrectly.  */
   85857   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   85858    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   85859   ){
   85860     assert( !isView );
   85861     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   85862                       pTab->zName, P4_STATIC);
   85863     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   85864       assert( pIdx->pSchema==pTab->pSchema );
   85865       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   85866     }
   85867   }else
   85868 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   85869   /* The usual case: There is a WHERE clause so we have to scan through
   85870   ** the table and pick which records to delete.
   85871   */
   85872   {
   85873     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
   85874     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
   85875     int regRowid;                   /* Actual register containing rowids */
   85876 
   85877     /* Collect rowids of every row to be deleted.
   85878     */
   85879     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   85880     pWInfo = sqlite3WhereBegin(
   85881         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
   85882     );
   85883     if( pWInfo==0 ) goto delete_from_cleanup;
   85884     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
   85885     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
   85886     if( db->flags & SQLITE_CountRows ){
   85887       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   85888     }
   85889     sqlite3WhereEnd(pWInfo);
   85890 
   85891     /* Delete every item whose key was written to the list during the
   85892     ** database scan.  We have to delete items after the scan is complete
   85893     ** because deleting an item can change the scan order.  */
   85894     end = sqlite3VdbeMakeLabel(v);
   85895 
   85896     /* Unless this is a view, open cursors for the table we are
   85897     ** deleting from and all its indices. If this is a view, then the
   85898     ** only effect this statement has is to fire the INSTEAD OF
   85899     ** triggers.  */
   85900     if( !isView ){
   85901       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
   85902     }
   85903 
   85904     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
   85905 
   85906     /* Delete the row */
   85907 #ifndef SQLITE_OMIT_VIRTUALTABLE
   85908     if( IsVirtual(pTab) ){
   85909       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   85910       sqlite3VtabMakeWritable(pParse, pTab);
   85911       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
   85912       sqlite3VdbeChangeP5(v, OE_Abort);
   85913       sqlite3MayAbort(pParse);
   85914     }else
   85915 #endif
   85916     {
   85917       int count = (pParse->nested==0);    /* True to count changes */
   85918       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
   85919     }
   85920 
   85921     /* End of the delete loop */
   85922     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   85923     sqlite3VdbeResolveLabel(v, end);
   85924 
   85925     /* Close the cursors open on the table and its indexes. */
   85926     if( !isView && !IsVirtual(pTab) ){
   85927       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   85928         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
   85929       }
   85930       sqlite3VdbeAddOp1(v, OP_Close, iCur);
   85931     }
   85932   }
   85933 
   85934   /* Update the sqlite_sequence table by storing the content of the
   85935   ** maximum rowid counter values recorded while inserting into
   85936   ** autoincrement tables.
   85937   */
   85938   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   85939     sqlite3AutoincrementEnd(pParse);
   85940   }
   85941 
   85942   /* Return the number of rows that were deleted. If this routine is
   85943   ** generating code because of a call to sqlite3NestedParse(), do not
   85944   ** invoke the callback function.
   85945   */
   85946   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   85947     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   85948     sqlite3VdbeSetNumCols(v, 1);
   85949     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   85950   }
   85951 
   85952 delete_from_cleanup:
   85953   sqlite3AuthContextPop(&sContext);
   85954   sqlite3SrcListDelete(db, pTabList);
   85955   sqlite3ExprDelete(db, pWhere);
   85956   return;
   85957 }
   85958 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   85959 ** thely may interfere with compilation of other functions in this file
   85960 ** (or in another file, if this file becomes part of the amalgamation).  */
   85961 #ifdef isView
   85962  #undef isView
   85963 #endif
   85964 #ifdef pTrigger
   85965  #undef pTrigger
   85966 #endif
   85967 
   85968 /*
   85969 ** This routine generates VDBE code that causes a single row of a
   85970 ** single table to be deleted.
   85971 **
   85972 ** The VDBE must be in a particular state when this routine is called.
   85973 ** These are the requirements:
   85974 **
   85975 **   1.  A read/write cursor pointing to pTab, the table containing the row
   85976 **       to be deleted, must be opened as cursor number $iCur.
   85977 **
   85978 **   2.  Read/write cursors for all indices of pTab must be open as
   85979 **       cursor number base+i for the i-th index.
   85980 **
   85981 **   3.  The record number of the row to be deleted must be stored in
   85982 **       memory cell iRowid.
   85983 **
   85984 ** This routine generates code to remove both the table record and all
   85985 ** index entries that point to that record.
   85986 */
   85987 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   85988   Parse *pParse,     /* Parsing context */
   85989   Table *pTab,       /* Table containing the row to be deleted */
   85990   int iCur,          /* Cursor number for the table */
   85991   int iRowid,        /* Memory cell that contains the rowid to delete */
   85992   int count,         /* If non-zero, increment the row change counter */
   85993   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   85994   int onconf         /* Default ON CONFLICT policy for triggers */
   85995 ){
   85996   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   85997   int iOld = 0;                   /* First register in OLD.* array */
   85998   int iLabel;                     /* Label resolved to end of generated code */
   85999 
   86000   /* Vdbe is guaranteed to have been allocated by this stage. */
   86001   assert( v );
   86002 
   86003   /* Seek cursor iCur to the row to delete. If this row no longer exists
   86004   ** (this can happen if a trigger program has already deleted it), do
   86005   ** not attempt to delete it or fire any DELETE triggers.  */
   86006   iLabel = sqlite3VdbeMakeLabel(v);
   86007   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   86008 
   86009   /* If there are any triggers to fire, allocate a range of registers to
   86010   ** use for the old.* references in the triggers.  */
   86011   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   86012     u32 mask;                     /* Mask of OLD.* columns in use */
   86013     int iCol;                     /* Iterator used while populating OLD.* */
   86014 
   86015     /* TODO: Could use temporary registers here. Also could attempt to
   86016     ** avoid copying the contents of the rowid register.  */
   86017     mask = sqlite3TriggerColmask(
   86018         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   86019     );
   86020     mask |= sqlite3FkOldmask(pParse, pTab);
   86021     iOld = pParse->nMem+1;
   86022     pParse->nMem += (1 + pTab->nCol);
   86023 
   86024     /* Populate the OLD.* pseudo-table register array. These values will be
   86025     ** used by any BEFORE and AFTER triggers that exist.  */
   86026     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
   86027     for(iCol=0; iCol<pTab->nCol; iCol++){
   86028       if( mask==0xffffffff || mask&(1<<iCol) ){
   86029         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
   86030       }
   86031     }
   86032 
   86033     /* Invoke BEFORE DELETE trigger programs. */
   86034     sqlite3CodeRowTrigger(pParse, pTrigger,
   86035         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   86036     );
   86037 
   86038     /* Seek the cursor to the row to be deleted again. It may be that
   86039     ** the BEFORE triggers coded above have already removed the row
   86040     ** being deleted. Do not attempt to delete the row a second time, and
   86041     ** do not fire AFTER triggers.  */
   86042     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   86043 
   86044     /* Do FK processing. This call checks that any FK constraints that
   86045     ** refer to this table (i.e. constraints attached to other tables)
   86046     ** are not violated by deleting this row.  */
   86047     sqlite3FkCheck(pParse, pTab, iOld, 0);
   86048   }
   86049 
   86050   /* Delete the index and table entries. Skip this step if pTab is really
   86051   ** a view (in which case the only effect of the DELETE statement is to
   86052   ** fire the INSTEAD OF triggers).  */
   86053   if( pTab->pSelect==0 ){
   86054     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
   86055     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
   86056     if( count ){
   86057       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   86058     }
   86059   }
   86060 
   86061   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   86062   ** handle rows (possibly in other tables) that refer via a foreign key
   86063   ** to the row just deleted. */
   86064   sqlite3FkActions(pParse, pTab, 0, iOld);
   86065 
   86066   /* Invoke AFTER DELETE trigger programs. */
   86067   sqlite3CodeRowTrigger(pParse, pTrigger,
   86068       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   86069   );
   86070 
   86071   /* Jump here if the row had already been deleted before any BEFORE
   86072   ** trigger programs were invoked. Or if a trigger program throws a
   86073   ** RAISE(IGNORE) exception.  */
   86074   sqlite3VdbeResolveLabel(v, iLabel);
   86075 }
   86076 
   86077 /*
   86078 ** This routine generates VDBE code that causes the deletion of all
   86079 ** index entries associated with a single row of a single table.
   86080 **
   86081 ** The VDBE must be in a particular state when this routine is called.
   86082 ** These are the requirements:
   86083 **
   86084 **   1.  A read/write cursor pointing to pTab, the table containing the row
   86085 **       to be deleted, must be opened as cursor number "iCur".
   86086 **
   86087 **   2.  Read/write cursors for all indices of pTab must be open as
   86088 **       cursor number iCur+i for the i-th index.
   86089 **
   86090 **   3.  The "iCur" cursor must be pointing to the row that is to be
   86091 **       deleted.
   86092 */
   86093 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   86094   Parse *pParse,     /* Parsing and code generating context */
   86095   Table *pTab,       /* Table containing the row to be deleted */
   86096   int iCur,          /* Cursor number for the table */
   86097   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   86098 ){
   86099   int i;
   86100   Index *pIdx;
   86101   int r1;
   86102 
   86103   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   86104     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
   86105     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
   86106     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
   86107   }
   86108 }
   86109 
   86110 /*
   86111 ** Generate code that will assemble an index key and put it in register
   86112 ** regOut.  The key with be for index pIdx which is an index on pTab.
   86113 ** iCur is the index of a cursor open on the pTab table and pointing to
   86114 ** the entry that needs indexing.
   86115 **
   86116 ** Return a register number which is the first in a block of
   86117 ** registers that holds the elements of the index key.  The
   86118 ** block of registers has already been deallocated by the time
   86119 ** this routine returns.
   86120 */
   86121 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   86122   Parse *pParse,     /* Parsing context */
   86123   Index *pIdx,       /* The index for which to generate a key */
   86124   int iCur,          /* Cursor number for the pIdx->pTable table */
   86125   int regOut,        /* Write the new index key to this register */
   86126   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
   86127 ){
   86128   Vdbe *v = pParse->pVdbe;
   86129   int j;
   86130   Table *pTab = pIdx->pTable;
   86131   int regBase;
   86132   int nCol;
   86133 
   86134   nCol = pIdx->nColumn;
   86135   regBase = sqlite3GetTempRange(pParse, nCol+1);
   86136   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
   86137   for(j=0; j<nCol; j++){
   86138     int idx = pIdx->aiColumn[j];
   86139     if( idx==pTab->iPKey ){
   86140       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
   86141     }else{
   86142       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
   86143       sqlite3ColumnDefault(v, pTab, idx, -1);
   86144     }
   86145   }
   86146   if( doMakeRec ){
   86147     const char *zAff;
   86148     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
   86149       zAff = 0;
   86150     }else{
   86151       zAff = sqlite3IndexAffinityStr(v, pIdx);
   86152     }
   86153     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
   86154     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
   86155   }
   86156   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
   86157   return regBase;
   86158 }
   86159 
   86160 /************** End of delete.c **********************************************/
   86161 /************** Begin file func.c ********************************************/
   86162 /*
   86163 ** 2002 February 23
   86164 **
   86165 ** The author disclaims copyright to this source code.  In place of
   86166 ** a legal notice, here is a blessing:
   86167 **
   86168 **    May you do good and not evil.
   86169 **    May you find forgiveness for yourself and forgive others.
   86170 **    May you share freely, never taking more than you give.
   86171 **
   86172 *************************************************************************
   86173 ** This file contains the C functions that implement various SQL
   86174 ** functions of SQLite.
   86175 **
   86176 ** There is only one exported symbol in this file - the function
   86177 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
   86178 ** All other code has file scope.
   86179 */
   86180 /* #include <stdlib.h> */
   86181 /* #include <assert.h> */
   86182 
   86183 /*
   86184 ** Return the collating function associated with a function.
   86185 */
   86186 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   86187   return context->pColl;
   86188 }
   86189 
   86190 /*
   86191 ** Indicate that the accumulator load should be skipped on this
   86192 ** iteration of the aggregate loop.
   86193 */
   86194 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
   86195   context->skipFlag = 1;
   86196 }
   86197 
   86198 /*
   86199 ** Implementation of the non-aggregate min() and max() functions
   86200 */
   86201 static void minmaxFunc(
   86202   sqlite3_context *context,
   86203   int argc,
   86204   sqlite3_value **argv
   86205 ){
   86206   int i;
   86207   int mask;    /* 0 for min() or 0xffffffff for max() */
   86208   int iBest;
   86209   CollSeq *pColl;
   86210 
   86211   assert( argc>1 );
   86212   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   86213   pColl = sqlite3GetFuncCollSeq(context);
   86214   assert( pColl );
   86215   assert( mask==-1 || mask==0 );
   86216   iBest = 0;
   86217   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   86218   for(i=1; i<argc; i++){
   86219     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   86220     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   86221       testcase( mask==0 );
   86222       iBest = i;
   86223     }
   86224   }
   86225   sqlite3_result_value(context, argv[iBest]);
   86226 }
   86227 
   86228 /*
   86229 ** Return the type of the argument.
   86230 */
   86231 static void typeofFunc(
   86232   sqlite3_context *context,
   86233   int NotUsed,
   86234   sqlite3_value **argv
   86235 ){
   86236   const char *z = 0;
   86237   UNUSED_PARAMETER(NotUsed);
   86238   switch( sqlite3_value_type(argv[0]) ){
   86239     case SQLITE_INTEGER: z = "integer"; break;
   86240     case SQLITE_TEXT:    z = "text";    break;
   86241     case SQLITE_FLOAT:   z = "real";    break;
   86242     case SQLITE_BLOB:    z = "blob";    break;
   86243     default:             z = "null";    break;
   86244   }
   86245   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   86246 }
   86247 
   86248 
   86249 /*
   86250 ** Implementation of the length() function
   86251 */
   86252 static void lengthFunc(
   86253   sqlite3_context *context,
   86254   int argc,
   86255   sqlite3_value **argv
   86256 ){
   86257   int len;
   86258 
   86259   assert( argc==1 );
   86260   UNUSED_PARAMETER(argc);
   86261   switch( sqlite3_value_type(argv[0]) ){
   86262     case SQLITE_BLOB:
   86263     case SQLITE_INTEGER:
   86264     case SQLITE_FLOAT: {
   86265       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   86266       break;
   86267     }
   86268     case SQLITE_TEXT: {
   86269       const unsigned char *z = sqlite3_value_text(argv[0]);
   86270       if( z==0 ) return;
   86271       len = 0;
   86272       while( *z ){
   86273         len++;
   86274         SQLITE_SKIP_UTF8(z);
   86275       }
   86276       sqlite3_result_int(context, len);
   86277       break;
   86278     }
   86279     default: {
   86280       sqlite3_result_null(context);
   86281       break;
   86282     }
   86283   }
   86284 }
   86285 
   86286 /*
   86287 ** Implementation of the abs() function.
   86288 **
   86289 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   86290 ** the numeric argument X.
   86291 */
   86292 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86293   assert( argc==1 );
   86294   UNUSED_PARAMETER(argc);
   86295   switch( sqlite3_value_type(argv[0]) ){
   86296     case SQLITE_INTEGER: {
   86297       i64 iVal = sqlite3_value_int64(argv[0]);
   86298       if( iVal<0 ){
   86299         if( (iVal<<1)==0 ){
   86300           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
   86301           ** abs(X) throws an integer overflow error since there is no
   86302           ** equivalent positive 64-bit two complement value. */
   86303           sqlite3_result_error(context, "integer overflow", -1);
   86304           return;
   86305         }
   86306         iVal = -iVal;
   86307       }
   86308       sqlite3_result_int64(context, iVal);
   86309       break;
   86310     }
   86311     case SQLITE_NULL: {
   86312       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   86313       sqlite3_result_null(context);
   86314       break;
   86315     }
   86316     default: {
   86317       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   86318       ** something that can be converted into a number, we have:
   86319       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   86320       ** cannot be converted to a numeric value.
   86321       */
   86322       double rVal = sqlite3_value_double(argv[0]);
   86323       if( rVal<0 ) rVal = -rVal;
   86324       sqlite3_result_double(context, rVal);
   86325       break;
   86326     }
   86327   }
   86328 }
   86329 
   86330 /*
   86331 ** Implementation of the substr() function.
   86332 **
   86333 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   86334 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   86335 ** of x.  If x is text, then we actually count UTF-8 characters.
   86336 ** If x is a blob, then we count bytes.
   86337 **
   86338 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   86339 **
   86340 ** If p2 is negative, return the p2 characters preceeding p1.
   86341 */
   86342 static void substrFunc(
   86343   sqlite3_context *context,
   86344   int argc,
   86345   sqlite3_value **argv
   86346 ){
   86347   const unsigned char *z;
   86348   const unsigned char *z2;
   86349   int len;
   86350   int p0type;
   86351   i64 p1, p2;
   86352   int negP2 = 0;
   86353 
   86354   assert( argc==3 || argc==2 );
   86355   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   86356    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   86357   ){
   86358     return;
   86359   }
   86360   p0type = sqlite3_value_type(argv[0]);
   86361   p1 = sqlite3_value_int(argv[1]);
   86362   if( p0type==SQLITE_BLOB ){
   86363     len = sqlite3_value_bytes(argv[0]);
   86364     z = sqlite3_value_blob(argv[0]);
   86365     if( z==0 ) return;
   86366     assert( len==sqlite3_value_bytes(argv[0]) );
   86367   }else{
   86368     z = sqlite3_value_text(argv[0]);
   86369     if( z==0 ) return;
   86370     len = 0;
   86371     if( p1<0 ){
   86372       for(z2=z; *z2; len++){
   86373         SQLITE_SKIP_UTF8(z2);
   86374       }
   86375     }
   86376   }
   86377   if( argc==3 ){
   86378     p2 = sqlite3_value_int(argv[2]);
   86379     if( p2<0 ){
   86380       p2 = -p2;
   86381       negP2 = 1;
   86382     }
   86383   }else{
   86384     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   86385   }
   86386   if( p1<0 ){
   86387     p1 += len;
   86388     if( p1<0 ){
   86389       p2 += p1;
   86390       if( p2<0 ) p2 = 0;
   86391       p1 = 0;
   86392     }
   86393   }else if( p1>0 ){
   86394     p1--;
   86395   }else if( p2>0 ){
   86396     p2--;
   86397   }
   86398   if( negP2 ){
   86399     p1 -= p2;
   86400     if( p1<0 ){
   86401       p2 += p1;
   86402       p1 = 0;
   86403     }
   86404   }
   86405   assert( p1>=0 && p2>=0 );
   86406   if( p0type!=SQLITE_BLOB ){
   86407     while( *z && p1 ){
   86408       SQLITE_SKIP_UTF8(z);
   86409       p1--;
   86410     }
   86411     for(z2=z; *z2 && p2; p2--){
   86412       SQLITE_SKIP_UTF8(z2);
   86413     }
   86414     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   86415   }else{
   86416     if( p1+p2>len ){
   86417       p2 = len-p1;
   86418       if( p2<0 ) p2 = 0;
   86419     }
   86420     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   86421   }
   86422 }
   86423 
   86424 /*
   86425 ** Implementation of the round() function
   86426 */
   86427 #ifndef SQLITE_OMIT_FLOATING_POINT
   86428 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86429   int n = 0;
   86430   double r;
   86431   char *zBuf;
   86432   assert( argc==1 || argc==2 );
   86433   if( argc==2 ){
   86434     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   86435     n = sqlite3_value_int(argv[1]);
   86436     if( n>30 ) n = 30;
   86437     if( n<0 ) n = 0;
   86438   }
   86439   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   86440   r = sqlite3_value_double(argv[0]);
   86441   /* If Y==0 and X will fit in a 64-bit int,
   86442   ** handle the rounding directly,
   86443   ** otherwise use printf.
   86444   */
   86445   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   86446     r = (double)((sqlite_int64)(r+0.5));
   86447   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   86448     r = -(double)((sqlite_int64)((-r)+0.5));
   86449   }else{
   86450     zBuf = sqlite3_mprintf("%.*f",n,r);
   86451     if( zBuf==0 ){
   86452       sqlite3_result_error_nomem(context);
   86453       return;
   86454     }
   86455     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   86456     sqlite3_free(zBuf);
   86457   }
   86458   sqlite3_result_double(context, r);
   86459 }
   86460 #endif
   86461 
   86462 /*
   86463 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   86464 ** allocation fails, call sqlite3_result_error_nomem() to notify
   86465 ** the database handle that malloc() has failed and return NULL.
   86466 ** If nByte is larger than the maximum string or blob length, then
   86467 ** raise an SQLITE_TOOBIG exception and return NULL.
   86468 */
   86469 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   86470   char *z;
   86471   sqlite3 *db = sqlite3_context_db_handle(context);
   86472   assert( nByte>0 );
   86473   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   86474   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   86475   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   86476     sqlite3_result_error_toobig(context);
   86477     z = 0;
   86478   }else{
   86479     z = sqlite3Malloc((int)nByte);
   86480     if( !z ){
   86481       sqlite3_result_error_nomem(context);
   86482     }
   86483   }
   86484   return z;
   86485 }
   86486 
   86487 /*
   86488 ** Implementation of the upper() and lower() SQL functions.
   86489 */
   86490 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86491   char *z1;
   86492   const char *z2;
   86493   int i, n;
   86494   UNUSED_PARAMETER(argc);
   86495   z2 = (char*)sqlite3_value_text(argv[0]);
   86496   n = sqlite3_value_bytes(argv[0]);
   86497   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   86498   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   86499   if( z2 ){
   86500     z1 = contextMalloc(context, ((i64)n)+1);
   86501     if( z1 ){
   86502       for(i=0; i<n; i++){
   86503         z1[i] = (char)sqlite3Toupper(z2[i]);
   86504       }
   86505       sqlite3_result_text(context, z1, n, sqlite3_free);
   86506     }
   86507   }
   86508 }
   86509 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86510   char *z1;
   86511   const char *z2;
   86512   int i, n;
   86513   UNUSED_PARAMETER(argc);
   86514   z2 = (char*)sqlite3_value_text(argv[0]);
   86515   n = sqlite3_value_bytes(argv[0]);
   86516   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   86517   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   86518   if( z2 ){
   86519     z1 = contextMalloc(context, ((i64)n)+1);
   86520     if( z1 ){
   86521       for(i=0; i<n; i++){
   86522         z1[i] = sqlite3Tolower(z2[i]);
   86523       }
   86524       sqlite3_result_text(context, z1, n, sqlite3_free);
   86525     }
   86526   }
   86527 }
   86528 
   86529 
   86530 #if 0  /* This function is never used. */
   86531 /*
   86532 ** The COALESCE() and IFNULL() functions used to be implemented as shown
   86533 ** here.  But now they are implemented as VDBE code so that unused arguments
   86534 ** do not have to be computed.  This legacy implementation is retained as
   86535 ** comment.
   86536 */
   86537 /*
   86538 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
   86539 ** All three do the same thing.  They return the first non-NULL
   86540 ** argument.
   86541 */
   86542 static void ifnullFunc(
   86543   sqlite3_context *context,
   86544   int argc,
   86545   sqlite3_value **argv
   86546 ){
   86547   int i;
   86548   for(i=0; i<argc; i++){
   86549     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
   86550       sqlite3_result_value(context, argv[i]);
   86551       break;
   86552     }
   86553   }
   86554 }
   86555 #endif /* NOT USED */
   86556 #define ifnullFunc versionFunc   /* Substitute function - never called */
   86557 
   86558 /*
   86559 ** Implementation of random().  Return a random integer.
   86560 */
   86561 static void randomFunc(
   86562   sqlite3_context *context,
   86563   int NotUsed,
   86564   sqlite3_value **NotUsed2
   86565 ){
   86566   sqlite_int64 r;
   86567   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86568   sqlite3_randomness(sizeof(r), &r);
   86569   if( r<0 ){
   86570     /* We need to prevent a random number of 0x8000000000000000
   86571     ** (or -9223372036854775808) since when you do abs() of that
   86572     ** number of you get the same value back again.  To do this
   86573     ** in a way that is testable, mask the sign bit off of negative
   86574     ** values, resulting in a positive value.  Then take the
   86575     ** 2s complement of that positive value.  The end result can
   86576     ** therefore be no less than -9223372036854775807.
   86577     */
   86578     r = -(r & LARGEST_INT64);
   86579   }
   86580   sqlite3_result_int64(context, r);
   86581 }
   86582 
   86583 /*
   86584 ** Implementation of randomblob(N).  Return a random blob
   86585 ** that is N bytes long.
   86586 */
   86587 static void randomBlob(
   86588   sqlite3_context *context,
   86589   int argc,
   86590   sqlite3_value **argv
   86591 ){
   86592   int n;
   86593   unsigned char *p;
   86594   assert( argc==1 );
   86595   UNUSED_PARAMETER(argc);
   86596   n = sqlite3_value_int(argv[0]);
   86597   if( n<1 ){
   86598     n = 1;
   86599   }
   86600   p = contextMalloc(context, n);
   86601   if( p ){
   86602     sqlite3_randomness(n, p);
   86603     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   86604   }
   86605 }
   86606 
   86607 /*
   86608 ** Implementation of the last_insert_rowid() SQL function.  The return
   86609 ** value is the same as the sqlite3_last_insert_rowid() API function.
   86610 */
   86611 static void last_insert_rowid(
   86612   sqlite3_context *context,
   86613   int NotUsed,
   86614   sqlite3_value **NotUsed2
   86615 ){
   86616   sqlite3 *db = sqlite3_context_db_handle(context);
   86617   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86618   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   86619   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   86620   ** function. */
   86621   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   86622 }
   86623 
   86624 /*
   86625 ** Implementation of the changes() SQL function.
   86626 **
   86627 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   86628 ** around the sqlite3_changes() C/C++ function and hence follows the same
   86629 ** rules for counting changes.
   86630 */
   86631 static void changes(
   86632   sqlite3_context *context,
   86633   int NotUsed,
   86634   sqlite3_value **NotUsed2
   86635 ){
   86636   sqlite3 *db = sqlite3_context_db_handle(context);
   86637   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86638   sqlite3_result_int(context, sqlite3_changes(db));
   86639 }
   86640 
   86641 /*
   86642 ** Implementation of the total_changes() SQL function.  The return value is
   86643 ** the same as the sqlite3_total_changes() API function.
   86644 */
   86645 static void total_changes(
   86646   sqlite3_context *context,
   86647   int NotUsed,
   86648   sqlite3_value **NotUsed2
   86649 ){
   86650   sqlite3 *db = sqlite3_context_db_handle(context);
   86651   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86652   /* IMP: R-52756-41993 This function is a wrapper around the
   86653   ** sqlite3_total_changes() C/C++ interface. */
   86654   sqlite3_result_int(context, sqlite3_total_changes(db));
   86655 }
   86656 
   86657 /*
   86658 ** A structure defining how to do GLOB-style comparisons.
   86659 */
   86660 struct compareInfo {
   86661   u8 matchAll;
   86662   u8 matchOne;
   86663   u8 matchSet;
   86664   u8 noCase;
   86665 };
   86666 
   86667 /*
   86668 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   86669 ** character is exactly one byte in size.  Also, all characters are
   86670 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   86671 ** whereas only characters less than 0x80 do in ASCII.
   86672 */
   86673 #if defined(SQLITE_EBCDIC)
   86674 # define sqlite3Utf8Read(A,C)  (*(A++))
   86675 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
   86676 #else
   86677 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
   86678 #endif
   86679 
   86680 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   86681 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   86682 ** case.  Thus  'a' LIKE 'A' would be true. */
   86683 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   86684 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   86685 ** is case sensitive causing 'a' LIKE 'A' to be false */
   86686 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   86687 
   86688 /*
   86689 ** Compare two UTF-8 strings for equality where the first string can
   86690 ** potentially be a "glob" expression.  Return true (1) if they
   86691 ** are the same and false (0) if they are different.
   86692 **
   86693 ** Globbing rules:
   86694 **
   86695 **      '*'       Matches any sequence of zero or more characters.
   86696 **
   86697 **      '?'       Matches exactly one character.
   86698 **
   86699 **     [...]      Matches one character from the enclosed list of
   86700 **                characters.
   86701 **
   86702 **     [^...]     Matches one character not in the enclosed list.
   86703 **
   86704 ** With the [...] and [^...] matching, a ']' character can be included
   86705 ** in the list by making it the first character after '[' or '^'.  A
   86706 ** range of characters can be specified using '-'.  Example:
   86707 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   86708 ** it the last character in the list.
   86709 **
   86710 ** This routine is usually quick, but can be N**2 in the worst case.
   86711 **
   86712 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   86713 **
   86714 **         abc[*]xyz        Matches "abc*xyz" only
   86715 */
   86716 static int patternCompare(
   86717   const u8 *zPattern,              /* The glob pattern */
   86718   const u8 *zString,               /* The string to compare against the glob */
   86719   const struct compareInfo *pInfo, /* Information about how to do the compare */
   86720   u32 esc                          /* The escape character */
   86721 ){
   86722   u32 c, c2;
   86723   int invert;
   86724   int seen;
   86725   u8 matchOne = pInfo->matchOne;
   86726   u8 matchAll = pInfo->matchAll;
   86727   u8 matchSet = pInfo->matchSet;
   86728   u8 noCase = pInfo->noCase;
   86729   int prevEscape = 0;     /* True if the previous character was 'escape' */
   86730 
   86731   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
   86732     if( !prevEscape && c==matchAll ){
   86733       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
   86734                || c == matchOne ){
   86735         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
   86736           return 0;
   86737         }
   86738       }
   86739       if( c==0 ){
   86740         return 1;
   86741       }else if( c==esc ){
   86742         c = sqlite3Utf8Read(zPattern, &zPattern);
   86743         if( c==0 ){
   86744           return 0;
   86745         }
   86746       }else if( c==matchSet ){
   86747         assert( esc==0 );         /* This is GLOB, not LIKE */
   86748         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   86749         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   86750           SQLITE_SKIP_UTF8(zString);
   86751         }
   86752         return *zString!=0;
   86753       }
   86754       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
   86755         if( noCase ){
   86756           GlogUpperToLower(c2);
   86757           GlogUpperToLower(c);
   86758           while( c2 != 0 && c2 != c ){
   86759             c2 = sqlite3Utf8Read(zString, &zString);
   86760             GlogUpperToLower(c2);
   86761           }
   86762         }else{
   86763           while( c2 != 0 && c2 != c ){
   86764             c2 = sqlite3Utf8Read(zString, &zString);
   86765           }
   86766         }
   86767         if( c2==0 ) return 0;
   86768         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   86769       }
   86770       return 0;
   86771     }else if( !prevEscape && c==matchOne ){
   86772       if( sqlite3Utf8Read(zString, &zString)==0 ){
   86773         return 0;
   86774       }
   86775     }else if( c==matchSet ){
   86776       u32 prior_c = 0;
   86777       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   86778       seen = 0;
   86779       invert = 0;
   86780       c = sqlite3Utf8Read(zString, &zString);
   86781       if( c==0 ) return 0;
   86782       c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86783       if( c2=='^' ){
   86784         invert = 1;
   86785         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86786       }
   86787       if( c2==']' ){
   86788         if( c==']' ) seen = 1;
   86789         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86790       }
   86791       while( c2 && c2!=']' ){
   86792         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   86793           c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86794           if( c>=prior_c && c<=c2 ) seen = 1;
   86795           prior_c = 0;
   86796         }else{
   86797           if( c==c2 ){
   86798             seen = 1;
   86799           }
   86800           prior_c = c2;
   86801         }
   86802         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86803       }
   86804       if( c2==0 || (seen ^ invert)==0 ){
   86805         return 0;
   86806       }
   86807     }else if( esc==c && !prevEscape ){
   86808       prevEscape = 1;
   86809     }else{
   86810       c2 = sqlite3Utf8Read(zString, &zString);
   86811       if( noCase ){
   86812         GlogUpperToLower(c);
   86813         GlogUpperToLower(c2);
   86814       }
   86815       if( c!=c2 ){
   86816         return 0;
   86817       }
   86818       prevEscape = 0;
   86819     }
   86820   }
   86821   return *zString==0;
   86822 }
   86823 
   86824 /*
   86825 ** Count the number of times that the LIKE operator (or GLOB which is
   86826 ** just a variation of LIKE) gets called.  This is used for testing
   86827 ** only.
   86828 */
   86829 #ifdef SQLITE_TEST
   86830 SQLITE_API int sqlite3_like_count = 0;
   86831 #endif
   86832 
   86833 
   86834 /*
   86835 ** Implementation of the like() SQL function.  This function implements
   86836 ** the build-in LIKE operator.  The first argument to the function is the
   86837 ** pattern and the second argument is the string.  So, the SQL statements:
   86838 **
   86839 **       A LIKE B
   86840 **
   86841 ** is implemented as like(B,A).
   86842 **
   86843 ** This same function (with a different compareInfo structure) computes
   86844 ** the GLOB operator.
   86845 */
   86846 static void likeFunc(
   86847   sqlite3_context *context,
   86848   int argc,
   86849   sqlite3_value **argv
   86850 ){
   86851   const unsigned char *zA, *zB;
   86852   u32 escape = 0;
   86853   int nPat;
   86854   sqlite3 *db = sqlite3_context_db_handle(context);
   86855 
   86856   zB = sqlite3_value_text(argv[0]);
   86857   zA = sqlite3_value_text(argv[1]);
   86858 
   86859   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   86860   ** of deep recursion and N*N behavior in patternCompare().
   86861   */
   86862   nPat = sqlite3_value_bytes(argv[0]);
   86863   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   86864   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   86865   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   86866     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   86867     return;
   86868   }
   86869   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   86870 
   86871   if( argc==3 ){
   86872     /* The escape character string must consist of a single UTF-8 character.
   86873     ** Otherwise, return an error.
   86874     */
   86875     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   86876     if( zEsc==0 ) return;
   86877     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   86878       sqlite3_result_error(context,
   86879           "ESCAPE expression must be a single character", -1);
   86880       return;
   86881     }
   86882     escape = sqlite3Utf8Read(zEsc, &zEsc);
   86883   }
   86884   if( zA && zB ){
   86885     struct compareInfo *pInfo = sqlite3_user_data(context);
   86886 #ifdef SQLITE_TEST
   86887     sqlite3_like_count++;
   86888 #endif
   86889 
   86890     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   86891   }
   86892 }
   86893 
   86894 /*
   86895 ** Implementation of the NULLIF(x,y) function.  The result is the first
   86896 ** argument if the arguments are different.  The result is NULL if the
   86897 ** arguments are equal to each other.
   86898 */
   86899 static void nullifFunc(
   86900   sqlite3_context *context,
   86901   int NotUsed,
   86902   sqlite3_value **argv
   86903 ){
   86904   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   86905   UNUSED_PARAMETER(NotUsed);
   86906   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   86907     sqlite3_result_value(context, argv[0]);
   86908   }
   86909 }
   86910 
   86911 /*
   86912 ** Implementation of the sqlite_version() function.  The result is the version
   86913 ** of the SQLite library that is running.
   86914 */
   86915 static void versionFunc(
   86916   sqlite3_context *context,
   86917   int NotUsed,
   86918   sqlite3_value **NotUsed2
   86919 ){
   86920   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86921   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   86922   ** sqlite3_libversion() C-interface. */
   86923   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   86924 }
   86925 
   86926 /*
   86927 ** Implementation of the sqlite_source_id() function. The result is a string
   86928 ** that identifies the particular version of the source code used to build
   86929 ** SQLite.
   86930 */
   86931 static void sourceidFunc(
   86932   sqlite3_context *context,
   86933   int NotUsed,
   86934   sqlite3_value **NotUsed2
   86935 ){
   86936   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86937   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   86938   ** sqlite3_sourceid() C interface. */
   86939   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   86940 }
   86941 
   86942 /*
   86943 ** Implementation of the sqlite_log() function.  This is a wrapper around
   86944 ** sqlite3_log().  The return value is NULL.  The function exists purely for
   86945 ** its side-effects.
   86946 */
   86947 static void errlogFunc(
   86948   sqlite3_context *context,
   86949   int argc,
   86950   sqlite3_value **argv
   86951 ){
   86952   UNUSED_PARAMETER(argc);
   86953   UNUSED_PARAMETER(context);
   86954   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
   86955 }
   86956 
   86957 /*
   86958 ** Implementation of the sqlite_compileoption_used() function.
   86959 ** The result is an integer that identifies if the compiler option
   86960 ** was used to build SQLite.
   86961 */
   86962 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   86963 static void compileoptionusedFunc(
   86964   sqlite3_context *context,
   86965   int argc,
   86966   sqlite3_value **argv
   86967 ){
   86968   const char *zOptName;
   86969   assert( argc==1 );
   86970   UNUSED_PARAMETER(argc);
   86971   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   86972   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   86973   ** function.
   86974   */
   86975   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   86976     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   86977   }
   86978 }
   86979 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   86980 
   86981 /*
   86982 ** Implementation of the sqlite_compileoption_get() function.
   86983 ** The result is a string that identifies the compiler options
   86984 ** used to build SQLite.
   86985 */
   86986 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   86987 static void compileoptiongetFunc(
   86988   sqlite3_context *context,
   86989   int argc,
   86990   sqlite3_value **argv
   86991 ){
   86992   int n;
   86993   assert( argc==1 );
   86994   UNUSED_PARAMETER(argc);
   86995   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   86996   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   86997   */
   86998   n = sqlite3_value_int(argv[0]);
   86999   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   87000 }
   87001 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   87002 
   87003 /* Array for converting from half-bytes (nybbles) into ASCII hex
   87004 ** digits. */
   87005 static const char hexdigits[] = {
   87006   '0', '1', '2', '3', '4', '5', '6', '7',
   87007   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   87008 };
   87009 
   87010 /*
   87011 ** EXPERIMENTAL - This is not an official function.  The interface may
   87012 ** change.  This function may disappear.  Do not write code that depends
   87013 ** on this function.
   87014 **
   87015 ** Implementation of the QUOTE() function.  This function takes a single
   87016 ** argument.  If the argument is numeric, the return value is the same as
   87017 ** the argument.  If the argument is NULL, the return value is the string
   87018 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   87019 ** single-quote escapes.
   87020 */
   87021 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   87022   assert( argc==1 );
   87023   UNUSED_PARAMETER(argc);
   87024   switch( sqlite3_value_type(argv[0]) ){
   87025     case SQLITE_INTEGER:
   87026     case SQLITE_FLOAT: {
   87027       sqlite3_result_value(context, argv[0]);
   87028       break;
   87029     }
   87030     case SQLITE_BLOB: {
   87031       char *zText = 0;
   87032       char const *zBlob = sqlite3_value_blob(argv[0]);
   87033       int nBlob = sqlite3_value_bytes(argv[0]);
   87034       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   87035       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   87036       if( zText ){
   87037         int i;
   87038         for(i=0; i<nBlob; i++){
   87039           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   87040           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   87041         }
   87042         zText[(nBlob*2)+2] = '\'';
   87043         zText[(nBlob*2)+3] = '\0';
   87044         zText[0] = 'X';
   87045         zText[1] = '\'';
   87046         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   87047         sqlite3_free(zText);
   87048       }
   87049       break;
   87050     }
   87051     case SQLITE_TEXT: {
   87052       int i,j;
   87053       u64 n;
   87054       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   87055       char *z;
   87056 
   87057       if( zArg==0 ) return;
   87058       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   87059       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   87060       if( z ){
   87061         z[0] = '\'';
   87062         for(i=0, j=1; zArg[i]; i++){
   87063           z[j++] = zArg[i];
   87064           if( zArg[i]=='\'' ){
   87065             z[j++] = '\'';
   87066           }
   87067         }
   87068         z[j++] = '\'';
   87069         z[j] = 0;
   87070         sqlite3_result_text(context, z, j, sqlite3_free);
   87071       }
   87072       break;
   87073     }
   87074     default: {
   87075       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   87076       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   87077       break;
   87078     }
   87079   }
   87080 }
   87081 
   87082 /*
   87083 ** The hex() function.  Interpret the argument as a blob.  Return
   87084 ** a hexadecimal rendering as text.
   87085 */
   87086 static void hexFunc(
   87087   sqlite3_context *context,
   87088   int argc,
   87089   sqlite3_value **argv
   87090 ){
   87091   int i, n;
   87092   const unsigned char *pBlob;
   87093   char *zHex, *z;
   87094   assert( argc==1 );
   87095   UNUSED_PARAMETER(argc);
   87096   pBlob = sqlite3_value_blob(argv[0]);
   87097   n = sqlite3_value_bytes(argv[0]);
   87098   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   87099   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   87100   if( zHex ){
   87101     for(i=0; i<n; i++, pBlob++){
   87102       unsigned char c = *pBlob;
   87103       *(z++) = hexdigits[(c>>4)&0xf];
   87104       *(z++) = hexdigits[c&0xf];
   87105     }
   87106     *z = 0;
   87107     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   87108   }
   87109 }
   87110 
   87111 /*
   87112 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   87113 */
   87114 static void zeroblobFunc(
   87115   sqlite3_context *context,
   87116   int argc,
   87117   sqlite3_value **argv
   87118 ){
   87119   i64 n;
   87120   sqlite3 *db = sqlite3_context_db_handle(context);
   87121   assert( argc==1 );
   87122   UNUSED_PARAMETER(argc);
   87123   n = sqlite3_value_int64(argv[0]);
   87124   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87125   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   87126   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   87127     sqlite3_result_error_toobig(context);
   87128   }else{
   87129     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
   87130   }
   87131 }
   87132 
   87133 /*
   87134 ** The replace() function.  Three arguments are all strings: call
   87135 ** them A, B, and C. The result is also a string which is derived
   87136 ** from A by replacing every occurance of B with C.  The match
   87137 ** must be exact.  Collating sequences are not used.
   87138 */
   87139 static void replaceFunc(
   87140   sqlite3_context *context,
   87141   int argc,
   87142   sqlite3_value **argv
   87143 ){
   87144   const unsigned char *zStr;        /* The input string A */
   87145   const unsigned char *zPattern;    /* The pattern string B */
   87146   const unsigned char *zRep;        /* The replacement string C */
   87147   unsigned char *zOut;              /* The output */
   87148   int nStr;                /* Size of zStr */
   87149   int nPattern;            /* Size of zPattern */
   87150   int nRep;                /* Size of zRep */
   87151   i64 nOut;                /* Maximum size of zOut */
   87152   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   87153   int i, j;                /* Loop counters */
   87154 
   87155   assert( argc==3 );
   87156   UNUSED_PARAMETER(argc);
   87157   zStr = sqlite3_value_text(argv[0]);
   87158   if( zStr==0 ) return;
   87159   nStr = sqlite3_value_bytes(argv[0]);
   87160   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   87161   zPattern = sqlite3_value_text(argv[1]);
   87162   if( zPattern==0 ){
   87163     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   87164             || sqlite3_context_db_handle(context)->mallocFailed );
   87165     return;
   87166   }
   87167   if( zPattern[0]==0 ){
   87168     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   87169     sqlite3_result_value(context, argv[0]);
   87170     return;
   87171   }
   87172   nPattern = sqlite3_value_bytes(argv[1]);
   87173   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   87174   zRep = sqlite3_value_text(argv[2]);
   87175   if( zRep==0 ) return;
   87176   nRep = sqlite3_value_bytes(argv[2]);
   87177   assert( zRep==sqlite3_value_text(argv[2]) );
   87178   nOut = nStr + 1;
   87179   assert( nOut<SQLITE_MAX_LENGTH );
   87180   zOut = contextMalloc(context, (i64)nOut);
   87181   if( zOut==0 ){
   87182     return;
   87183   }
   87184   loopLimit = nStr - nPattern;
   87185   for(i=j=0; i<=loopLimit; i++){
   87186     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   87187       zOut[j++] = zStr[i];
   87188     }else{
   87189       u8 *zOld;
   87190       sqlite3 *db = sqlite3_context_db_handle(context);
   87191       nOut += nRep - nPattern;
   87192       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87193       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87194       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   87195         sqlite3_result_error_toobig(context);
   87196         sqlite3_free(zOut);
   87197         return;
   87198       }
   87199       zOld = zOut;
   87200       zOut = sqlite3_realloc(zOut, (int)nOut);
   87201       if( zOut==0 ){
   87202         sqlite3_result_error_nomem(context);
   87203         sqlite3_free(zOld);
   87204         return;
   87205       }
   87206       memcpy(&zOut[j], zRep, nRep);
   87207       j += nRep;
   87208       i += nPattern-1;
   87209     }
   87210   }
   87211   assert( j+nStr-i+1==nOut );
   87212   memcpy(&zOut[j], &zStr[i], nStr-i);
   87213   j += nStr - i;
   87214   assert( j<=nOut );
   87215   zOut[j] = 0;
   87216   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   87217 }
   87218 
   87219 /*
   87220 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   87221 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   87222 */
   87223 static void trimFunc(
   87224   sqlite3_context *context,
   87225   int argc,
   87226   sqlite3_value **argv
   87227 ){
   87228   const unsigned char *zIn;         /* Input string */
   87229   const unsigned char *zCharSet;    /* Set of characters to trim */
   87230   int nIn;                          /* Number of bytes in input */
   87231   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   87232   int i;                            /* Loop counter */
   87233   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   87234   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   87235   int nChar;                        /* Number of characters in zCharSet */
   87236 
   87237   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   87238     return;
   87239   }
   87240   zIn = sqlite3_value_text(argv[0]);
   87241   if( zIn==0 ) return;
   87242   nIn = sqlite3_value_bytes(argv[0]);
   87243   assert( zIn==sqlite3_value_text(argv[0]) );
   87244   if( argc==1 ){
   87245     static const unsigned char lenOne[] = { 1 };
   87246     static unsigned char * const azOne[] = { (u8*)" " };
   87247     nChar = 1;
   87248     aLen = (u8*)lenOne;
   87249     azChar = (unsigned char **)azOne;
   87250     zCharSet = 0;
   87251   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   87252     return;
   87253   }else{
   87254     const unsigned char *z;
   87255     for(z=zCharSet, nChar=0; *z; nChar++){
   87256       SQLITE_SKIP_UTF8(z);
   87257     }
   87258     if( nChar>0 ){
   87259       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   87260       if( azChar==0 ){
   87261         return;
   87262       }
   87263       aLen = (unsigned char*)&azChar[nChar];
   87264       for(z=zCharSet, nChar=0; *z; nChar++){
   87265         azChar[nChar] = (unsigned char *)z;
   87266         SQLITE_SKIP_UTF8(z);
   87267         aLen[nChar] = (u8)(z - azChar[nChar]);
   87268       }
   87269     }
   87270   }
   87271   if( nChar>0 ){
   87272     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   87273     if( flags & 1 ){
   87274       while( nIn>0 ){
   87275         int len = 0;
   87276         for(i=0; i<nChar; i++){
   87277           len = aLen[i];
   87278           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   87279         }
   87280         if( i>=nChar ) break;
   87281         zIn += len;
   87282         nIn -= len;
   87283       }
   87284     }
   87285     if( flags & 2 ){
   87286       while( nIn>0 ){
   87287         int len = 0;
   87288         for(i=0; i<nChar; i++){
   87289           len = aLen[i];
   87290           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   87291         }
   87292         if( i>=nChar ) break;
   87293         nIn -= len;
   87294       }
   87295     }
   87296     if( zCharSet ){
   87297       sqlite3_free(azChar);
   87298     }
   87299   }
   87300   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   87301 }
   87302 
   87303 
   87304 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   87305 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   87306 ** when SQLite is built.
   87307 */
   87308 #ifdef SQLITE_SOUNDEX
   87309 /*
   87310 ** Compute the soundex encoding of a word.
   87311 **
   87312 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   87313 ** soundex encoding of the string X.
   87314 */
   87315 static void soundexFunc(
   87316   sqlite3_context *context,
   87317   int argc,
   87318   sqlite3_value **argv
   87319 ){
   87320   char zResult[8];
   87321   const u8 *zIn;
   87322   int i, j;
   87323   static const unsigned char iCode[] = {
   87324     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87325     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87326     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87327     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87328     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   87329     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   87330     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   87331     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   87332   };
   87333   assert( argc==1 );
   87334   zIn = (u8*)sqlite3_value_text(argv[0]);
   87335   if( zIn==0 ) zIn = (u8*)"";
   87336   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   87337   if( zIn[i] ){
   87338     u8 prevcode = iCode[zIn[i]&0x7f];
   87339     zResult[0] = sqlite3Toupper(zIn[i]);
   87340     for(j=1; j<4 && zIn[i]; i++){
   87341       int code = iCode[zIn[i]&0x7f];
   87342       if( code>0 ){
   87343         if( code!=prevcode ){
   87344           prevcode = code;
   87345           zResult[j++] = code + '0';
   87346         }
   87347       }else{
   87348         prevcode = 0;
   87349       }
   87350     }
   87351     while( j<4 ){
   87352       zResult[j++] = '0';
   87353     }
   87354     zResult[j] = 0;
   87355     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   87356   }else{
   87357     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   87358     ** is NULL or contains no ASCII alphabetic characters. */
   87359     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   87360   }
   87361 }
   87362 #endif /* SQLITE_SOUNDEX */
   87363 
   87364 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   87365 /*
   87366 ** A function that loads a shared-library extension then returns NULL.
   87367 */
   87368 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   87369   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   87370   const char *zProc;
   87371   sqlite3 *db = sqlite3_context_db_handle(context);
   87372   char *zErrMsg = 0;
   87373 
   87374   if( argc==2 ){
   87375     zProc = (const char *)sqlite3_value_text(argv[1]);
   87376   }else{
   87377     zProc = 0;
   87378   }
   87379   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   87380     sqlite3_result_error(context, zErrMsg, -1);
   87381     sqlite3_free(zErrMsg);
   87382   }
   87383 }
   87384 #endif
   87385 
   87386 
   87387 /*
   87388 ** An instance of the following structure holds the context of a
   87389 ** sum() or avg() aggregate computation.
   87390 */
   87391 typedef struct SumCtx SumCtx;
   87392 struct SumCtx {
   87393   double rSum;      /* Floating point sum */
   87394   i64 iSum;         /* Integer sum */
   87395   i64 cnt;          /* Number of elements summed */
   87396   u8 overflow;      /* True if integer overflow seen */
   87397   u8 approx;        /* True if non-integer value was input to the sum */
   87398 };
   87399 
   87400 /*
   87401 ** Routines used to compute the sum, average, and total.
   87402 **
   87403 ** The SUM() function follows the (broken) SQL standard which means
   87404 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   87405 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   87406 ** SUM might return an integer if it never encounters a floating point
   87407 ** value.  TOTAL never fails, but SUM might through an exception if
   87408 ** it overflows an integer.
   87409 */
   87410 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   87411   SumCtx *p;
   87412   int type;
   87413   assert( argc==1 );
   87414   UNUSED_PARAMETER(argc);
   87415   p = sqlite3_aggregate_context(context, sizeof(*p));
   87416   type = sqlite3_value_numeric_type(argv[0]);
   87417   if( p && type!=SQLITE_NULL ){
   87418     p->cnt++;
   87419     if( type==SQLITE_INTEGER ){
   87420       i64 v = sqlite3_value_int64(argv[0]);
   87421       p->rSum += v;
   87422       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
   87423         p->overflow = 1;
   87424       }
   87425     }else{
   87426       p->rSum += sqlite3_value_double(argv[0]);
   87427       p->approx = 1;
   87428     }
   87429   }
   87430 }
   87431 static void sumFinalize(sqlite3_context *context){
   87432   SumCtx *p;
   87433   p = sqlite3_aggregate_context(context, 0);
   87434   if( p && p->cnt>0 ){
   87435     if( p->overflow ){
   87436       sqlite3_result_error(context,"integer overflow",-1);
   87437     }else if( p->approx ){
   87438       sqlite3_result_double(context, p->rSum);
   87439     }else{
   87440       sqlite3_result_int64(context, p->iSum);
   87441     }
   87442   }
   87443 }
   87444 static void avgFinalize(sqlite3_context *context){
   87445   SumCtx *p;
   87446   p = sqlite3_aggregate_context(context, 0);
   87447   if( p && p->cnt>0 ){
   87448     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   87449   }
   87450 }
   87451 static void totalFinalize(sqlite3_context *context){
   87452   SumCtx *p;
   87453   p = sqlite3_aggregate_context(context, 0);
   87454   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   87455   sqlite3_result_double(context, p ? p->rSum : (double)0);
   87456 }
   87457 
   87458 /*
   87459 ** The following structure keeps track of state information for the
   87460 ** count() aggregate function.
   87461 */
   87462 typedef struct CountCtx CountCtx;
   87463 struct CountCtx {
   87464   i64 n;
   87465 };
   87466 
   87467 /*
   87468 ** Routines to implement the count() aggregate function.
   87469 */
   87470 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   87471   CountCtx *p;
   87472   p = sqlite3_aggregate_context(context, sizeof(*p));
   87473   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   87474     p->n++;
   87475   }
   87476 
   87477 #ifndef SQLITE_OMIT_DEPRECATED
   87478   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   87479   ** sure it still operates correctly, verify that its count agrees with our
   87480   ** internal count when using count(*) and when the total count can be
   87481   ** expressed as a 32-bit integer. */
   87482   assert( argc==1 || p==0 || p->n>0x7fffffff
   87483           || p->n==sqlite3_aggregate_count(context) );
   87484 #endif
   87485 }
   87486 static void countFinalize(sqlite3_context *context){
   87487   CountCtx *p;
   87488   p = sqlite3_aggregate_context(context, 0);
   87489   sqlite3_result_int64(context, p ? p->n : 0);
   87490 }
   87491 
   87492 /*
   87493 ** Routines to implement min() and max() aggregate functions.
   87494 */
   87495 static void minmaxStep(
   87496   sqlite3_context *context,
   87497   int NotUsed,
   87498   sqlite3_value **argv
   87499 ){
   87500   Mem *pArg  = (Mem *)argv[0];
   87501   Mem *pBest;
   87502   UNUSED_PARAMETER(NotUsed);
   87503 
   87504   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   87505   if( !pBest ) return;
   87506 
   87507   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   87508     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
   87509   }else if( pBest->flags ){
   87510     int max;
   87511     int cmp;
   87512     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   87513     /* This step function is used for both the min() and max() aggregates,
   87514     ** the only difference between the two being that the sense of the
   87515     ** comparison is inverted. For the max() aggregate, the
   87516     ** sqlite3_user_data() function returns (void *)-1. For min() it
   87517     ** returns (void *)db, where db is the sqlite3* database pointer.
   87518     ** Therefore the next statement sets variable 'max' to 1 for the max()
   87519     ** aggregate, or 0 for min().
   87520     */
   87521     max = sqlite3_user_data(context)!=0;
   87522     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   87523     if( (max && cmp<0) || (!max && cmp>0) ){
   87524       sqlite3VdbeMemCopy(pBest, pArg);
   87525     }else{
   87526       sqlite3SkipAccumulatorLoad(context);
   87527     }
   87528   }else{
   87529     sqlite3VdbeMemCopy(pBest, pArg);
   87530   }
   87531 }
   87532 static void minMaxFinalize(sqlite3_context *context){
   87533   sqlite3_value *pRes;
   87534   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   87535   if( pRes ){
   87536     if( pRes->flags ){
   87537       sqlite3_result_value(context, pRes);
   87538     }
   87539     sqlite3VdbeMemRelease(pRes);
   87540   }
   87541 }
   87542 
   87543 /*
   87544 ** group_concat(EXPR, ?SEPARATOR?)
   87545 */
   87546 static void groupConcatStep(
   87547   sqlite3_context *context,
   87548   int argc,
   87549   sqlite3_value **argv
   87550 ){
   87551   const char *zVal;
   87552   StrAccum *pAccum;
   87553   const char *zSep;
   87554   int nVal, nSep;
   87555   assert( argc==1 || argc==2 );
   87556   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   87557   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   87558 
   87559   if( pAccum ){
   87560     sqlite3 *db = sqlite3_context_db_handle(context);
   87561     int firstTerm = pAccum->useMalloc==0;
   87562     pAccum->useMalloc = 2;
   87563     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   87564     if( !firstTerm ){
   87565       if( argc==2 ){
   87566         zSep = (char*)sqlite3_value_text(argv[1]);
   87567         nSep = sqlite3_value_bytes(argv[1]);
   87568       }else{
   87569         zSep = ",";
   87570         nSep = 1;
   87571       }
   87572       sqlite3StrAccumAppend(pAccum, zSep, nSep);
   87573     }
   87574     zVal = (char*)sqlite3_value_text(argv[0]);
   87575     nVal = sqlite3_value_bytes(argv[0]);
   87576     sqlite3StrAccumAppend(pAccum, zVal, nVal);
   87577   }
   87578 }
   87579 static void groupConcatFinalize(sqlite3_context *context){
   87580   StrAccum *pAccum;
   87581   pAccum = sqlite3_aggregate_context(context, 0);
   87582   if( pAccum ){
   87583     if( pAccum->tooBig ){
   87584       sqlite3_result_error_toobig(context);
   87585     }else if( pAccum->mallocFailed ){
   87586       sqlite3_result_error_nomem(context);
   87587     }else{
   87588       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   87589                           sqlite3_free);
   87590     }
   87591   }
   87592 }
   87593 
   87594 /*
   87595 ** This routine does per-connection function registration.  Most
   87596 ** of the built-in functions above are part of the global function set.
   87597 ** This routine only deals with those that are not global.
   87598 */
   87599 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   87600   int rc = sqlite3_overload_function(db, "MATCH", 2);
   87601   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   87602   if( rc==SQLITE_NOMEM ){
   87603     db->mallocFailed = 1;
   87604   }
   87605 }
   87606 
   87607 /*
   87608 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   87609 */
   87610 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   87611   FuncDef *pDef;
   87612   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   87613                              2, SQLITE_UTF8, 0);
   87614   if( ALWAYS(pDef) ){
   87615     pDef->flags = flagVal;
   87616   }
   87617 }
   87618 
   87619 /*
   87620 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   87621 ** parameter determines whether or not the LIKE operator is case
   87622 ** sensitive.  GLOB is always case sensitive.
   87623 */
   87624 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   87625   struct compareInfo *pInfo;
   87626   if( caseSensitive ){
   87627     pInfo = (struct compareInfo*)&likeInfoAlt;
   87628   }else{
   87629     pInfo = (struct compareInfo*)&likeInfoNorm;
   87630   }
   87631   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   87632   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   87633   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
   87634       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   87635   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   87636   setLikeOptFlag(db, "like",
   87637       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   87638 }
   87639 
   87640 /*
   87641 ** pExpr points to an expression which implements a function.  If
   87642 ** it is appropriate to apply the LIKE optimization to that function
   87643 ** then set aWc[0] through aWc[2] to the wildcard characters and
   87644 ** return TRUE.  If the function is not a LIKE-style function then
   87645 ** return FALSE.
   87646 */
   87647 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   87648   FuncDef *pDef;
   87649   if( pExpr->op!=TK_FUNCTION
   87650    || !pExpr->x.pList
   87651    || pExpr->x.pList->nExpr!=2
   87652   ){
   87653     return 0;
   87654   }
   87655   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   87656   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   87657                              sqlite3Strlen30(pExpr->u.zToken),
   87658                              2, SQLITE_UTF8, 0);
   87659   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
   87660     return 0;
   87661   }
   87662 
   87663   /* The memcpy() statement assumes that the wildcard characters are
   87664   ** the first three statements in the compareInfo structure.  The
   87665   ** asserts() that follow verify that assumption
   87666   */
   87667   memcpy(aWc, pDef->pUserData, 3);
   87668   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   87669   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   87670   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   87671   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
   87672   return 1;
   87673 }
   87674 
   87675 /*
   87676 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   87677 ** to the global function hash table.  This occurs at start-time (as
   87678 ** a consequence of calling sqlite3_initialize()).
   87679 **
   87680 ** After this routine runs
   87681 */
   87682 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   87683   /*
   87684   ** The following array holds FuncDef structures for all of the functions
   87685   ** defined in this file.
   87686   **
   87687   ** The array cannot be constant since changes are made to the
   87688   ** FuncDef.pHash elements at start-time.  The elements of this array
   87689   ** are read-only after initialization is complete.
   87690   */
   87691   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   87692     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   87693     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   87694     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   87695     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   87696     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   87697     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   87698     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   87699     FUNCTION(min,                0, 0, 1, 0                ),
   87700     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   87701     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   87702     FUNCTION(max,                0, 1, 1, 0                ),
   87703     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   87704     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
   87705     FUNCTION(length,             1, 0, 0, lengthFunc       ),
   87706     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   87707     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   87708     FUNCTION(abs,                1, 0, 0, absFunc          ),
   87709 #ifndef SQLITE_OMIT_FLOATING_POINT
   87710     FUNCTION(round,              1, 0, 0, roundFunc        ),
   87711     FUNCTION(round,              2, 0, 0, roundFunc        ),
   87712 #endif
   87713     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   87714     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   87715     FUNCTION(coalesce,           1, 0, 0, 0                ),
   87716     FUNCTION(coalesce,           0, 0, 0, 0                ),
   87717 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
   87718     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
   87719     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   87720 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
   87721     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
   87722     FUNCTION(random,             0, 0, 0, randomFunc       ),
   87723     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
   87724     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   87725     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   87726     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   87727     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
   87728 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   87729     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   87730     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   87731 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   87732     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   87733     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
   87734     FUNCTION(changes,            0, 0, 0, changes          ),
   87735     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
   87736     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   87737     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   87738   #ifdef SQLITE_SOUNDEX
   87739     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   87740   #endif
   87741   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   87742     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   87743     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   87744   #endif
   87745     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   87746     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   87747     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   87748  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   87749     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
   87750     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   87751     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   87752     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   87753 
   87754     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87755   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   87756     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87757     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87758   #else
   87759     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   87760     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   87761   #endif
   87762   };
   87763 
   87764   int i;
   87765   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   87766   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   87767 
   87768   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   87769     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   87770   }
   87771   sqlite3RegisterDateTimeFunctions();
   87772 #ifndef SQLITE_OMIT_ALTERTABLE
   87773   sqlite3AlterFunctions();
   87774 #endif
   87775 }
   87776 
   87777 /************** End of func.c ************************************************/
   87778 /************** Begin file fkey.c ********************************************/
   87779 /*
   87780 **
   87781 ** The author disclaims copyright to this source code.  In place of
   87782 ** a legal notice, here is a blessing:
   87783 **
   87784 **    May you do good and not evil.
   87785 **    May you find forgiveness for yourself and forgive others.
   87786 **    May you share freely, never taking more than you give.
   87787 **
   87788 *************************************************************************
   87789 ** This file contains code used by the compiler to add foreign key
   87790 ** support to compiled SQL statements.
   87791 */
   87792 
   87793 #ifndef SQLITE_OMIT_FOREIGN_KEY
   87794 #ifndef SQLITE_OMIT_TRIGGER
   87795 
   87796 /*
   87797 ** Deferred and Immediate FKs
   87798 ** --------------------------
   87799 **
   87800 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   87801 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
   87802 ** is returned and the current statement transaction rolled back. If a
   87803 ** deferred foreign key constraint is violated, no action is taken
   87804 ** immediately. However if the application attempts to commit the
   87805 ** transaction before fixing the constraint violation, the attempt fails.
   87806 **
   87807 ** Deferred constraints are implemented using a simple counter associated
   87808 ** with the database handle. The counter is set to zero each time a
   87809 ** database transaction is opened. Each time a statement is executed
   87810 ** that causes a foreign key violation, the counter is incremented. Each
   87811 ** time a statement is executed that removes an existing violation from
   87812 ** the database, the counter is decremented. When the transaction is
   87813 ** committed, the commit fails if the current value of the counter is
   87814 ** greater than zero. This scheme has two big drawbacks:
   87815 **
   87816 **   * When a commit fails due to a deferred foreign key constraint,
   87817 **     there is no way to tell which foreign constraint is not satisfied,
   87818 **     or which row it is not satisfied for.
   87819 **
   87820 **   * If the database contains foreign key violations when the
   87821 **     transaction is opened, this may cause the mechanism to malfunction.
   87822 **
   87823 ** Despite these problems, this approach is adopted as it seems simpler
   87824 ** than the alternatives.
   87825 **
   87826 ** INSERT operations:
   87827 **
   87828 **   I.1) For each FK for which the table is the child table, search
   87829 **        the parent table for a match. If none is found increment the
   87830 **        constraint counter.
   87831 **
   87832 **   I.2) For each FK for which the table is the parent table,
   87833 **        search the child table for rows that correspond to the new
   87834 **        row in the parent table. Decrement the counter for each row
   87835 **        found (as the constraint is now satisfied).
   87836 **
   87837 ** DELETE operations:
   87838 **
   87839 **   D.1) For each FK for which the table is the child table,
   87840 **        search the parent table for a row that corresponds to the
   87841 **        deleted row in the child table. If such a row is not found,
   87842 **        decrement the counter.
   87843 **
   87844 **   D.2) For each FK for which the table is the parent table, search
   87845 **        the child table for rows that correspond to the deleted row
   87846 **        in the parent table. For each found increment the counter.
   87847 **
   87848 ** UPDATE operations:
   87849 **
   87850 **   An UPDATE command requires that all 4 steps above are taken, but only
   87851 **   for FK constraints for which the affected columns are actually
   87852 **   modified (values must be compared at runtime).
   87853 **
   87854 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   87855 ** This simplifies the implementation a bit.
   87856 **
   87857 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   87858 ** resolution is considered to delete rows before the new row is inserted.
   87859 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   87860 ** is thrown, even if the FK constraint would be satisfied after the new
   87861 ** row is inserted.
   87862 **
   87863 ** Immediate constraints are usually handled similarly. The only difference
   87864 ** is that the counter used is stored as part of each individual statement
   87865 ** object (struct Vdbe). If, after the statement has run, its immediate
   87866 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
   87867 ** and the statement transaction is rolled back. An exception is an INSERT
   87868 ** statement that inserts a single row only (no triggers). In this case,
   87869 ** instead of using a counter, an exception is thrown immediately if the
   87870 ** INSERT violates a foreign key constraint. This is necessary as such
   87871 ** an INSERT does not open a statement transaction.
   87872 **
   87873 ** TODO: How should dropping a table be handled? How should renaming a
   87874 ** table be handled?
   87875 **
   87876 **
   87877 ** Query API Notes
   87878 ** ---------------
   87879 **
   87880 ** Before coding an UPDATE or DELETE row operation, the code-generator
   87881 ** for those two operations needs to know whether or not the operation
   87882 ** requires any FK processing and, if so, which columns of the original
   87883 ** row are required by the FK processing VDBE code (i.e. if FKs were
   87884 ** implemented using triggers, which of the old.* columns would be
   87885 ** accessed). No information is required by the code-generator before
   87886 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   87887 ** generation code to query for this information are:
   87888 **
   87889 **   sqlite3FkRequired() - Test to see if FK processing is required.
   87890 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   87891 **
   87892 **
   87893 ** Externally accessible module functions
   87894 ** --------------------------------------
   87895 **
   87896 **   sqlite3FkCheck()    - Check for foreign key violations.
   87897 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   87898 **   sqlite3FkDelete()   - Delete an FKey structure.
   87899 */
   87900 
   87901 /*
   87902 ** VDBE Calling Convention
   87903 ** -----------------------
   87904 **
   87905 ** Example:
   87906 **
   87907 **   For the following INSERT statement:
   87908 **
   87909 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   87910 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   87911 **
   87912 **   Register (x):        2    (type integer)
   87913 **   Register (x+1):      1    (type integer)
   87914 **   Register (x+2):      NULL (type NULL)
   87915 **   Register (x+3):      3.1  (type real)
   87916 */
   87917 
   87918 /*
   87919 ** A foreign key constraint requires that the key columns in the parent
   87920 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   87921 ** Given that pParent is the parent table for foreign key constraint pFKey,
   87922 ** search the schema a unique index on the parent key columns.
   87923 **
   87924 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   87925 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   87926 ** is set to point to the unique index.
   87927 **
   87928 ** If the parent key consists of a single column (the foreign key constraint
   87929 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   87930 ** Otherwise, it is set to point to an allocated array of size N, where
   87931 ** N is the number of columns in the parent key. The first element of the
   87932 ** array is the index of the child table column that is mapped by the FK
   87933 ** constraint to the parent table column stored in the left-most column
   87934 ** of index *ppIdx. The second element of the array is the index of the
   87935 ** child table column that corresponds to the second left-most column of
   87936 ** *ppIdx, and so on.
   87937 **
   87938 ** If the required index cannot be found, either because:
   87939 **
   87940 **   1) The named parent key columns do not exist, or
   87941 **
   87942 **   2) The named parent key columns do exist, but are not subject to a
   87943 **      UNIQUE or PRIMARY KEY constraint, or
   87944 **
   87945 **   3) No parent key columns were provided explicitly as part of the
   87946 **      foreign key definition, and the parent table does not have a
   87947 **      PRIMARY KEY, or
   87948 **
   87949 **   4) No parent key columns were provided explicitly as part of the
   87950 **      foreign key definition, and the PRIMARY KEY of the parent table
   87951 **      consists of a a different number of columns to the child key in
   87952 **      the child table.
   87953 **
   87954 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   87955 ** into pParse. If an OOM error occurs, non-zero is returned and the
   87956 ** pParse->db->mallocFailed flag is set.
   87957 */
   87958 static int locateFkeyIndex(
   87959   Parse *pParse,                  /* Parse context to store any error in */
   87960   Table *pParent,                 /* Parent table of FK constraint pFKey */
   87961   FKey *pFKey,                    /* Foreign key to find index for */
   87962   Index **ppIdx,                  /* OUT: Unique index on parent table */
   87963   int **paiCol                    /* OUT: Map of index columns in pFKey */
   87964 ){
   87965   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   87966   int *aiCol = 0;                     /* Value to return via *paiCol */
   87967   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   87968   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   87969 
   87970   /* The caller is responsible for zeroing output parameters. */
   87971   assert( ppIdx && *ppIdx==0 );
   87972   assert( !paiCol || *paiCol==0 );
   87973   assert( pParse );
   87974 
   87975   /* If this is a non-composite (single column) foreign key, check if it
   87976   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   87977   ** and *paiCol set to zero and return early.
   87978   **
   87979   ** Otherwise, for a composite foreign key (more than one column), allocate
   87980   ** space for the aiCol array (returned via output parameter *paiCol).
   87981   ** Non-composite foreign keys do not require the aiCol array.
   87982   */
   87983   if( nCol==1 ){
   87984     /* The FK maps to the IPK if any of the following are true:
   87985     **
   87986     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   87987     **      mapped to the primary key of table pParent, or
   87988     **   2) The FK is explicitly mapped to a column declared as INTEGER
   87989     **      PRIMARY KEY.
   87990     */
   87991     if( pParent->iPKey>=0 ){
   87992       if( !zKey ) return 0;
   87993       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   87994     }
   87995   }else if( paiCol ){
   87996     assert( nCol>1 );
   87997     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   87998     if( !aiCol ) return 1;
   87999     *paiCol = aiCol;
   88000   }
   88001 
   88002   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   88003     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
   88004       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   88005       ** of columns. If each indexed column corresponds to a foreign key
   88006       ** column of pFKey, then this index is a winner.  */
   88007 
   88008       if( zKey==0 ){
   88009         /* If zKey is NULL, then this foreign key is implicitly mapped to
   88010         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   88011         ** identified by the test (Index.autoIndex==2).  */
   88012         if( pIdx->autoIndex==2 ){
   88013           if( aiCol ){
   88014             int i;
   88015             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   88016           }
   88017           break;
   88018         }
   88019       }else{
   88020         /* If zKey is non-NULL, then this foreign key was declared to
   88021         ** map to an explicit list of columns in table pParent. Check if this
   88022         ** index matches those columns. Also, check that the index uses
   88023         ** the default collation sequences for each column. */
   88024         int i, j;
   88025         for(i=0; i<nCol; i++){
   88026           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   88027           char *zDfltColl;                  /* Def. collation for column */
   88028           char *zIdxCol;                    /* Name of indexed column */
   88029 
   88030           /* If the index uses a collation sequence that is different from
   88031           ** the default collation sequence for the column, this index is
   88032           ** unusable. Bail out early in this case.  */
   88033           zDfltColl = pParent->aCol[iCol].zColl;
   88034           if( !zDfltColl ){
   88035             zDfltColl = "BINARY";
   88036           }
   88037           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   88038 
   88039           zIdxCol = pParent->aCol[iCol].zName;
   88040           for(j=0; j<nCol; j++){
   88041             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   88042               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   88043               break;
   88044             }
   88045           }
   88046           if( j==nCol ) break;
   88047         }
   88048         if( i==nCol ) break;      /* pIdx is usable */
   88049       }
   88050     }
   88051   }
   88052 
   88053   if( !pIdx ){
   88054     if( !pParse->disableTriggers ){
   88055       sqlite3ErrorMsg(pParse, "foreign key mismatch");
   88056     }
   88057     sqlite3DbFree(pParse->db, aiCol);
   88058     return 1;
   88059   }
   88060 
   88061   *ppIdx = pIdx;
   88062   return 0;
   88063 }
   88064 
   88065 /*
   88066 ** This function is called when a row is inserted into or deleted from the
   88067 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   88068 ** on the child table of pFKey, this function is invoked twice for each row
   88069 ** affected - once to "delete" the old row, and then again to "insert" the
   88070 ** new row.
   88071 **
   88072 ** Each time it is called, this function generates VDBE code to locate the
   88073 ** row in the parent table that corresponds to the row being inserted into
   88074 ** or deleted from the child table. If the parent row can be found, no
   88075 ** special action is taken. Otherwise, if the parent row can *not* be
   88076 ** found in the parent table:
   88077 **
   88078 **   Operation | FK type   | Action taken
   88079 **   --------------------------------------------------------------------------
   88080 **   INSERT      immediate   Increment the "immediate constraint counter".
   88081 **
   88082 **   DELETE      immediate   Decrement the "immediate constraint counter".
   88083 **
   88084 **   INSERT      deferred    Increment the "deferred constraint counter".
   88085 **
   88086 **   DELETE      deferred    Decrement the "deferred constraint counter".
   88087 **
   88088 ** These operations are identified in the comment at the top of this file
   88089 ** (fkey.c) as "I.1" and "D.1".
   88090 */
   88091 static void fkLookupParent(
   88092   Parse *pParse,        /* Parse context */
   88093   int iDb,              /* Index of database housing pTab */
   88094   Table *pTab,          /* Parent table of FK pFKey */
   88095   Index *pIdx,          /* Unique index on parent key columns in pTab */
   88096   FKey *pFKey,          /* Foreign key constraint */
   88097   int *aiCol,           /* Map from parent key columns to child table columns */
   88098   int regData,          /* Address of array containing child table row */
   88099   int nIncr,            /* Increment constraint counter by this */
   88100   int isIgnore          /* If true, pretend pTab contains all NULL values */
   88101 ){
   88102   int i;                                    /* Iterator variable */
   88103   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   88104   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   88105   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   88106 
   88107   /* If nIncr is less than zero, then check at runtime if there are any
   88108   ** outstanding constraints to resolve. If there are not, there is no need
   88109   ** to check if deleting this row resolves any outstanding violations.
   88110   **
   88111   ** Check if any of the key columns in the child table row are NULL. If
   88112   ** any are, then the constraint is considered satisfied. No need to
   88113   ** search for a matching row in the parent table.  */
   88114   if( nIncr<0 ){
   88115     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   88116   }
   88117   for(i=0; i<pFKey->nCol; i++){
   88118     int iReg = aiCol[i] + regData + 1;
   88119     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
   88120   }
   88121 
   88122   if( isIgnore==0 ){
   88123     if( pIdx==0 ){
   88124       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   88125       ** column of the parent table (table pTab).  */
   88126       int iMustBeInt;               /* Address of MustBeInt instruction */
   88127       int regTemp = sqlite3GetTempReg(pParse);
   88128 
   88129       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   88130       ** apply the affinity of the parent key). If this fails, then there
   88131       ** is no matching parent key. Before using MustBeInt, make a copy of
   88132       ** the value. Otherwise, the value inserted into the child key column
   88133       ** will have INTEGER affinity applied to it, which may not be correct.  */
   88134       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   88135       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   88136 
   88137       /* If the parent table is the same as the child table, and we are about
   88138       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   88139       ** then check if the row being inserted matches itself. If so, do not
   88140       ** increment the constraint-counter.  */
   88141       if( pTab==pFKey->pFrom && nIncr==1 ){
   88142         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
   88143       }
   88144 
   88145       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   88146       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
   88147       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   88148       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   88149       sqlite3VdbeJumpHere(v, iMustBeInt);
   88150       sqlite3ReleaseTempReg(pParse, regTemp);
   88151     }else{
   88152       int nCol = pFKey->nCol;
   88153       int regTemp = sqlite3GetTempRange(pParse, nCol);
   88154       int regRec = sqlite3GetTempReg(pParse);
   88155       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   88156 
   88157       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   88158       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
   88159       for(i=0; i<nCol; i++){
   88160         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   88161       }
   88162 
   88163       /* If the parent table is the same as the child table, and we are about
   88164       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   88165       ** then check if the row being inserted matches itself. If so, do not
   88166       ** increment the constraint-counter.
   88167       **
   88168       ** If any of the parent-key values are NULL, then the row cannot match
   88169       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
   88170       ** of the parent-key values are NULL (at this point it is known that
   88171       ** none of the child key values are).
   88172       */
   88173       if( pTab==pFKey->pFrom && nIncr==1 ){
   88174         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   88175         for(i=0; i<nCol; i++){
   88176           int iChild = aiCol[i]+1+regData;
   88177           int iParent = pIdx->aiColumn[i]+1+regData;
   88178           assert( aiCol[i]!=pTab->iPKey );
   88179           if( pIdx->aiColumn[i]==pTab->iPKey ){
   88180             /* The parent key is a composite key that includes the IPK column */
   88181             iParent = regData;
   88182           }
   88183           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
   88184           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   88185         }
   88186         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   88187       }
   88188 
   88189       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
   88190       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
   88191       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
   88192 
   88193       sqlite3ReleaseTempReg(pParse, regRec);
   88194       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   88195     }
   88196   }
   88197 
   88198   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   88199     /* Special case: If this is an INSERT statement that will insert exactly
   88200     ** one row into the table, raise a constraint immediately instead of
   88201     ** incrementing a counter. This is necessary as the VM code is being
   88202     ** generated for will not open a statement transaction.  */
   88203     assert( nIncr==1 );
   88204     sqlite3HaltConstraint(
   88205         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   88206     );
   88207   }else{
   88208     if( nIncr>0 && pFKey->isDeferred==0 ){
   88209       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   88210     }
   88211     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   88212   }
   88213 
   88214   sqlite3VdbeResolveLabel(v, iOk);
   88215   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   88216 }
   88217 
   88218 /*
   88219 ** This function is called to generate code executed when a row is deleted
   88220 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   88221 ** deferred, when a row is inserted into the same table. When generating
   88222 ** code for an SQL UPDATE operation, this function may be called twice -
   88223 ** once to "delete" the old row and once to "insert" the new row.
   88224 **
   88225 ** The code generated by this function scans through the rows in the child
   88226 ** table that correspond to the parent table row being deleted or inserted.
   88227 ** For each child row found, one of the following actions is taken:
   88228 **
   88229 **   Operation | FK type   | Action taken
   88230 **   --------------------------------------------------------------------------
   88231 **   DELETE      immediate   Increment the "immediate constraint counter".
   88232 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   88233 **                           throw a "foreign key constraint failed" exception.
   88234 **
   88235 **   INSERT      immediate   Decrement the "immediate constraint counter".
   88236 **
   88237 **   DELETE      deferred    Increment the "deferred constraint counter".
   88238 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   88239 **                           throw a "foreign key constraint failed" exception.
   88240 **
   88241 **   INSERT      deferred    Decrement the "deferred constraint counter".
   88242 **
   88243 ** These operations are identified in the comment at the top of this file
   88244 ** (fkey.c) as "I.2" and "D.2".
   88245 */
   88246 static void fkScanChildren(
   88247   Parse *pParse,                  /* Parse context */
   88248   SrcList *pSrc,                  /* SrcList containing the table to scan */
   88249   Table *pTab,
   88250   Index *pIdx,                    /* Foreign key index */
   88251   FKey *pFKey,                    /* Foreign key relationship */
   88252   int *aiCol,                     /* Map from pIdx cols to child table cols */
   88253   int regData,                    /* Referenced table data starts here */
   88254   int nIncr                       /* Amount to increment deferred counter by */
   88255 ){
   88256   sqlite3 *db = pParse->db;       /* Database handle */
   88257   int i;                          /* Iterator variable */
   88258   Expr *pWhere = 0;               /* WHERE clause to scan with */
   88259   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   88260   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   88261   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   88262   Vdbe *v = sqlite3GetVdbe(pParse);
   88263 
   88264   assert( !pIdx || pIdx->pTable==pTab );
   88265 
   88266   if( nIncr<0 ){
   88267     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   88268   }
   88269 
   88270   /* Create an Expr object representing an SQL expression like:
   88271   **
   88272   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   88273   **
   88274   ** The collation sequence used for the comparison should be that of
   88275   ** the parent key columns. The affinity of the parent key column should
   88276   ** be applied to each child key value before the comparison takes place.
   88277   */
   88278   for(i=0; i<pFKey->nCol; i++){
   88279     Expr *pLeft;                  /* Value from parent table row */
   88280     Expr *pRight;                 /* Column ref to child table */
   88281     Expr *pEq;                    /* Expression (pLeft = pRight) */
   88282     int iCol;                     /* Index of column in child table */
   88283     const char *zCol;             /* Name of column in child table */
   88284 
   88285     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   88286     if( pLeft ){
   88287       /* Set the collation sequence and affinity of the LHS of each TK_EQ
   88288       ** expression to the parent key column defaults.  */
   88289       if( pIdx ){
   88290         Column *pCol;
   88291         iCol = pIdx->aiColumn[i];
   88292         pCol = &pTab->aCol[iCol];
   88293         if( pTab->iPKey==iCol ) iCol = -1;
   88294         pLeft->iTable = regData+iCol+1;
   88295         pLeft->affinity = pCol->affinity;
   88296         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
   88297       }else{
   88298         pLeft->iTable = regData;
   88299         pLeft->affinity = SQLITE_AFF_INTEGER;
   88300       }
   88301     }
   88302     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   88303     assert( iCol>=0 );
   88304     zCol = pFKey->pFrom->aCol[iCol].zName;
   88305     pRight = sqlite3Expr(db, TK_ID, zCol);
   88306     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   88307     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88308   }
   88309 
   88310   /* If the child table is the same as the parent table, and this scan
   88311   ** is taking place as part of a DELETE operation (operation D.2), omit the
   88312   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
   88313   ** clause, where $rowid is the rowid of the row being deleted.  */
   88314   if( pTab==pFKey->pFrom && nIncr>0 ){
   88315     Expr *pEq;                    /* Expression (pLeft = pRight) */
   88316     Expr *pLeft;                  /* Value from parent table row */
   88317     Expr *pRight;                 /* Column ref to child table */
   88318     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   88319     pRight = sqlite3Expr(db, TK_COLUMN, 0);
   88320     if( pLeft && pRight ){
   88321       pLeft->iTable = regData;
   88322       pLeft->affinity = SQLITE_AFF_INTEGER;
   88323       pRight->iTable = pSrc->a[0].iCursor;
   88324       pRight->iColumn = -1;
   88325     }
   88326     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   88327     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88328   }
   88329 
   88330   /* Resolve the references in the WHERE clause. */
   88331   memset(&sNameContext, 0, sizeof(NameContext));
   88332   sNameContext.pSrcList = pSrc;
   88333   sNameContext.pParse = pParse;
   88334   sqlite3ResolveExprNames(&sNameContext, pWhere);
   88335 
   88336   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   88337   ** clause. If the constraint is not deferred, throw an exception for
   88338   ** each row found. Otherwise, for deferred constraints, increment the
   88339   ** deferred constraint counter by nIncr for each row selected.  */
   88340   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
   88341   if( nIncr>0 && pFKey->isDeferred==0 ){
   88342     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   88343   }
   88344   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   88345   if( pWInfo ){
   88346     sqlite3WhereEnd(pWInfo);
   88347   }
   88348 
   88349   /* Clean up the WHERE clause constructed above. */
   88350   sqlite3ExprDelete(db, pWhere);
   88351   if( iFkIfZero ){
   88352     sqlite3VdbeJumpHere(v, iFkIfZero);
   88353   }
   88354 }
   88355 
   88356 /*
   88357 ** This function returns a pointer to the head of a linked list of FK
   88358 ** constraints for which table pTab is the parent table. For example,
   88359 ** given the following schema:
   88360 **
   88361 **   CREATE TABLE t1(a PRIMARY KEY);
   88362 **   CREATE TABLE t2(b REFERENCES t1(a);
   88363 **
   88364 ** Calling this function with table "t1" as an argument returns a pointer
   88365 ** to the FKey structure representing the foreign key constraint on table
   88366 ** "t2". Calling this function with "t2" as the argument would return a
   88367 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   88368 ** table).
   88369 */
   88370 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   88371   int nName = sqlite3Strlen30(pTab->zName);
   88372   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   88373 }
   88374 
   88375 /*
   88376 ** The second argument is a Trigger structure allocated by the
   88377 ** fkActionTrigger() routine. This function deletes the Trigger structure
   88378 ** and all of its sub-components.
   88379 **
   88380 ** The Trigger structure or any of its sub-components may be allocated from
   88381 ** the lookaside buffer belonging to database handle dbMem.
   88382 */
   88383 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   88384   if( p ){
   88385     TriggerStep *pStep = p->step_list;
   88386     sqlite3ExprDelete(dbMem, pStep->pWhere);
   88387     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   88388     sqlite3SelectDelete(dbMem, pStep->pSelect);
   88389     sqlite3ExprDelete(dbMem, p->pWhen);
   88390     sqlite3DbFree(dbMem, p);
   88391   }
   88392 }
   88393 
   88394 /*
   88395 ** This function is called to generate code that runs when table pTab is
   88396 ** being dropped from the database. The SrcList passed as the second argument
   88397 ** to this function contains a single entry guaranteed to resolve to
   88398 ** table pTab.
   88399 **
   88400 ** Normally, no code is required. However, if either
   88401 **
   88402 **   (a) The table is the parent table of a FK constraint, or
   88403 **   (b) The table is the child table of a deferred FK constraint and it is
   88404 **       determined at runtime that there are outstanding deferred FK
   88405 **       constraint violations in the database,
   88406 **
   88407 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   88408 ** the table from the database. Triggers are disabled while running this
   88409 ** DELETE, but foreign key actions are not.
   88410 */
   88411 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   88412   sqlite3 *db = pParse->db;
   88413   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   88414     int iSkip = 0;
   88415     Vdbe *v = sqlite3GetVdbe(pParse);
   88416 
   88417     assert( v );                  /* VDBE has already been allocated */
   88418     if( sqlite3FkReferences(pTab)==0 ){
   88419       /* Search for a deferred foreign key constraint for which this table
   88420       ** is the child table. If one cannot be found, return without
   88421       ** generating any VDBE code. If one can be found, then jump over
   88422       ** the entire DELETE if there are no outstanding deferred constraints
   88423       ** when this statement is run.  */
   88424       FKey *p;
   88425       for(p=pTab->pFKey; p; p=p->pNextFrom){
   88426         if( p->isDeferred ) break;
   88427       }
   88428       if( !p ) return;
   88429       iSkip = sqlite3VdbeMakeLabel(v);
   88430       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
   88431     }
   88432 
   88433     pParse->disableTriggers = 1;
   88434     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   88435     pParse->disableTriggers = 0;
   88436 
   88437     /* If the DELETE has generated immediate foreign key constraint
   88438     ** violations, halt the VDBE and return an error at this point, before
   88439     ** any modifications to the schema are made. This is because statement
   88440     ** transactions are not able to rollback schema changes.  */
   88441     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   88442     sqlite3HaltConstraint(
   88443         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   88444     );
   88445 
   88446     if( iSkip ){
   88447       sqlite3VdbeResolveLabel(v, iSkip);
   88448     }
   88449   }
   88450 }
   88451 
   88452 /*
   88453 ** This function is called when inserting, deleting or updating a row of
   88454 ** table pTab to generate VDBE code to perform foreign key constraint
   88455 ** processing for the operation.
   88456 **
   88457 ** For a DELETE operation, parameter regOld is passed the index of the
   88458 ** first register in an array of (pTab->nCol+1) registers containing the
   88459 ** rowid of the row being deleted, followed by each of the column values
   88460 ** of the row being deleted, from left to right. Parameter regNew is passed
   88461 ** zero in this case.
   88462 **
   88463 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   88464 ** first register of an array of (pTab->nCol+1) registers containing the new
   88465 ** row data.
   88466 **
   88467 ** For an UPDATE operation, this function is called twice. Once before
   88468 ** the original record is deleted from the table using the calling convention
   88469 ** described for DELETE. Then again after the original record is deleted
   88470 ** but before the new record is inserted using the INSERT convention.
   88471 */
   88472 SQLITE_PRIVATE void sqlite3FkCheck(
   88473   Parse *pParse,                  /* Parse context */
   88474   Table *pTab,                    /* Row is being deleted from this table */
   88475   int regOld,                     /* Previous row data is stored here */
   88476   int regNew                      /* New row data is stored here */
   88477 ){
   88478   sqlite3 *db = pParse->db;       /* Database handle */
   88479   FKey *pFKey;                    /* Used to iterate through FKs */
   88480   int iDb;                        /* Index of database containing pTab */
   88481   const char *zDb;                /* Name of database containing pTab */
   88482   int isIgnoreErrors = pParse->disableTriggers;
   88483 
   88484   /* Exactly one of regOld and regNew should be non-zero. */
   88485   assert( (regOld==0)!=(regNew==0) );
   88486 
   88487   /* If foreign-keys are disabled, this function is a no-op. */
   88488   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   88489 
   88490   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88491   zDb = db->aDb[iDb].zName;
   88492 
   88493   /* Loop through all the foreign key constraints for which pTab is the
   88494   ** child table (the table that the foreign key definition is part of).  */
   88495   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   88496     Table *pTo;                   /* Parent table of foreign key pFKey */
   88497     Index *pIdx = 0;              /* Index on key columns in pTo */
   88498     int *aiFree = 0;
   88499     int *aiCol;
   88500     int iCol;
   88501     int i;
   88502     int isIgnore = 0;
   88503 
   88504     /* Find the parent table of this foreign key. Also find a unique index
   88505     ** on the parent key columns in the parent table. If either of these
   88506     ** schema items cannot be located, set an error in pParse and return
   88507     ** early.  */
   88508     if( pParse->disableTriggers ){
   88509       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   88510     }else{
   88511       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   88512     }
   88513     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   88514       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
   88515       if( !isIgnoreErrors || db->mallocFailed ) return;
   88516       if( pTo==0 ){
   88517         /* If isIgnoreErrors is true, then a table is being dropped. In this
   88518         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
   88519         ** before actually dropping it in order to check FK constraints.
   88520         ** If the parent table of an FK constraint on the current table is
   88521         ** missing, behave as if it is empty. i.e. decrement the relevant
   88522         ** FK counter for each row of the current table with non-NULL keys.
   88523         */
   88524         Vdbe *v = sqlite3GetVdbe(pParse);
   88525         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   88526         for(i=0; i<pFKey->nCol; i++){
   88527           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   88528           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
   88529         }
   88530         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   88531       }
   88532       continue;
   88533     }
   88534     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   88535 
   88536     if( aiFree ){
   88537       aiCol = aiFree;
   88538     }else{
   88539       iCol = pFKey->aCol[0].iFrom;
   88540       aiCol = &iCol;
   88541     }
   88542     for(i=0; i<pFKey->nCol; i++){
   88543       if( aiCol[i]==pTab->iPKey ){
   88544         aiCol[i] = -1;
   88545       }
   88546 #ifndef SQLITE_OMIT_AUTHORIZATION
   88547       /* Request permission to read the parent key columns. If the
   88548       ** authorization callback returns SQLITE_IGNORE, behave as if any
   88549       ** values read from the parent table are NULL. */
   88550       if( db->xAuth ){
   88551         int rcauth;
   88552         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   88553         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   88554         isIgnore = (rcauth==SQLITE_IGNORE);
   88555       }
   88556 #endif
   88557     }
   88558 
   88559     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   88560     ** a cursor to use to search the unique index on the parent key columns
   88561     ** in the parent table.  */
   88562     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   88563     pParse->nTab++;
   88564 
   88565     if( regOld!=0 ){
   88566       /* A row is being removed from the child table. Search for the parent.
   88567       ** If the parent does not exist, removing the child row resolves an
   88568       ** outstanding foreign key constraint violation. */
   88569       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   88570     }
   88571     if( regNew!=0 ){
   88572       /* A row is being added to the child table. If a parent row cannot
   88573       ** be found, adding the child row has violated the FK constraint. */
   88574       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   88575     }
   88576 
   88577     sqlite3DbFree(db, aiFree);
   88578   }
   88579 
   88580   /* Loop through all the foreign key constraints that refer to this table */
   88581   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   88582     Index *pIdx = 0;              /* Foreign key index for pFKey */
   88583     SrcList *pSrc;
   88584     int *aiCol = 0;
   88585 
   88586     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   88587       assert( regOld==0 && regNew!=0 );
   88588       /* Inserting a single row into a parent table cannot cause an immediate
   88589       ** foreign key violation. So do nothing in this case.  */
   88590       continue;
   88591     }
   88592 
   88593     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   88594       if( !isIgnoreErrors || db->mallocFailed ) return;
   88595       continue;
   88596     }
   88597     assert( aiCol || pFKey->nCol==1 );
   88598 
   88599     /* Create a SrcList structure containing a single table (the table
   88600     ** the foreign key that refers to this table is attached to). This
   88601     ** is required for the sqlite3WhereXXX() interface.  */
   88602     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   88603     if( pSrc ){
   88604       struct SrcList_item *pItem = pSrc->a;
   88605       pItem->pTab = pFKey->pFrom;
   88606       pItem->zName = pFKey->pFrom->zName;
   88607       pItem->pTab->nRef++;
   88608       pItem->iCursor = pParse->nTab++;
   88609 
   88610       if( regNew!=0 ){
   88611         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   88612       }
   88613       if( regOld!=0 ){
   88614         /* If there is a RESTRICT action configured for the current operation
   88615         ** on the parent table of this FK, then throw an exception
   88616         ** immediately if the FK constraint is violated, even if this is a
   88617         ** deferred trigger. That's what RESTRICT means. To defer checking
   88618         ** the constraint, the FK should specify NO ACTION (represented
   88619         ** using OE_None). NO ACTION is the default.  */
   88620         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   88621       }
   88622       pItem->zName = 0;
   88623       sqlite3SrcListDelete(db, pSrc);
   88624     }
   88625     sqlite3DbFree(db, aiCol);
   88626   }
   88627 }
   88628 
   88629 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   88630 
   88631 /*
   88632 ** This function is called before generating code to update or delete a
   88633 ** row contained in table pTab.
   88634 */
   88635 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   88636   Parse *pParse,                  /* Parse context */
   88637   Table *pTab                     /* Table being modified */
   88638 ){
   88639   u32 mask = 0;
   88640   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88641     FKey *p;
   88642     int i;
   88643     for(p=pTab->pFKey; p; p=p->pNextFrom){
   88644       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   88645     }
   88646     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   88647       Index *pIdx = 0;
   88648       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
   88649       if( pIdx ){
   88650         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   88651       }
   88652     }
   88653   }
   88654   return mask;
   88655 }
   88656 
   88657 /*
   88658 ** This function is called before generating code to update or delete a
   88659 ** row contained in table pTab. If the operation is a DELETE, then
   88660 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   88661 ** to an array of size N, where N is the number of columns in table pTab.
   88662 ** If the i'th column is not modified by the UPDATE, then the corresponding
   88663 ** entry in the aChange[] array is set to -1. If the column is modified,
   88664 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   88665 ** UPDATE statement modifies the rowid fields of the table.
   88666 **
   88667 ** If any foreign key processing will be required, this function returns
   88668 ** true. If there is no foreign key related processing, this function
   88669 ** returns false.
   88670 */
   88671 SQLITE_PRIVATE int sqlite3FkRequired(
   88672   Parse *pParse,                  /* Parse context */
   88673   Table *pTab,                    /* Table being modified */
   88674   int *aChange,                   /* Non-NULL for UPDATE operations */
   88675   int chngRowid                   /* True for UPDATE that affects rowid */
   88676 ){
   88677   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88678     if( !aChange ){
   88679       /* A DELETE operation. Foreign key processing is required if the
   88680       ** table in question is either the child or parent table for any
   88681       ** foreign key constraint.  */
   88682       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   88683     }else{
   88684       /* This is an UPDATE. Foreign key processing is only required if the
   88685       ** operation modifies one or more child or parent key columns. */
   88686       int i;
   88687       FKey *p;
   88688 
   88689       /* Check if any child key columns are being modified. */
   88690       for(p=pTab->pFKey; p; p=p->pNextFrom){
   88691         for(i=0; i<p->nCol; i++){
   88692           int iChildKey = p->aCol[i].iFrom;
   88693           if( aChange[iChildKey]>=0 ) return 1;
   88694           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
   88695         }
   88696       }
   88697 
   88698       /* Check if any parent key columns are being modified. */
   88699       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   88700         for(i=0; i<p->nCol; i++){
   88701           char *zKey = p->aCol[i].zCol;
   88702           int iKey;
   88703           for(iKey=0; iKey<pTab->nCol; iKey++){
   88704             Column *pCol = &pTab->aCol[iKey];
   88705             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
   88706               if( aChange[iKey]>=0 ) return 1;
   88707               if( iKey==pTab->iPKey && chngRowid ) return 1;
   88708             }
   88709           }
   88710         }
   88711       }
   88712     }
   88713   }
   88714   return 0;
   88715 }
   88716 
   88717 /*
   88718 ** This function is called when an UPDATE or DELETE operation is being
   88719 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   88720 ** If the current operation is an UPDATE, then the pChanges parameter is
   88721 ** passed a pointer to the list of columns being modified. If it is a
   88722 ** DELETE, pChanges is passed a NULL pointer.
   88723 **
   88724 ** It returns a pointer to a Trigger structure containing a trigger
   88725 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   88726 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   88727 ** returned (these actions require no special handling by the triggers
   88728 ** sub-system, code for them is created by fkScanChildren()).
   88729 **
   88730 ** For example, if pFKey is the foreign key and pTab is table "p" in
   88731 ** the following schema:
   88732 **
   88733 **   CREATE TABLE p(pk PRIMARY KEY);
   88734 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   88735 **
   88736 ** then the returned trigger structure is equivalent to:
   88737 **
   88738 **   CREATE TRIGGER ... DELETE ON p BEGIN
   88739 **     DELETE FROM c WHERE ck = old.pk;
   88740 **   END;
   88741 **
   88742 ** The returned pointer is cached as part of the foreign key object. It
   88743 ** is eventually freed along with the rest of the foreign key object by
   88744 ** sqlite3FkDelete().
   88745 */
   88746 static Trigger *fkActionTrigger(
   88747   Parse *pParse,                  /* Parse context */
   88748   Table *pTab,                    /* Table being updated or deleted from */
   88749   FKey *pFKey,                    /* Foreign key to get action for */
   88750   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   88751 ){
   88752   sqlite3 *db = pParse->db;       /* Database handle */
   88753   int action;                     /* One of OE_None, OE_Cascade etc. */
   88754   Trigger *pTrigger;              /* Trigger definition to return */
   88755   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   88756 
   88757   action = pFKey->aAction[iAction];
   88758   pTrigger = pFKey->apTrigger[iAction];
   88759 
   88760   if( action!=OE_None && !pTrigger ){
   88761     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   88762     char const *zFrom;            /* Name of child table */
   88763     int nFrom;                    /* Length in bytes of zFrom */
   88764     Index *pIdx = 0;              /* Parent key index for this FK */
   88765     int *aiCol = 0;               /* child table cols -> parent key cols */
   88766     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   88767     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   88768     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   88769     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   88770     int i;                        /* Iterator variable */
   88771     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   88772 
   88773     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   88774     assert( aiCol || pFKey->nCol==1 );
   88775 
   88776     for(i=0; i<pFKey->nCol; i++){
   88777       Token tOld = { "old", 3 };  /* Literal "old" token */
   88778       Token tNew = { "new", 3 };  /* Literal "new" token */
   88779       Token tFromCol;             /* Name of column in child table */
   88780       Token tToCol;               /* Name of column in parent table */
   88781       int iFromCol;               /* Idx of column in child table */
   88782       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   88783 
   88784       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   88785       assert( iFromCol>=0 );
   88786       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   88787       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   88788 
   88789       tToCol.n = sqlite3Strlen30(tToCol.z);
   88790       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   88791 
   88792       /* Create the expression "OLD.zToCol = zFromCol". It is important
   88793       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   88794       ** that the affinity and collation sequence associated with the
   88795       ** parent table are used for the comparison. */
   88796       pEq = sqlite3PExpr(pParse, TK_EQ,
   88797           sqlite3PExpr(pParse, TK_DOT,
   88798             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   88799             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   88800           , 0),
   88801           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   88802       , 0);
   88803       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88804 
   88805       /* For ON UPDATE, construct the next term of the WHEN clause.
   88806       ** The final WHEN clause will be like this:
   88807       **
   88808       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   88809       */
   88810       if( pChanges ){
   88811         pEq = sqlite3PExpr(pParse, TK_IS,
   88812             sqlite3PExpr(pParse, TK_DOT,
   88813               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   88814               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   88815               0),
   88816             sqlite3PExpr(pParse, TK_DOT,
   88817               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   88818               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   88819               0),
   88820             0);
   88821         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   88822       }
   88823 
   88824       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   88825         Expr *pNew;
   88826         if( action==OE_Cascade ){
   88827           pNew = sqlite3PExpr(pParse, TK_DOT,
   88828             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   88829             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   88830           , 0);
   88831         }else if( action==OE_SetDflt ){
   88832           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   88833           if( pDflt ){
   88834             pNew = sqlite3ExprDup(db, pDflt, 0);
   88835           }else{
   88836             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   88837           }
   88838         }else{
   88839           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   88840         }
   88841         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   88842         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   88843       }
   88844     }
   88845     sqlite3DbFree(db, aiCol);
   88846 
   88847     zFrom = pFKey->pFrom->zName;
   88848     nFrom = sqlite3Strlen30(zFrom);
   88849 
   88850     if( action==OE_Restrict ){
   88851       Token tFrom;
   88852       Expr *pRaise;
   88853 
   88854       tFrom.z = zFrom;
   88855       tFrom.n = nFrom;
   88856       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
   88857       if( pRaise ){
   88858         pRaise->affinity = OE_Abort;
   88859       }
   88860       pSelect = sqlite3SelectNew(pParse,
   88861           sqlite3ExprListAppend(pParse, 0, pRaise),
   88862           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   88863           pWhere,
   88864           0, 0, 0, 0, 0, 0
   88865       );
   88866       pWhere = 0;
   88867     }
   88868 
   88869     /* Disable lookaside memory allocation */
   88870     enableLookaside = db->lookaside.bEnabled;
   88871     db->lookaside.bEnabled = 0;
   88872 
   88873     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   88874         sizeof(Trigger) +         /* struct Trigger */
   88875         sizeof(TriggerStep) +     /* Single step in trigger program */
   88876         nFrom + 1                 /* Space for pStep->target.z */
   88877     );
   88878     if( pTrigger ){
   88879       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   88880       pStep->target.z = (char *)&pStep[1];
   88881       pStep->target.n = nFrom;
   88882       memcpy((char *)pStep->target.z, zFrom, nFrom);
   88883 
   88884       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   88885       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   88886       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   88887       if( pWhen ){
   88888         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   88889         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   88890       }
   88891     }
   88892 
   88893     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   88894     db->lookaside.bEnabled = enableLookaside;
   88895 
   88896     sqlite3ExprDelete(db, pWhere);
   88897     sqlite3ExprDelete(db, pWhen);
   88898     sqlite3ExprListDelete(db, pList);
   88899     sqlite3SelectDelete(db, pSelect);
   88900     if( db->mallocFailed==1 ){
   88901       fkTriggerDelete(db, pTrigger);
   88902       return 0;
   88903     }
   88904     assert( pStep!=0 );
   88905 
   88906     switch( action ){
   88907       case OE_Restrict:
   88908         pStep->op = TK_SELECT;
   88909         break;
   88910       case OE_Cascade:
   88911         if( !pChanges ){
   88912           pStep->op = TK_DELETE;
   88913           break;
   88914         }
   88915       default:
   88916         pStep->op = TK_UPDATE;
   88917     }
   88918     pStep->pTrig = pTrigger;
   88919     pTrigger->pSchema = pTab->pSchema;
   88920     pTrigger->pTabSchema = pTab->pSchema;
   88921     pFKey->apTrigger[iAction] = pTrigger;
   88922     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   88923   }
   88924 
   88925   return pTrigger;
   88926 }
   88927 
   88928 /*
   88929 ** This function is called when deleting or updating a row to implement
   88930 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   88931 */
   88932 SQLITE_PRIVATE void sqlite3FkActions(
   88933   Parse *pParse,                  /* Parse context */
   88934   Table *pTab,                    /* Table being updated or deleted from */
   88935   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   88936   int regOld                      /* Address of array containing old row */
   88937 ){
   88938   /* If foreign-key support is enabled, iterate through all FKs that
   88939   ** refer to table pTab. If there is an action associated with the FK
   88940   ** for this operation (either update or delete), invoke the associated
   88941   ** trigger sub-program.  */
   88942   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88943     FKey *pFKey;                  /* Iterator variable */
   88944     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   88945       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   88946       if( pAction ){
   88947         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
   88948       }
   88949     }
   88950   }
   88951 }
   88952 
   88953 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   88954 
   88955 /*
   88956 ** Free all memory associated with foreign key definitions attached to
   88957 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   88958 ** hash table.
   88959 */
   88960 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   88961   FKey *pFKey;                    /* Iterator variable */
   88962   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   88963 
   88964   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
   88965   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   88966 
   88967     /* Remove the FK from the fkeyHash hash table. */
   88968     if( !db || db->pnBytesFreed==0 ){
   88969       if( pFKey->pPrevTo ){
   88970         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   88971       }else{
   88972         void *p = (void *)pFKey->pNextTo;
   88973         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   88974         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
   88975       }
   88976       if( pFKey->pNextTo ){
   88977         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   88978       }
   88979     }
   88980 
   88981     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   88982     ** classified as either immediate or deferred.
   88983     */
   88984     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   88985 
   88986     /* Delete any triggers created to implement actions for this FK. */
   88987 #ifndef SQLITE_OMIT_TRIGGER
   88988     fkTriggerDelete(db, pFKey->apTrigger[0]);
   88989     fkTriggerDelete(db, pFKey->apTrigger[1]);
   88990 #endif
   88991 
   88992     pNext = pFKey->pNextFrom;
   88993     sqlite3DbFree(db, pFKey);
   88994   }
   88995 }
   88996 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   88997 
   88998 /************** End of fkey.c ************************************************/
   88999 /************** Begin file insert.c ******************************************/
   89000 /*
   89001 ** 2001 September 15
   89002 **
   89003 ** The author disclaims copyright to this source code.  In place of
   89004 ** a legal notice, here is a blessing:
   89005 **
   89006 **    May you do good and not evil.
   89007 **    May you find forgiveness for yourself and forgive others.
   89008 **    May you share freely, never taking more than you give.
   89009 **
   89010 *************************************************************************
   89011 ** This file contains C code routines that are called by the parser
   89012 ** to handle INSERT statements in SQLite.
   89013 */
   89014 
   89015 /*
   89016 ** Generate code that will open a table for reading.
   89017 */
   89018 SQLITE_PRIVATE void sqlite3OpenTable(
   89019   Parse *p,       /* Generate code into this VDBE */
   89020   int iCur,       /* The cursor number of the table */
   89021   int iDb,        /* The database index in sqlite3.aDb[] */
   89022   Table *pTab,    /* The table to be opened */
   89023   int opcode      /* OP_OpenRead or OP_OpenWrite */
   89024 ){
   89025   Vdbe *v;
   89026   if( IsVirtual(pTab) ) return;
   89027   v = sqlite3GetVdbe(p);
   89028   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   89029   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
   89030   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
   89031   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
   89032   VdbeComment((v, "%s", pTab->zName));
   89033 }
   89034 
   89035 /*
   89036 ** Return a pointer to the column affinity string associated with index
   89037 ** pIdx. A column affinity string has one character for each column in
   89038 ** the table, according to the affinity of the column:
   89039 **
   89040 **  Character      Column affinity
   89041 **  ------------------------------
   89042 **  'a'            TEXT
   89043 **  'b'            NONE
   89044 **  'c'            NUMERIC
   89045 **  'd'            INTEGER
   89046 **  'e'            REAL
   89047 **
   89048 ** An extra 'd' is appended to the end of the string to cover the
   89049 ** rowid that appears as the last column in every index.
   89050 **
   89051 ** Memory for the buffer containing the column index affinity string
   89052 ** is managed along with the rest of the Index structure. It will be
   89053 ** released when sqlite3DeleteIndex() is called.
   89054 */
   89055 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   89056   if( !pIdx->zColAff ){
   89057     /* The first time a column affinity string for a particular index is
   89058     ** required, it is allocated and populated here. It is then stored as
   89059     ** a member of the Index structure for subsequent use.
   89060     **
   89061     ** The column affinity string will eventually be deleted by
   89062     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   89063     ** up.
   89064     */
   89065     int n;
   89066     Table *pTab = pIdx->pTable;
   89067     sqlite3 *db = sqlite3VdbeDb(v);
   89068     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
   89069     if( !pIdx->zColAff ){
   89070       db->mallocFailed = 1;
   89071       return 0;
   89072     }
   89073     for(n=0; n<pIdx->nColumn; n++){
   89074       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
   89075     }
   89076     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
   89077     pIdx->zColAff[n] = 0;
   89078   }
   89079 
   89080   return pIdx->zColAff;
   89081 }
   89082 
   89083 /*
   89084 ** Set P4 of the most recently inserted opcode to a column affinity
   89085 ** string for table pTab. A column affinity string has one character
   89086 ** for each column indexed by the index, according to the affinity of the
   89087 ** column:
   89088 **
   89089 **  Character      Column affinity
   89090 **  ------------------------------
   89091 **  'a'            TEXT
   89092 **  'b'            NONE
   89093 **  'c'            NUMERIC
   89094 **  'd'            INTEGER
   89095 **  'e'            REAL
   89096 */
   89097 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
   89098   /* The first time a column affinity string for a particular table
   89099   ** is required, it is allocated and populated here. It is then
   89100   ** stored as a member of the Table structure for subsequent use.
   89101   **
   89102   ** The column affinity string will eventually be deleted by
   89103   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
   89104   */
   89105   if( !pTab->zColAff ){
   89106     char *zColAff;
   89107     int i;
   89108     sqlite3 *db = sqlite3VdbeDb(v);
   89109 
   89110     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   89111     if( !zColAff ){
   89112       db->mallocFailed = 1;
   89113       return;
   89114     }
   89115 
   89116     for(i=0; i<pTab->nCol; i++){
   89117       zColAff[i] = pTab->aCol[i].affinity;
   89118     }
   89119     zColAff[pTab->nCol] = '\0';
   89120 
   89121     pTab->zColAff = zColAff;
   89122   }
   89123 
   89124   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
   89125 }
   89126 
   89127 /*
   89128 ** Return non-zero if the table pTab in database iDb or any of its indices
   89129 ** have been opened at any point in the VDBE program beginning at location
   89130 ** iStartAddr throught the end of the program.  This is used to see if
   89131 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   89132 ** run without using temporary table for the results of the SELECT.
   89133 */
   89134 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
   89135   Vdbe *v = sqlite3GetVdbe(p);
   89136   int i;
   89137   int iEnd = sqlite3VdbeCurrentAddr(v);
   89138 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89139   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   89140 #endif
   89141 
   89142   for(i=iStartAddr; i<iEnd; i++){
   89143     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   89144     assert( pOp!=0 );
   89145     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   89146       Index *pIndex;
   89147       int tnum = pOp->p2;
   89148       if( tnum==pTab->tnum ){
   89149         return 1;
   89150       }
   89151       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   89152         if( tnum==pIndex->tnum ){
   89153           return 1;
   89154         }
   89155       }
   89156     }
   89157 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89158     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   89159       assert( pOp->p4.pVtab!=0 );
   89160       assert( pOp->p4type==P4_VTAB );
   89161       return 1;
   89162     }
   89163 #endif
   89164   }
   89165   return 0;
   89166 }
   89167 
   89168 #ifndef SQLITE_OMIT_AUTOINCREMENT
   89169 /*
   89170 ** Locate or create an AutoincInfo structure associated with table pTab
   89171 ** which is in database iDb.  Return the register number for the register
   89172 ** that holds the maximum rowid.
   89173 **
   89174 ** There is at most one AutoincInfo structure per table even if the
   89175 ** same table is autoincremented multiple times due to inserts within
   89176 ** triggers.  A new AutoincInfo structure is created if this is the
   89177 ** first use of table pTab.  On 2nd and subsequent uses, the original
   89178 ** AutoincInfo structure is used.
   89179 **
   89180 ** Three memory locations are allocated:
   89181 **
   89182 **   (1)  Register to hold the name of the pTab table.
   89183 **   (2)  Register to hold the maximum ROWID of pTab.
   89184 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   89185 **
   89186 ** The 2nd register is the one that is returned.  That is all the
   89187 ** insert routine needs to know about.
   89188 */
   89189 static int autoIncBegin(
   89190   Parse *pParse,      /* Parsing context */
   89191   int iDb,            /* Index of the database holding pTab */
   89192   Table *pTab         /* The table we are writing to */
   89193 ){
   89194   int memId = 0;      /* Register holding maximum rowid */
   89195   if( pTab->tabFlags & TF_Autoincrement ){
   89196     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   89197     AutoincInfo *pInfo;
   89198 
   89199     pInfo = pToplevel->pAinc;
   89200     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   89201     if( pInfo==0 ){
   89202       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   89203       if( pInfo==0 ) return 0;
   89204       pInfo->pNext = pToplevel->pAinc;
   89205       pToplevel->pAinc = pInfo;
   89206       pInfo->pTab = pTab;
   89207       pInfo->iDb = iDb;
   89208       pToplevel->nMem++;                  /* Register to hold name of table */
   89209       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   89210       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   89211     }
   89212     memId = pInfo->regCtr;
   89213   }
   89214   return memId;
   89215 }
   89216 
   89217 /*
   89218 ** This routine generates code that will initialize all of the
   89219 ** register used by the autoincrement tracker.
   89220 */
   89221 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   89222   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   89223   sqlite3 *db = pParse->db;  /* The database connection */
   89224   Db *pDb;                   /* Database only autoinc table */
   89225   int memId;                 /* Register holding max rowid */
   89226   int addr;                  /* A VDBE address */
   89227   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   89228 
   89229   /* This routine is never called during trigger-generation.  It is
   89230   ** only called from the top-level */
   89231   assert( pParse->pTriggerTab==0 );
   89232   assert( pParse==sqlite3ParseToplevel(pParse) );
   89233 
   89234   assert( v );   /* We failed long ago if this is not so */
   89235   for(p = pParse->pAinc; p; p = p->pNext){
   89236     pDb = &db->aDb[p->iDb];
   89237     memId = p->regCtr;
   89238     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   89239     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   89240     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   89241     addr = sqlite3VdbeCurrentAddr(v);
   89242     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   89243     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
   89244     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   89245     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
   89246     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   89247     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   89248     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   89249     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   89250     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
   89251     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   89252     sqlite3VdbeAddOp0(v, OP_Close);
   89253   }
   89254 }
   89255 
   89256 /*
   89257 ** Update the maximum rowid for an autoincrement calculation.
   89258 **
   89259 ** This routine should be called when the top of the stack holds a
   89260 ** new rowid that is about to be inserted.  If that new rowid is
   89261 ** larger than the maximum rowid in the memId memory cell, then the
   89262 ** memory cell is updated.  The stack is unchanged.
   89263 */
   89264 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   89265   if( memId>0 ){
   89266     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   89267   }
   89268 }
   89269 
   89270 /*
   89271 ** This routine generates the code needed to write autoincrement
   89272 ** maximum rowid values back into the sqlite_sequence register.
   89273 ** Every statement that might do an INSERT into an autoincrement
   89274 ** table (either directly or through triggers) needs to call this
   89275 ** routine just before the "exit" code.
   89276 */
   89277 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   89278   AutoincInfo *p;
   89279   Vdbe *v = pParse->pVdbe;
   89280   sqlite3 *db = pParse->db;
   89281 
   89282   assert( v );
   89283   for(p = pParse->pAinc; p; p = p->pNext){
   89284     Db *pDb = &db->aDb[p->iDb];
   89285     int j1, j2, j3, j4, j5;
   89286     int iRec;
   89287     int memId = p->regCtr;
   89288 
   89289     iRec = sqlite3GetTempReg(pParse);
   89290     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   89291     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   89292     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
   89293     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
   89294     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
   89295     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
   89296     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
   89297     sqlite3VdbeJumpHere(v, j2);
   89298     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   89299     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
   89300     sqlite3VdbeJumpHere(v, j4);
   89301     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   89302     sqlite3VdbeJumpHere(v, j1);
   89303     sqlite3VdbeJumpHere(v, j5);
   89304     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   89305     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   89306     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   89307     sqlite3VdbeAddOp0(v, OP_Close);
   89308     sqlite3ReleaseTempReg(pParse, iRec);
   89309   }
   89310 }
   89311 #else
   89312 /*
   89313 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   89314 ** above are all no-ops
   89315 */
   89316 # define autoIncBegin(A,B,C) (0)
   89317 # define autoIncStep(A,B,C)
   89318 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   89319 
   89320 
   89321 /* Forward declaration */
   89322 static int xferOptimization(
   89323   Parse *pParse,        /* Parser context */
   89324   Table *pDest,         /* The table we are inserting into */
   89325   Select *pSelect,      /* A SELECT statement to use as the data source */
   89326   int onError,          /* How to handle constraint errors */
   89327   int iDbDest           /* The database of pDest */
   89328 );
   89329 
   89330 /*
   89331 ** This routine is call to handle SQL of the following forms:
   89332 **
   89333 **    insert into TABLE (IDLIST) values(EXPRLIST)
   89334 **    insert into TABLE (IDLIST) select
   89335 **
   89336 ** The IDLIST following the table name is always optional.  If omitted,
   89337 ** then a list of all columns for the table is substituted.  The IDLIST
   89338 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   89339 **
   89340 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   89341 ** statement above, and pSelect is NULL.  For the second form, pList is
   89342 ** NULL and pSelect is a pointer to the select statement used to generate
   89343 ** data for the insert.
   89344 **
   89345 ** The code generated follows one of four templates.  For a simple
   89346 ** select with data coming from a VALUES clause, the code executes
   89347 ** once straight down through.  Pseudo-code follows (we call this
   89348 ** the "1st template"):
   89349 **
   89350 **         open write cursor to <table> and its indices
   89351 **         puts VALUES clause expressions onto the stack
   89352 **         write the resulting record into <table>
   89353 **         cleanup
   89354 **
   89355 ** The three remaining templates assume the statement is of the form
   89356 **
   89357 **   INSERT INTO <table> SELECT ...
   89358 **
   89359 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   89360 ** in other words if the SELECT pulls all columns from a single table
   89361 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   89362 ** if <table2> and <table1> are distinct tables but have identical
   89363 ** schemas, including all the same indices, then a special optimization
   89364 ** is invoked that copies raw records from <table2> over to <table1>.
   89365 ** See the xferOptimization() function for the implementation of this
   89366 ** template.  This is the 2nd template.
   89367 **
   89368 **         open a write cursor to <table>
   89369 **         open read cursor on <table2>
   89370 **         transfer all records in <table2> over to <table>
   89371 **         close cursors
   89372 **         foreach index on <table>
   89373 **           open a write cursor on the <table> index
   89374 **           open a read cursor on the corresponding <table2> index
   89375 **           transfer all records from the read to the write cursors
   89376 **           close cursors
   89377 **         end foreach
   89378 **
   89379 ** The 3rd template is for when the second template does not apply
   89380 ** and the SELECT clause does not read from <table> at any time.
   89381 ** The generated code follows this template:
   89382 **
   89383 **         EOF <- 0
   89384 **         X <- A
   89385 **         goto B
   89386 **      A: setup for the SELECT
   89387 **         loop over the rows in the SELECT
   89388 **           load values into registers R..R+n
   89389 **           yield X
   89390 **         end loop
   89391 **         cleanup after the SELECT
   89392 **         EOF <- 1
   89393 **         yield X
   89394 **         goto A
   89395 **      B: open write cursor to <table> and its indices
   89396 **      C: yield X
   89397 **         if EOF goto D
   89398 **         insert the select result into <table> from R..R+n
   89399 **         goto C
   89400 **      D: cleanup
   89401 **
   89402 ** The 4th template is used if the insert statement takes its
   89403 ** values from a SELECT but the data is being inserted into a table
   89404 ** that is also read as part of the SELECT.  In the third form,
   89405 ** we have to use a intermediate table to store the results of
   89406 ** the select.  The template is like this:
   89407 **
   89408 **         EOF <- 0
   89409 **         X <- A
   89410 **         goto B
   89411 **      A: setup for the SELECT
   89412 **         loop over the tables in the SELECT
   89413 **           load value into register R..R+n
   89414 **           yield X
   89415 **         end loop
   89416 **         cleanup after the SELECT
   89417 **         EOF <- 1
   89418 **         yield X
   89419 **         halt-error
   89420 **      B: open temp table
   89421 **      L: yield X
   89422 **         if EOF goto M
   89423 **         insert row from R..R+n into temp table
   89424 **         goto L
   89425 **      M: open write cursor to <table> and its indices
   89426 **         rewind temp table
   89427 **      C: loop over rows of intermediate table
   89428 **           transfer values form intermediate table into <table>
   89429 **         end loop
   89430 **      D: cleanup
   89431 */
   89432 SQLITE_PRIVATE void sqlite3Insert(
   89433   Parse *pParse,        /* Parser context */
   89434   SrcList *pTabList,    /* Name of table into which we are inserting */
   89435   ExprList *pList,      /* List of values to be inserted */
   89436   Select *pSelect,      /* A SELECT statement to use as the data source */
   89437   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   89438   int onError           /* How to handle constraint errors */
   89439 ){
   89440   sqlite3 *db;          /* The main database structure */
   89441   Table *pTab;          /* The table to insert into.  aka TABLE */
   89442   char *zTab;           /* Name of the table into which we are inserting */
   89443   const char *zDb;      /* Name of the database holding this table */
   89444   int i, j, idx;        /* Loop counters */
   89445   Vdbe *v;              /* Generate code into this virtual machine */
   89446   Index *pIdx;          /* For looping over indices of the table */
   89447   int nColumn;          /* Number of columns in the data */
   89448   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   89449   int baseCur = 0;      /* VDBE Cursor number for pTab */
   89450   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   89451   int endOfLoop;        /* Label for the end of the insertion loop */
   89452   int useTempTable = 0; /* Store SELECT results in intermediate table */
   89453   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   89454   int addrInsTop = 0;   /* Jump to label "D" */
   89455   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   89456   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   89457   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   89458   int iDb;              /* Index of database holding TABLE */
   89459   Db *pDb;              /* The database containing table being inserted into */
   89460   int appendFlag = 0;   /* True if the insert is likely to be an append */
   89461 
   89462   /* Register allocations */
   89463   int regFromSelect = 0;/* Base register for data coming from SELECT */
   89464   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   89465   int regRowCount = 0;  /* Memory cell used for the row counter */
   89466   int regIns;           /* Block of regs holding rowid+data being inserted */
   89467   int regRowid;         /* registers holding insert rowid */
   89468   int regData;          /* register holding first column to insert */
   89469   int regEof = 0;       /* Register recording end of SELECT data */
   89470   int *aRegIdx = 0;     /* One register allocated to each index */
   89471 
   89472 #ifndef SQLITE_OMIT_TRIGGER
   89473   int isView;                 /* True if attempting to insert into a view */
   89474   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   89475   int tmask;                  /* Mask of trigger times */
   89476 #endif
   89477 
   89478   db = pParse->db;
   89479   memset(&dest, 0, sizeof(dest));
   89480   if( pParse->nErr || db->mallocFailed ){
   89481     goto insert_cleanup;
   89482   }
   89483 
   89484   /* Locate the table into which we will be inserting new information.
   89485   */
   89486   assert( pTabList->nSrc==1 );
   89487   zTab = pTabList->a[0].zName;
   89488   if( NEVER(zTab==0) ) goto insert_cleanup;
   89489   pTab = sqlite3SrcListLookup(pParse, pTabList);
   89490   if( pTab==0 ){
   89491     goto insert_cleanup;
   89492   }
   89493   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   89494   assert( iDb<db->nDb );
   89495   pDb = &db->aDb[iDb];
   89496   zDb = pDb->zName;
   89497   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   89498     goto insert_cleanup;
   89499   }
   89500 
   89501   /* Figure out if we have any triggers and if the table being
   89502   ** inserted into is a view
   89503   */
   89504 #ifndef SQLITE_OMIT_TRIGGER
   89505   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   89506   isView = pTab->pSelect!=0;
   89507 #else
   89508 # define pTrigger 0
   89509 # define tmask 0
   89510 # define isView 0
   89511 #endif
   89512 #ifdef SQLITE_OMIT_VIEW
   89513 # undef isView
   89514 # define isView 0
   89515 #endif
   89516   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   89517 
   89518   /* If pTab is really a view, make sure it has been initialized.
   89519   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
   89520   ** module table).
   89521   */
   89522   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   89523     goto insert_cleanup;
   89524   }
   89525 
   89526   /* Ensure that:
   89527   *  (a) the table is not read-only,
   89528   *  (b) that if it is a view then ON INSERT triggers exist
   89529   */
   89530   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   89531     goto insert_cleanup;
   89532   }
   89533 
   89534   /* Allocate a VDBE
   89535   */
   89536   v = sqlite3GetVdbe(pParse);
   89537   if( v==0 ) goto insert_cleanup;
   89538   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   89539   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   89540 
   89541 #ifndef SQLITE_OMIT_XFER_OPT
   89542   /* If the statement is of the form
   89543   **
   89544   **       INSERT INTO <table1> SELECT * FROM <table2>;
   89545   **
   89546   ** Then special optimizations can be applied that make the transfer
   89547   ** very fast and which reduce fragmentation of indices.
   89548   **
   89549   ** This is the 2nd template.
   89550   */
   89551   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   89552     assert( !pTrigger );
   89553     assert( pList==0 );
   89554     goto insert_end;
   89555   }
   89556 #endif /* SQLITE_OMIT_XFER_OPT */
   89557 
   89558   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   89559   ** sqlite_sequence table and store it in memory cell regAutoinc.
   89560   */
   89561   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   89562 
   89563   /* Figure out how many columns of data are supplied.  If the data
   89564   ** is coming from a SELECT statement, then generate a co-routine that
   89565   ** produces a single row of the SELECT on each invocation.  The
   89566   ** co-routine is the common header to the 3rd and 4th templates.
   89567   */
   89568   if( pSelect ){
   89569     /* Data is coming from a SELECT.  Generate code to implement that SELECT
   89570     ** as a co-routine.  The code is common to both the 3rd and 4th
   89571     ** templates:
   89572     **
   89573     **         EOF <- 0
   89574     **         X <- A
   89575     **         goto B
   89576     **      A: setup for the SELECT
   89577     **         loop over the tables in the SELECT
   89578     **           load value into register R..R+n
   89579     **           yield X
   89580     **         end loop
   89581     **         cleanup after the SELECT
   89582     **         EOF <- 1
   89583     **         yield X
   89584     **         halt-error
   89585     **
   89586     ** On each invocation of the co-routine, it puts a single row of the
   89587     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
   89588     ** (These output registers are allocated by sqlite3Select().)  When
   89589     ** the SELECT completes, it sets the EOF flag stored in regEof.
   89590     */
   89591     int rc, j1;
   89592 
   89593     regEof = ++pParse->nMem;
   89594     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
   89595     VdbeComment((v, "SELECT eof flag"));
   89596     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
   89597     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
   89598     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
   89599     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   89600     VdbeComment((v, "Jump over SELECT coroutine"));
   89601 
   89602     /* Resolve the expressions in the SELECT statement and execute it. */
   89603     rc = sqlite3Select(pParse, pSelect, &dest);
   89604     assert( pParse->nErr==0 || rc );
   89605     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
   89606       goto insert_cleanup;
   89607     }
   89608     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
   89609     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
   89610     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
   89611     VdbeComment((v, "End of SELECT coroutine"));
   89612     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
   89613 
   89614     regFromSelect = dest.iMem;
   89615     assert( pSelect->pEList );
   89616     nColumn = pSelect->pEList->nExpr;
   89617     assert( dest.nMem==nColumn );
   89618 
   89619     /* Set useTempTable to TRUE if the result of the SELECT statement
   89620     ** should be written into a temporary table (template 4).  Set to
   89621     ** FALSE if each* row of the SELECT can be written directly into
   89622     ** the destination table (template 3).
   89623     **
   89624     ** A temp table must be used if the table being updated is also one
   89625     ** of the tables being read by the SELECT statement.  Also use a
   89626     ** temp table in the case of row triggers.
   89627     */
   89628     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
   89629       useTempTable = 1;
   89630     }
   89631 
   89632     if( useTempTable ){
   89633       /* Invoke the coroutine to extract information from the SELECT
   89634       ** and add it to a transient table srcTab.  The code generated
   89635       ** here is from the 4th template:
   89636       **
   89637       **      B: open temp table
   89638       **      L: yield X
   89639       **         if EOF goto M
   89640       **         insert row from R..R+n into temp table
   89641       **         goto L
   89642       **      M: ...
   89643       */
   89644       int regRec;          /* Register to hold packed record */
   89645       int regTempRowid;    /* Register to hold temp table ROWID */
   89646       int addrTop;         /* Label "L" */
   89647       int addrIf;          /* Address of jump to M */
   89648 
   89649       srcTab = pParse->nTab++;
   89650       regRec = sqlite3GetTempReg(pParse);
   89651       regTempRowid = sqlite3GetTempReg(pParse);
   89652       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   89653       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   89654       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
   89655       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   89656       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   89657       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   89658       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   89659       sqlite3VdbeJumpHere(v, addrIf);
   89660       sqlite3ReleaseTempReg(pParse, regRec);
   89661       sqlite3ReleaseTempReg(pParse, regTempRowid);
   89662     }
   89663   }else{
   89664     /* This is the case if the data for the INSERT is coming from a VALUES
   89665     ** clause
   89666     */
   89667     NameContext sNC;
   89668     memset(&sNC, 0, sizeof(sNC));
   89669     sNC.pParse = pParse;
   89670     srcTab = -1;
   89671     assert( useTempTable==0 );
   89672     nColumn = pList ? pList->nExpr : 0;
   89673     for(i=0; i<nColumn; i++){
   89674       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   89675         goto insert_cleanup;
   89676       }
   89677     }
   89678   }
   89679 
   89680   /* Make sure the number of columns in the source data matches the number
   89681   ** of columns to be inserted into the table.
   89682   */
   89683   if( IsVirtual(pTab) ){
   89684     for(i=0; i<pTab->nCol; i++){
   89685       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   89686     }
   89687   }
   89688   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   89689     sqlite3ErrorMsg(pParse,
   89690        "table %S has %d columns but %d values were supplied",
   89691        pTabList, 0, pTab->nCol-nHidden, nColumn);
   89692     goto insert_cleanup;
   89693   }
   89694   if( pColumn!=0 && nColumn!=pColumn->nId ){
   89695     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   89696     goto insert_cleanup;
   89697   }
   89698 
   89699   /* If the INSERT statement included an IDLIST term, then make sure
   89700   ** all elements of the IDLIST really are columns of the table and
   89701   ** remember the column indices.
   89702   **
   89703   ** If the table has an INTEGER PRIMARY KEY column and that column
   89704   ** is named in the IDLIST, then record in the keyColumn variable
   89705   ** the index into IDLIST of the primary key column.  keyColumn is
   89706   ** the index of the primary key as it appears in IDLIST, not as
   89707   ** is appears in the original table.  (The index of the primary
   89708   ** key in the original table is pTab->iPKey.)
   89709   */
   89710   if( pColumn ){
   89711     for(i=0; i<pColumn->nId; i++){
   89712       pColumn->a[i].idx = -1;
   89713     }
   89714     for(i=0; i<pColumn->nId; i++){
   89715       for(j=0; j<pTab->nCol; j++){
   89716         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   89717           pColumn->a[i].idx = j;
   89718           if( j==pTab->iPKey ){
   89719             keyColumn = i;
   89720           }
   89721           break;
   89722         }
   89723       }
   89724       if( j>=pTab->nCol ){
   89725         if( sqlite3IsRowid(pColumn->a[i].zName) ){
   89726           keyColumn = i;
   89727         }else{
   89728           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   89729               pTabList, 0, pColumn->a[i].zName);
   89730           pParse->checkSchema = 1;
   89731           goto insert_cleanup;
   89732         }
   89733       }
   89734     }
   89735   }
   89736 
   89737   /* If there is no IDLIST term but the table has an integer primary
   89738   ** key, the set the keyColumn variable to the primary key column index
   89739   ** in the original table definition.
   89740   */
   89741   if( pColumn==0 && nColumn>0 ){
   89742     keyColumn = pTab->iPKey;
   89743   }
   89744 
   89745   /* Initialize the count of rows to be inserted
   89746   */
   89747   if( db->flags & SQLITE_CountRows ){
   89748     regRowCount = ++pParse->nMem;
   89749     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   89750   }
   89751 
   89752   /* If this is not a view, open the table and and all indices */
   89753   if( !isView ){
   89754     int nIdx;
   89755 
   89756     baseCur = pParse->nTab;
   89757     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
   89758     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   89759     if( aRegIdx==0 ){
   89760       goto insert_cleanup;
   89761     }
   89762     for(i=0; i<nIdx; i++){
   89763       aRegIdx[i] = ++pParse->nMem;
   89764     }
   89765   }
   89766 
   89767   /* This is the top of the main insertion loop */
   89768   if( useTempTable ){
   89769     /* This block codes the top of loop only.  The complete loop is the
   89770     ** following pseudocode (template 4):
   89771     **
   89772     **         rewind temp table
   89773     **      C: loop over rows of intermediate table
   89774     **           transfer values form intermediate table into <table>
   89775     **         end loop
   89776     **      D: ...
   89777     */
   89778     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
   89779     addrCont = sqlite3VdbeCurrentAddr(v);
   89780   }else if( pSelect ){
   89781     /* This block codes the top of loop only.  The complete loop is the
   89782     ** following pseudocode (template 3):
   89783     **
   89784     **      C: yield X
   89785     **         if EOF goto D
   89786     **         insert the select result into <table> from R..R+n
   89787     **         goto C
   89788     **      D: ...
   89789     */
   89790     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   89791     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
   89792   }
   89793 
   89794   /* Allocate registers for holding the rowid of the new row,
   89795   ** the content of the new row, and the assemblied row record.
   89796   */
   89797   regRowid = regIns = pParse->nMem+1;
   89798   pParse->nMem += pTab->nCol + 1;
   89799   if( IsVirtual(pTab) ){
   89800     regRowid++;
   89801     pParse->nMem++;
   89802   }
   89803   regData = regRowid+1;
   89804 
   89805   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   89806   */
   89807   endOfLoop = sqlite3VdbeMakeLabel(v);
   89808   if( tmask & TRIGGER_BEFORE ){
   89809     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   89810 
   89811     /* build the NEW.* reference row.  Note that if there is an INTEGER
   89812     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   89813     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   89814     ** we do not know what the unique ID will be (because the insert has
   89815     ** not happened yet) so we substitute a rowid of -1
   89816     */
   89817     if( keyColumn<0 ){
   89818       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   89819     }else{
   89820       int j1;
   89821       if( useTempTable ){
   89822         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
   89823       }else{
   89824         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   89825         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
   89826       }
   89827       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
   89828       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   89829       sqlite3VdbeJumpHere(v, j1);
   89830       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
   89831     }
   89832 
   89833     /* Cannot have triggers on a virtual table. If it were possible,
   89834     ** this block would have to account for hidden column.
   89835     */
   89836     assert( !IsVirtual(pTab) );
   89837 
   89838     /* Create the new column data
   89839     */
   89840     for(i=0; i<pTab->nCol; i++){
   89841       if( pColumn==0 ){
   89842         j = i;
   89843       }else{
   89844         for(j=0; j<pColumn->nId; j++){
   89845           if( pColumn->a[j].idx==i ) break;
   89846         }
   89847       }
   89848       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
   89849         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   89850       }else if( useTempTable ){
   89851         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   89852       }else{
   89853         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   89854         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   89855       }
   89856     }
   89857 
   89858     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   89859     ** do not attempt any conversions before assembling the record.
   89860     ** If this is a real table, attempt conversions as required by the
   89861     ** table column affinities.
   89862     */
   89863     if( !isView ){
   89864       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   89865       sqlite3TableAffinityStr(v, pTab);
   89866     }
   89867 
   89868     /* Fire BEFORE or INSTEAD OF triggers */
   89869     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   89870         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   89871 
   89872     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   89873   }
   89874 
   89875   /* Push the record number for the new entry onto the stack.  The
   89876   ** record number is a randomly generate integer created by NewRowid
   89877   ** except when the table has an INTEGER PRIMARY KEY column, in which
   89878   ** case the record number is the same as that column.
   89879   */
   89880   if( !isView ){
   89881     if( IsVirtual(pTab) ){
   89882       /* The row that the VUpdate opcode will delete: none */
   89883       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   89884     }
   89885     if( keyColumn>=0 ){
   89886       if( useTempTable ){
   89887         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
   89888       }else if( pSelect ){
   89889         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
   89890       }else{
   89891         VdbeOp *pOp;
   89892         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
   89893         pOp = sqlite3VdbeGetOp(v, -1);
   89894         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   89895           appendFlag = 1;
   89896           pOp->opcode = OP_NewRowid;
   89897           pOp->p1 = baseCur;
   89898           pOp->p2 = regRowid;
   89899           pOp->p3 = regAutoinc;
   89900         }
   89901       }
   89902       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   89903       ** to generate a unique primary key value.
   89904       */
   89905       if( !appendFlag ){
   89906         int j1;
   89907         if( !IsVirtual(pTab) ){
   89908           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
   89909           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   89910           sqlite3VdbeJumpHere(v, j1);
   89911         }else{
   89912           j1 = sqlite3VdbeCurrentAddr(v);
   89913           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
   89914         }
   89915         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
   89916       }
   89917     }else if( IsVirtual(pTab) ){
   89918       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   89919     }else{
   89920       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   89921       appendFlag = 1;
   89922     }
   89923     autoIncStep(pParse, regAutoinc, regRowid);
   89924 
   89925     /* Push onto the stack, data for all columns of the new entry, beginning
   89926     ** with the first column.
   89927     */
   89928     nHidden = 0;
   89929     for(i=0; i<pTab->nCol; i++){
   89930       int iRegStore = regRowid+1+i;
   89931       if( i==pTab->iPKey ){
   89932         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   89933         ** Whenever this column is read, the record number will be substituted
   89934         ** in its place.  So will fill this column with a NULL to avoid
   89935         ** taking up data space with information that will never be used. */
   89936         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
   89937         continue;
   89938       }
   89939       if( pColumn==0 ){
   89940         if( IsHiddenColumn(&pTab->aCol[i]) ){
   89941           assert( IsVirtual(pTab) );
   89942           j = -1;
   89943           nHidden++;
   89944         }else{
   89945           j = i - nHidden;
   89946         }
   89947       }else{
   89948         for(j=0; j<pColumn->nId; j++){
   89949           if( pColumn->a[j].idx==i ) break;
   89950         }
   89951       }
   89952       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   89953         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
   89954       }else if( useTempTable ){
   89955         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   89956       }else if( pSelect ){
   89957         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   89958       }else{
   89959         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   89960       }
   89961     }
   89962 
   89963     /* Generate code to check constraints and generate index keys and
   89964     ** do the insertion.
   89965     */
   89966 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89967     if( IsVirtual(pTab) ){
   89968       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   89969       sqlite3VtabMakeWritable(pParse, pTab);
   89970       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   89971       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   89972       sqlite3MayAbort(pParse);
   89973     }else
   89974 #endif
   89975     {
   89976       int isReplace;    /* Set to true if constraints may cause a replace */
   89977       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
   89978           keyColumn>=0, 0, onError, endOfLoop, &isReplace
   89979       );
   89980       sqlite3FkCheck(pParse, pTab, 0, regIns);
   89981       sqlite3CompleteInsertion(
   89982           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
   89983       );
   89984     }
   89985   }
   89986 
   89987   /* Update the count of rows that are inserted
   89988   */
   89989   if( (db->flags & SQLITE_CountRows)!=0 ){
   89990     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   89991   }
   89992 
   89993   if( pTrigger ){
   89994     /* Code AFTER triggers */
   89995     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   89996         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   89997   }
   89998 
   89999   /* The bottom of the main insertion loop, if the data source
   90000   ** is a SELECT statement.
   90001   */
   90002   sqlite3VdbeResolveLabel(v, endOfLoop);
   90003   if( useTempTable ){
   90004     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
   90005     sqlite3VdbeJumpHere(v, addrInsTop);
   90006     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   90007   }else if( pSelect ){
   90008     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   90009     sqlite3VdbeJumpHere(v, addrInsTop);
   90010   }
   90011 
   90012   if( !IsVirtual(pTab) && !isView ){
   90013     /* Close all tables opened */
   90014     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
   90015     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   90016       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
   90017     }
   90018   }
   90019 
   90020 insert_end:
   90021   /* Update the sqlite_sequence table by storing the content of the
   90022   ** maximum rowid counter values recorded while inserting into
   90023   ** autoincrement tables.
   90024   */
   90025   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   90026     sqlite3AutoincrementEnd(pParse);
   90027   }
   90028 
   90029   /*
   90030   ** Return the number of rows inserted. If this routine is
   90031   ** generating code because of a call to sqlite3NestedParse(), do not
   90032   ** invoke the callback function.
   90033   */
   90034   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   90035     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   90036     sqlite3VdbeSetNumCols(v, 1);
   90037     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   90038   }
   90039 
   90040 insert_cleanup:
   90041   sqlite3SrcListDelete(db, pTabList);
   90042   sqlite3ExprListDelete(db, pList);
   90043   sqlite3SelectDelete(db, pSelect);
   90044   sqlite3IdListDelete(db, pColumn);
   90045   sqlite3DbFree(db, aRegIdx);
   90046 }
   90047 
   90048 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   90049 ** thely may interfere with compilation of other functions in this file
   90050 ** (or in another file, if this file becomes part of the amalgamation).  */
   90051 #ifdef isView
   90052  #undef isView
   90053 #endif
   90054 #ifdef pTrigger
   90055  #undef pTrigger
   90056 #endif
   90057 #ifdef tmask
   90058  #undef tmask
   90059 #endif
   90060 
   90061 
   90062 /*
   90063 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
   90064 **
   90065 ** The input is a range of consecutive registers as follows:
   90066 **
   90067 **    1.  The rowid of the row after the update.
   90068 **
   90069 **    2.  The data in the first column of the entry after the update.
   90070 **
   90071 **    i.  Data from middle columns...
   90072 **
   90073 **    N.  The data in the last column of the entry after the update.
   90074 **
   90075 ** The regRowid parameter is the index of the register containing (1).
   90076 **
   90077 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
   90078 ** the address of a register containing the rowid before the update takes
   90079 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
   90080 ** is false, indicating an INSERT statement, then a non-zero rowidChng
   90081 ** indicates that the rowid was explicitly specified as part of the
   90082 ** INSERT statement. If rowidChng is false, it means that  the rowid is
   90083 ** computed automatically in an insert or that the rowid value is not
   90084 ** modified by an update.
   90085 **
   90086 ** The code generated by this routine store new index entries into
   90087 ** registers identified by aRegIdx[].  No index entry is created for
   90088 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   90089 ** the same as the order of indices on the linked list of indices
   90090 ** attached to the table.
   90091 **
   90092 ** This routine also generates code to check constraints.  NOT NULL,
   90093 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   90094 ** then the appropriate action is performed.  There are five possible
   90095 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   90096 **
   90097 **  Constraint type  Action       What Happens
   90098 **  ---------------  ----------   ----------------------------------------
   90099 **  any              ROLLBACK     The current transaction is rolled back and
   90100 **                                sqlite3_exec() returns immediately with a
   90101 **                                return code of SQLITE_CONSTRAINT.
   90102 **
   90103 **  any              ABORT        Back out changes from the current command
   90104 **                                only (do not do a complete rollback) then
   90105 **                                cause sqlite3_exec() to return immediately
   90106 **                                with SQLITE_CONSTRAINT.
   90107 **
   90108 **  any              FAIL         Sqlite3_exec() returns immediately with a
   90109 **                                return code of SQLITE_CONSTRAINT.  The
   90110 **                                transaction is not rolled back and any
   90111 **                                prior changes are retained.
   90112 **
   90113 **  any              IGNORE       The record number and data is popped from
   90114 **                                the stack and there is an immediate jump
   90115 **                                to label ignoreDest.
   90116 **
   90117 **  NOT NULL         REPLACE      The NULL value is replace by the default
   90118 **                                value for that column.  If the default value
   90119 **                                is NULL, the action is the same as ABORT.
   90120 **
   90121 **  UNIQUE           REPLACE      The other row that conflicts with the row
   90122 **                                being inserted is removed.
   90123 **
   90124 **  CHECK            REPLACE      Illegal.  The results in an exception.
   90125 **
   90126 ** Which action to take is determined by the overrideError parameter.
   90127 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   90128 ** is used.  Or if pParse->onError==OE_Default then the onError value
   90129 ** for the constraint is used.
   90130 **
   90131 ** The calling routine must open a read/write cursor for pTab with
   90132 ** cursor number "baseCur".  All indices of pTab must also have open
   90133 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
   90134 ** Except, if there is no possibility of a REPLACE action then
   90135 ** cursors do not need to be open for indices where aRegIdx[i]==0.
   90136 */
   90137 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   90138   Parse *pParse,      /* The parser context */
   90139   Table *pTab,        /* the table into which we are inserting */
   90140   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   90141   int regRowid,       /* Index of the range of input registers */
   90142   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   90143   int rowidChng,      /* True if the rowid might collide with existing entry */
   90144   int isUpdate,       /* True for UPDATE, False for INSERT */
   90145   int overrideError,  /* Override onError to this if not OE_Default */
   90146   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
   90147   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
   90148 ){
   90149   int i;              /* loop counter */
   90150   Vdbe *v;            /* VDBE under constrution */
   90151   int nCol;           /* Number of columns */
   90152   int onError;        /* Conflict resolution strategy */
   90153   int j1;             /* Addresss of jump instruction */
   90154   int j2 = 0, j3;     /* Addresses of jump instructions */
   90155   int regData;        /* Register containing first data column */
   90156   int iCur;           /* Table cursor number */
   90157   Index *pIdx;         /* Pointer to one of the indices */
   90158   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   90159   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
   90160 
   90161   v = sqlite3GetVdbe(pParse);
   90162   assert( v!=0 );
   90163   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   90164   nCol = pTab->nCol;
   90165   regData = regRowid + 1;
   90166 
   90167   /* Test all NOT NULL constraints.
   90168   */
   90169   for(i=0; i<nCol; i++){
   90170     if( i==pTab->iPKey ){
   90171       continue;
   90172     }
   90173     onError = pTab->aCol[i].notNull;
   90174     if( onError==OE_None ) continue;
   90175     if( overrideError!=OE_Default ){
   90176       onError = overrideError;
   90177     }else if( onError==OE_Default ){
   90178       onError = OE_Abort;
   90179     }
   90180     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   90181       onError = OE_Abort;
   90182     }
   90183     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   90184         || onError==OE_Ignore || onError==OE_Replace );
   90185     switch( onError ){
   90186       case OE_Abort:
   90187         sqlite3MayAbort(pParse);
   90188       case OE_Rollback:
   90189       case OE_Fail: {
   90190         char *zMsg;
   90191         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
   90192                                   SQLITE_CONSTRAINT, onError, regData+i);
   90193         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
   90194                               pTab->zName, pTab->aCol[i].zName);
   90195         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
   90196         break;
   90197       }
   90198       case OE_Ignore: {
   90199         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
   90200         break;
   90201       }
   90202       default: {
   90203         assert( onError==OE_Replace );
   90204         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
   90205         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
   90206         sqlite3VdbeJumpHere(v, j1);
   90207         break;
   90208       }
   90209     }
   90210   }
   90211 
   90212   /* Test all CHECK constraints
   90213   */
   90214 #ifndef SQLITE_OMIT_CHECK
   90215   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
   90216     int allOk = sqlite3VdbeMakeLabel(v);
   90217     pParse->ckBase = regData;
   90218     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
   90219     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   90220     if( onError==OE_Ignore ){
   90221       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90222     }else{
   90223       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   90224       sqlite3HaltConstraint(pParse, onError, 0, 0);
   90225     }
   90226     sqlite3VdbeResolveLabel(v, allOk);
   90227   }
   90228 #endif /* !defined(SQLITE_OMIT_CHECK) */
   90229 
   90230   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
   90231   ** of the new record does not previously exist.  Except, if this
   90232   ** is an UPDATE and the primary key is not changing, that is OK.
   90233   */
   90234   if( rowidChng ){
   90235     onError = pTab->keyConf;
   90236     if( overrideError!=OE_Default ){
   90237       onError = overrideError;
   90238     }else if( onError==OE_Default ){
   90239       onError = OE_Abort;
   90240     }
   90241 
   90242     if( isUpdate ){
   90243       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
   90244     }
   90245     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
   90246     switch( onError ){
   90247       default: {
   90248         onError = OE_Abort;
   90249         /* Fall thru into the next case */
   90250       }
   90251       case OE_Rollback:
   90252       case OE_Abort:
   90253       case OE_Fail: {
   90254         sqlite3HaltConstraint(
   90255           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   90256         break;
   90257       }
   90258       case OE_Replace: {
   90259         /* If there are DELETE triggers on this table and the
   90260         ** recursive-triggers flag is set, call GenerateRowDelete() to
   90261         ** remove the conflicting row from the the table. This will fire
   90262         ** the triggers and remove both the table and index b-tree entries.
   90263         **
   90264         ** Otherwise, if there are no triggers or the recursive-triggers
   90265         ** flag is not set, but the table has one or more indexes, call
   90266         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   90267         ** only. The table b-tree entry will be replaced by the new entry
   90268         ** when it is inserted.
   90269         **
   90270         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   90271         ** also invoke MultiWrite() to indicate that this VDBE may require
   90272         ** statement rollback (if the statement is aborted after the delete
   90273         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   90274         ** but being more selective here allows statements like:
   90275         **
   90276         **   REPLACE INTO t(rowid) VALUES($newrowid)
   90277         **
   90278         ** to run without a statement journal if there are no indexes on the
   90279         ** table.
   90280         */
   90281         Trigger *pTrigger = 0;
   90282         if( pParse->db->flags&SQLITE_RecTriggers ){
   90283           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   90284         }
   90285         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   90286           sqlite3MultiWrite(pParse);
   90287           sqlite3GenerateRowDelete(
   90288               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
   90289           );
   90290         }else if( pTab->pIndex ){
   90291           sqlite3MultiWrite(pParse);
   90292           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
   90293         }
   90294         seenReplace = 1;
   90295         break;
   90296       }
   90297       case OE_Ignore: {
   90298         assert( seenReplace==0 );
   90299         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90300         break;
   90301       }
   90302     }
   90303     sqlite3VdbeJumpHere(v, j3);
   90304     if( isUpdate ){
   90305       sqlite3VdbeJumpHere(v, j2);
   90306     }
   90307   }
   90308 
   90309   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   90310   ** index and making sure that duplicate entries do not already exist.
   90311   ** Add the new records to the indices as we go.
   90312   */
   90313   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
   90314     int regIdx;
   90315     int regR;
   90316 
   90317     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
   90318 
   90319     /* Create a key for accessing the index entry */
   90320     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
   90321     for(i=0; i<pIdx->nColumn; i++){
   90322       int idx = pIdx->aiColumn[i];
   90323       if( idx==pTab->iPKey ){
   90324         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   90325       }else{
   90326         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
   90327       }
   90328     }
   90329     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   90330     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
   90331     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
   90332     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
   90333 
   90334     /* Find out what action to take in case there is an indexing conflict */
   90335     onError = pIdx->onError;
   90336     if( onError==OE_None ){
   90337       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   90338       continue;  /* pIdx is not a UNIQUE index */
   90339     }
   90340     if( overrideError!=OE_Default ){
   90341       onError = overrideError;
   90342     }else if( onError==OE_Default ){
   90343       onError = OE_Abort;
   90344     }
   90345     if( seenReplace ){
   90346       if( onError==OE_Ignore ) onError = OE_Replace;
   90347       else if( onError==OE_Fail ) onError = OE_Abort;
   90348     }
   90349 
   90350     /* Check to see if the new index entry will be unique */
   90351     regR = sqlite3GetTempReg(pParse);
   90352     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
   90353     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
   90354                            regR, SQLITE_INT_TO_PTR(regIdx),
   90355                            P4_INT32);
   90356     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   90357 
   90358     /* Generate code that executes if the new index entry is not unique */
   90359     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   90360         || onError==OE_Ignore || onError==OE_Replace );
   90361     switch( onError ){
   90362       case OE_Rollback:
   90363       case OE_Abort:
   90364       case OE_Fail: {
   90365         int j;
   90366         StrAccum errMsg;
   90367         const char *zSep;
   90368         char *zErr;
   90369 
   90370         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   90371         errMsg.db = pParse->db;
   90372         zSep = pIdx->nColumn>1 ? "columns " : "column ";
   90373         for(j=0; j<pIdx->nColumn; j++){
   90374           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   90375           sqlite3StrAccumAppend(&errMsg, zSep, -1);
   90376           zSep = ", ";
   90377           sqlite3StrAccumAppend(&errMsg, zCol, -1);
   90378         }
   90379         sqlite3StrAccumAppend(&errMsg,
   90380             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
   90381         zErr = sqlite3StrAccumFinish(&errMsg);
   90382         sqlite3HaltConstraint(pParse, onError, zErr, 0);
   90383         sqlite3DbFree(errMsg.db, zErr);
   90384         break;
   90385       }
   90386       case OE_Ignore: {
   90387         assert( seenReplace==0 );
   90388         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90389         break;
   90390       }
   90391       default: {
   90392         Trigger *pTrigger = 0;
   90393         assert( onError==OE_Replace );
   90394         sqlite3MultiWrite(pParse);
   90395         if( pParse->db->flags&SQLITE_RecTriggers ){
   90396           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   90397         }
   90398         sqlite3GenerateRowDelete(
   90399             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
   90400         );
   90401         seenReplace = 1;
   90402         break;
   90403       }
   90404     }
   90405     sqlite3VdbeJumpHere(v, j3);
   90406     sqlite3ReleaseTempReg(pParse, regR);
   90407   }
   90408 
   90409   if( pbMayReplace ){
   90410     *pbMayReplace = seenReplace;
   90411   }
   90412 }
   90413 
   90414 /*
   90415 ** This routine generates code to finish the INSERT or UPDATE operation
   90416 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   90417 ** A consecutive range of registers starting at regRowid contains the
   90418 ** rowid and the content to be inserted.
   90419 **
   90420 ** The arguments to this routine should be the same as the first six
   90421 ** arguments to sqlite3GenerateConstraintChecks.
   90422 */
   90423 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   90424   Parse *pParse,      /* The parser context */
   90425   Table *pTab,        /* the table into which we are inserting */
   90426   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   90427   int regRowid,       /* Range of content */
   90428   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   90429   int isUpdate,       /* True for UPDATE, False for INSERT */
   90430   int appendBias,     /* True if this is likely to be an append */
   90431   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   90432 ){
   90433   int i;
   90434   Vdbe *v;
   90435   int nIdx;
   90436   Index *pIdx;
   90437   u8 pik_flags;
   90438   int regData;
   90439   int regRec;
   90440 
   90441   v = sqlite3GetVdbe(pParse);
   90442   assert( v!=0 );
   90443   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   90444   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   90445   for(i=nIdx-1; i>=0; i--){
   90446     if( aRegIdx[i]==0 ) continue;
   90447     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
   90448     if( useSeekResult ){
   90449       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   90450     }
   90451   }
   90452   regData = regRowid + 1;
   90453   regRec = sqlite3GetTempReg(pParse);
   90454   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   90455   sqlite3TableAffinityStr(v, pTab);
   90456   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   90457   if( pParse->nested ){
   90458     pik_flags = 0;
   90459   }else{
   90460     pik_flags = OPFLAG_NCHANGE;
   90461     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   90462   }
   90463   if( appendBias ){
   90464     pik_flags |= OPFLAG_APPEND;
   90465   }
   90466   if( useSeekResult ){
   90467     pik_flags |= OPFLAG_USESEEKRESULT;
   90468   }
   90469   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
   90470   if( !pParse->nested ){
   90471     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   90472   }
   90473   sqlite3VdbeChangeP5(v, pik_flags);
   90474 }
   90475 
   90476 /*
   90477 ** Generate code that will open cursors for a table and for all
   90478 ** indices of that table.  The "baseCur" parameter is the cursor number used
   90479 ** for the table.  Indices are opened on subsequent cursors.
   90480 **
   90481 ** Return the number of indices on the table.
   90482 */
   90483 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   90484   Parse *pParse,   /* Parsing context */
   90485   Table *pTab,     /* Table to be opened */
   90486   int baseCur,     /* Cursor number assigned to the table */
   90487   int op           /* OP_OpenRead or OP_OpenWrite */
   90488 ){
   90489   int i;
   90490   int iDb;
   90491   Index *pIdx;
   90492   Vdbe *v;
   90493 
   90494   if( IsVirtual(pTab) ) return 0;
   90495   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   90496   v = sqlite3GetVdbe(pParse);
   90497   assert( v!=0 );
   90498   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
   90499   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   90500     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   90501     assert( pIdx->pSchema==pTab->pSchema );
   90502     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
   90503                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90504     VdbeComment((v, "%s", pIdx->zName));
   90505   }
   90506   if( pParse->nTab<baseCur+i ){
   90507     pParse->nTab = baseCur+i;
   90508   }
   90509   return i-1;
   90510 }
   90511 
   90512 
   90513 #ifdef SQLITE_TEST
   90514 /*
   90515 ** The following global variable is incremented whenever the
   90516 ** transfer optimization is used.  This is used for testing
   90517 ** purposes only - to make sure the transfer optimization really
   90518 ** is happening when it is suppose to.
   90519 */
   90520 SQLITE_API int sqlite3_xferopt_count;
   90521 #endif /* SQLITE_TEST */
   90522 
   90523 
   90524 #ifndef SQLITE_OMIT_XFER_OPT
   90525 /*
   90526 ** Check to collation names to see if they are compatible.
   90527 */
   90528 static int xferCompatibleCollation(const char *z1, const char *z2){
   90529   if( z1==0 ){
   90530     return z2==0;
   90531   }
   90532   if( z2==0 ){
   90533     return 0;
   90534   }
   90535   return sqlite3StrICmp(z1, z2)==0;
   90536 }
   90537 
   90538 
   90539 /*
   90540 ** Check to see if index pSrc is compatible as a source of data
   90541 ** for index pDest in an insert transfer optimization.  The rules
   90542 ** for a compatible index:
   90543 **
   90544 **    *   The index is over the same set of columns
   90545 **    *   The same DESC and ASC markings occurs on all columns
   90546 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   90547 **    *   The same collating sequence on each column
   90548 */
   90549 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   90550   int i;
   90551   assert( pDest && pSrc );
   90552   assert( pDest->pTable!=pSrc->pTable );
   90553   if( pDest->nColumn!=pSrc->nColumn ){
   90554     return 0;   /* Different number of columns */
   90555   }
   90556   if( pDest->onError!=pSrc->onError ){
   90557     return 0;   /* Different conflict resolution strategies */
   90558   }
   90559   for(i=0; i<pSrc->nColumn; i++){
   90560     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   90561       return 0;   /* Different columns indexed */
   90562     }
   90563     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   90564       return 0;   /* Different sort orders */
   90565     }
   90566     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   90567       return 0;   /* Different collating sequences */
   90568     }
   90569   }
   90570 
   90571   /* If no test above fails then the indices must be compatible */
   90572   return 1;
   90573 }
   90574 
   90575 /*
   90576 ** Attempt the transfer optimization on INSERTs of the form
   90577 **
   90578 **     INSERT INTO tab1 SELECT * FROM tab2;
   90579 **
   90580 ** The xfer optimization transfers raw records from tab2 over to tab1.
   90581 ** Columns are not decoded and reassemblied, which greatly improves
   90582 ** performance.  Raw index records are transferred in the same way.
   90583 **
   90584 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
   90585 ** There are lots of rules for determining compatibility - see comments
   90586 ** embedded in the code for details.
   90587 **
   90588 ** This routine returns TRUE if the optimization is guaranteed to be used.
   90589 ** Sometimes the xfer optimization will only work if the destination table
   90590 ** is empty - a factor that can only be determined at run-time.  In that
   90591 ** case, this routine generates code for the xfer optimization but also
   90592 ** does a test to see if the destination table is empty and jumps over the
   90593 ** xfer optimization code if the test fails.  In that case, this routine
   90594 ** returns FALSE so that the caller will know to go ahead and generate
   90595 ** an unoptimized transfer.  This routine also returns FALSE if there
   90596 ** is no chance that the xfer optimization can be applied.
   90597 **
   90598 ** This optimization is particularly useful at making VACUUM run faster.
   90599 */
   90600 static int xferOptimization(
   90601   Parse *pParse,        /* Parser context */
   90602   Table *pDest,         /* The table we are inserting into */
   90603   Select *pSelect,      /* A SELECT statement to use as the data source */
   90604   int onError,          /* How to handle constraint errors */
   90605   int iDbDest           /* The database of pDest */
   90606 ){
   90607   ExprList *pEList;                /* The result set of the SELECT */
   90608   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   90609   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   90610   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   90611   int i;                           /* Loop counter */
   90612   int iDbSrc;                      /* The database of pSrc */
   90613   int iSrc, iDest;                 /* Cursors from source and destination */
   90614   int addr1, addr2;                /* Loop addresses */
   90615   int emptyDestTest;               /* Address of test for empty pDest */
   90616   int emptySrcTest;                /* Address of test for empty pSrc */
   90617   Vdbe *v;                         /* The VDBE we are building */
   90618   KeyInfo *pKey;                   /* Key information for an index */
   90619   int regAutoinc;                  /* Memory register used by AUTOINC */
   90620   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   90621   int regData, regRowid;           /* Registers holding data and rowid */
   90622 
   90623   if( pSelect==0 ){
   90624     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   90625   }
   90626   if( sqlite3TriggerList(pParse, pDest) ){
   90627     return 0;   /* tab1 must not have triggers */
   90628   }
   90629 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90630   if( pDest->tabFlags & TF_Virtual ){
   90631     return 0;   /* tab1 must not be a virtual table */
   90632   }
   90633 #endif
   90634   if( onError==OE_Default ){
   90635     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
   90636     if( onError==OE_Default ) onError = OE_Abort;
   90637   }
   90638   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   90639   if( pSelect->pSrc->nSrc!=1 ){
   90640     return 0;   /* FROM clause must have exactly one term */
   90641   }
   90642   if( pSelect->pSrc->a[0].pSelect ){
   90643     return 0;   /* FROM clause cannot contain a subquery */
   90644   }
   90645   if( pSelect->pWhere ){
   90646     return 0;   /* SELECT may not have a WHERE clause */
   90647   }
   90648   if( pSelect->pOrderBy ){
   90649     return 0;   /* SELECT may not have an ORDER BY clause */
   90650   }
   90651   /* Do not need to test for a HAVING clause.  If HAVING is present but
   90652   ** there is no ORDER BY, we will get an error. */
   90653   if( pSelect->pGroupBy ){
   90654     return 0;   /* SELECT may not have a GROUP BY clause */
   90655   }
   90656   if( pSelect->pLimit ){
   90657     return 0;   /* SELECT may not have a LIMIT clause */
   90658   }
   90659   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   90660   if( pSelect->pPrior ){
   90661     return 0;   /* SELECT may not be a compound query */
   90662   }
   90663   if( pSelect->selFlags & SF_Distinct ){
   90664     return 0;   /* SELECT may not be DISTINCT */
   90665   }
   90666   pEList = pSelect->pEList;
   90667   assert( pEList!=0 );
   90668   if( pEList->nExpr!=1 ){
   90669     return 0;   /* The result set must have exactly one column */
   90670   }
   90671   assert( pEList->a[0].pExpr );
   90672   if( pEList->a[0].pExpr->op!=TK_ALL ){
   90673     return 0;   /* The result set must be the special operator "*" */
   90674   }
   90675 
   90676   /* At this point we have established that the statement is of the
   90677   ** correct syntactic form to participate in this optimization.  Now
   90678   ** we have to check the semantics.
   90679   */
   90680   pItem = pSelect->pSrc->a;
   90681   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   90682   if( pSrc==0 ){
   90683     return 0;   /* FROM clause does not contain a real table */
   90684   }
   90685   if( pSrc==pDest ){
   90686     return 0;   /* tab1 and tab2 may not be the same table */
   90687   }
   90688 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90689   if( pSrc->tabFlags & TF_Virtual ){
   90690     return 0;   /* tab2 must not be a virtual table */
   90691   }
   90692 #endif
   90693   if( pSrc->pSelect ){
   90694     return 0;   /* tab2 may not be a view */
   90695   }
   90696   if( pDest->nCol!=pSrc->nCol ){
   90697     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   90698   }
   90699   if( pDest->iPKey!=pSrc->iPKey ){
   90700     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   90701   }
   90702   for(i=0; i<pDest->nCol; i++){
   90703     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
   90704       return 0;    /* Affinity must be the same on all columns */
   90705     }
   90706     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
   90707       return 0;    /* Collating sequence must be the same on all columns */
   90708     }
   90709     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
   90710       return 0;    /* tab2 must be NOT NULL if tab1 is */
   90711     }
   90712   }
   90713   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   90714     if( pDestIdx->onError!=OE_None ){
   90715       destHasUniqueIdx = 1;
   90716     }
   90717     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   90718       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   90719     }
   90720     if( pSrcIdx==0 ){
   90721       return 0;    /* pDestIdx has no corresponding index in pSrc */
   90722     }
   90723   }
   90724 #ifndef SQLITE_OMIT_CHECK
   90725   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
   90726     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   90727   }
   90728 #endif
   90729 #ifndef SQLITE_OMIT_FOREIGN_KEY
   90730   /* Disallow the transfer optimization if the destination table constains
   90731   ** any foreign key constraints.  This is more restrictive than necessary.
   90732   ** But the main beneficiary of the transfer optimization is the VACUUM
   90733   ** command, and the VACUUM command disables foreign key constraints.  So
   90734   ** the extra complication to make this rule less restrictive is probably
   90735   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   90736   */
   90737   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
   90738     return 0;
   90739   }
   90740 #endif
   90741   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
   90742     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
   90743   }
   90744 
   90745   /* If we get this far, it means that the xfer optimization is at
   90746   ** least a possibility, though it might only work if the destination
   90747   ** table (tab1) is initially empty.
   90748   */
   90749 #ifdef SQLITE_TEST
   90750   sqlite3_xferopt_count++;
   90751 #endif
   90752   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   90753   v = sqlite3GetVdbe(pParse);
   90754   sqlite3CodeVerifySchema(pParse, iDbSrc);
   90755   iSrc = pParse->nTab++;
   90756   iDest = pParse->nTab++;
   90757   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   90758   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   90759   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
   90760    || destHasUniqueIdx                              /* (2) */
   90761    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
   90762   ){
   90763     /* In some circumstances, we are able to run the xfer optimization
   90764     ** only if the destination table is initially empty.  This code makes
   90765     ** that determination.  Conditions under which the destination must
   90766     ** be empty:
   90767     **
   90768     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
   90769     **     (If the destination is not initially empty, the rowid fields
   90770     **     of index entries might need to change.)
   90771     **
   90772     ** (2) The destination has a unique index.  (The xfer optimization
   90773     **     is unable to test uniqueness.)
   90774     **
   90775     ** (3) onError is something other than OE_Abort and OE_Rollback.
   90776     */
   90777     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
   90778     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   90779     sqlite3VdbeJumpHere(v, addr1);
   90780   }else{
   90781     emptyDestTest = 0;
   90782   }
   90783   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   90784   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   90785   regData = sqlite3GetTempReg(pParse);
   90786   regRowid = sqlite3GetTempReg(pParse);
   90787   if( pDest->iPKey>=0 ){
   90788     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   90789     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   90790     sqlite3HaltConstraint(
   90791         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   90792     sqlite3VdbeJumpHere(v, addr2);
   90793     autoIncStep(pParse, regAutoinc, regRowid);
   90794   }else if( pDest->pIndex==0 ){
   90795     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   90796   }else{
   90797     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   90798     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   90799   }
   90800   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   90801   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   90802   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   90803   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   90804   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
   90805   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   90806     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   90807       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   90808     }
   90809     assert( pSrcIdx );
   90810     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   90811     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90812     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
   90813     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
   90814                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90815     VdbeComment((v, "%s", pSrcIdx->zName));
   90816     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
   90817     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
   90818                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90819     VdbeComment((v, "%s", pDestIdx->zName));
   90820     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   90821     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   90822     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   90823     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
   90824     sqlite3VdbeJumpHere(v, addr1);
   90825   }
   90826   sqlite3VdbeJumpHere(v, emptySrcTest);
   90827   sqlite3ReleaseTempReg(pParse, regRowid);
   90828   sqlite3ReleaseTempReg(pParse, regData);
   90829   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   90830   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90831   if( emptyDestTest ){
   90832     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   90833     sqlite3VdbeJumpHere(v, emptyDestTest);
   90834     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90835     return 0;
   90836   }else{
   90837     return 1;
   90838   }
   90839 }
   90840 #endif /* SQLITE_OMIT_XFER_OPT */
   90841 
   90842 /************** End of insert.c **********************************************/
   90843 /************** Begin file legacy.c ******************************************/
   90844 /*
   90845 ** 2001 September 15
   90846 **
   90847 ** The author disclaims copyright to this source code.  In place of
   90848 ** a legal notice, here is a blessing:
   90849 **
   90850 **    May you do good and not evil.
   90851 **    May you find forgiveness for yourself and forgive others.
   90852 **    May you share freely, never taking more than you give.
   90853 **
   90854 *************************************************************************
   90855 ** Main file for the SQLite library.  The routines in this file
   90856 ** implement the programmer interface to the library.  Routines in
   90857 ** other files are for internal use by SQLite and should not be
   90858 ** accessed by users of the library.
   90859 */
   90860 
   90861 
   90862 /*
   90863 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   90864 ** codes.  Also write an error message into memory obtained from
   90865 ** malloc() and make *pzErrMsg point to that message.
   90866 **
   90867 ** If the SQL is a query, then for each row in the query result
   90868 ** the xCallback() function is called.  pArg becomes the first
   90869 ** argument to xCallback().  If xCallback=NULL then no callback
   90870 ** is invoked, even for queries.
   90871 */
   90872 SQLITE_API int sqlite3_exec(
   90873   sqlite3 *db,                /* The database on which the SQL executes */
   90874   const char *zSql,           /* The SQL to be executed */
   90875   sqlite3_callback xCallback, /* Invoke this callback routine */
   90876   void *pArg,                 /* First argument to xCallback() */
   90877   char **pzErrMsg             /* Write error messages here */
   90878 ){
   90879   int rc = SQLITE_OK;         /* Return code */
   90880   const char *zLeftover;      /* Tail of unprocessed SQL */
   90881   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   90882   char **azCols = 0;          /* Names of result columns */
   90883   int nRetry = 0;             /* Number of retry attempts */
   90884   int callbackIsInit;         /* True if callback data is initialized */
   90885 
   90886   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   90887   if( zSql==0 ) zSql = "";
   90888 
   90889   sqlite3_mutex_enter(db->mutex);
   90890   sqlite3Error(db, SQLITE_OK, 0);
   90891   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
   90892     int nCol;
   90893     char **azVals = 0;
   90894 
   90895     pStmt = 0;
   90896     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
   90897     assert( rc==SQLITE_OK || pStmt==0 );
   90898     if( rc!=SQLITE_OK ){
   90899       continue;
   90900     }
   90901     if( !pStmt ){
   90902       /* this happens for a comment or white-space */
   90903       zSql = zLeftover;
   90904       continue;
   90905     }
   90906 
   90907     callbackIsInit = 0;
   90908     nCol = sqlite3_column_count(pStmt);
   90909 
   90910     while( 1 ){
   90911       int i;
   90912       rc = sqlite3_step(pStmt);
   90913 
   90914       /* Invoke the callback function if required */
   90915       if( xCallback && (SQLITE_ROW==rc ||
   90916           (SQLITE_DONE==rc && !callbackIsInit
   90917                            && db->flags&SQLITE_NullCallback)) ){
   90918         if( !callbackIsInit ){
   90919           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   90920           if( azCols==0 ){
   90921             goto exec_out;
   90922           }
   90923           for(i=0; i<nCol; i++){
   90924             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   90925             /* sqlite3VdbeSetColName() installs column names as UTF8
   90926             ** strings so there is no way for sqlite3_column_name() to fail. */
   90927             assert( azCols[i]!=0 );
   90928           }
   90929           callbackIsInit = 1;
   90930         }
   90931         if( rc==SQLITE_ROW ){
   90932           azVals = &azCols[nCol];
   90933           for(i=0; i<nCol; i++){
   90934             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   90935             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   90936               db->mallocFailed = 1;
   90937               goto exec_out;
   90938             }
   90939           }
   90940         }
   90941         if( xCallback(pArg, nCol, azVals, azCols) ){
   90942           rc = SQLITE_ABORT;
   90943           sqlite3VdbeFinalize((Vdbe *)pStmt);
   90944           pStmt = 0;
   90945           sqlite3Error(db, SQLITE_ABORT, 0);
   90946           goto exec_out;
   90947         }
   90948       }
   90949 
   90950       if( rc!=SQLITE_ROW ){
   90951         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   90952         pStmt = 0;
   90953         if( rc!=SQLITE_SCHEMA ){
   90954           nRetry = 0;
   90955           zSql = zLeftover;
   90956           while( sqlite3Isspace(zSql[0]) ) zSql++;
   90957         }
   90958         break;
   90959       }
   90960     }
   90961 
   90962     sqlite3DbFree(db, azCols);
   90963     azCols = 0;
   90964   }
   90965 
   90966 exec_out:
   90967   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   90968   sqlite3DbFree(db, azCols);
   90969 
   90970   rc = sqlite3ApiExit(db, rc);
   90971   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   90972     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   90973     *pzErrMsg = sqlite3Malloc(nErrMsg);
   90974     if( *pzErrMsg ){
   90975       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   90976     }else{
   90977       rc = SQLITE_NOMEM;
   90978       sqlite3Error(db, SQLITE_NOMEM, 0);
   90979     }
   90980   }else if( pzErrMsg ){
   90981     *pzErrMsg = 0;
   90982   }
   90983 
   90984   assert( (rc&db->errMask)==rc );
   90985   sqlite3_mutex_leave(db->mutex);
   90986   return rc;
   90987 }
   90988 
   90989 /************** End of legacy.c **********************************************/
   90990 /************** Begin file loadext.c *****************************************/
   90991 /*
   90992 ** 2006 June 7
   90993 **
   90994 ** The author disclaims copyright to this source code.  In place of
   90995 ** a legal notice, here is a blessing:
   90996 **
   90997 **    May you do good and not evil.
   90998 **    May you find forgiveness for yourself and forgive others.
   90999 **    May you share freely, never taking more than you give.
   91000 **
   91001 *************************************************************************
   91002 ** This file contains code used to dynamically load extensions into
   91003 ** the SQLite library.
   91004 */
   91005 
   91006 #ifndef SQLITE_CORE
   91007   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   91008 #endif
   91009 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   91010 /************** Begin file sqlite3ext.h **************************************/
   91011 /*
   91012 ** 2006 June 7
   91013 **
   91014 ** The author disclaims copyright to this source code.  In place of
   91015 ** a legal notice, here is a blessing:
   91016 **
   91017 **    May you do good and not evil.
   91018 **    May you find forgiveness for yourself and forgive others.
   91019 **    May you share freely, never taking more than you give.
   91020 **
   91021 *************************************************************************
   91022 ** This header file defines the SQLite interface for use by
   91023 ** shared libraries that want to be imported as extensions into
   91024 ** an SQLite instance.  Shared libraries that intend to be loaded
   91025 ** as extensions by SQLite should #include this file instead of
   91026 ** sqlite3.h.
   91027 */
   91028 #ifndef _SQLITE3EXT_H_
   91029 #define _SQLITE3EXT_H_
   91030 
   91031 typedef struct sqlite3_api_routines sqlite3_api_routines;
   91032 
   91033 /*
   91034 ** The following structure holds pointers to all of the SQLite API
   91035 ** routines.
   91036 **
   91037 ** WARNING:  In order to maintain backwards compatibility, add new
   91038 ** interfaces to the end of this structure only.  If you insert new
   91039 ** interfaces in the middle of this structure, then older different
   91040 ** versions of SQLite will not be able to load each others' shared
   91041 ** libraries!
   91042 */
   91043 struct sqlite3_api_routines {
   91044   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   91045   int  (*aggregate_count)(sqlite3_context*);
   91046   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   91047   int  (*bind_double)(sqlite3_stmt*,int,double);
   91048   int  (*bind_int)(sqlite3_stmt*,int,int);
   91049   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   91050   int  (*bind_null)(sqlite3_stmt*,int);
   91051   int  (*bind_parameter_count)(sqlite3_stmt*);
   91052   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   91053   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   91054   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   91055   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   91056   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   91057   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   91058   int  (*busy_timeout)(sqlite3*,int ms);
   91059   int  (*changes)(sqlite3*);
   91060   int  (*close)(sqlite3*);
   91061   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
   91062                            int eTextRep,const char*));
   91063   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
   91064                              int eTextRep,const void*));
   91065   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   91066   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   91067   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   91068   int  (*column_count)(sqlite3_stmt*pStmt);
   91069   const char * (*column_database_name)(sqlite3_stmt*,int);
   91070   const void * (*column_database_name16)(sqlite3_stmt*,int);
   91071   const char * (*column_decltype)(sqlite3_stmt*,int i);
   91072   const void * (*column_decltype16)(sqlite3_stmt*,int);
   91073   double  (*column_double)(sqlite3_stmt*,int iCol);
   91074   int  (*column_int)(sqlite3_stmt*,int iCol);
   91075   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   91076   const char * (*column_name)(sqlite3_stmt*,int);
   91077   const void * (*column_name16)(sqlite3_stmt*,int);
   91078   const char * (*column_origin_name)(sqlite3_stmt*,int);
   91079   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   91080   const char * (*column_table_name)(sqlite3_stmt*,int);
   91081   const void * (*column_table_name16)(sqlite3_stmt*,int);
   91082   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   91083   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   91084   int  (*column_type)(sqlite3_stmt*,int iCol);
   91085   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   91086   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   91087   int  (*complete)(const char*sql);
   91088   int  (*complete16)(const void*sql);
   91089   int  (*create_collation)(sqlite3*,const char*,int,void*,
   91090                            int(*)(void*,int,const void*,int,const void*));
   91091   int  (*create_collation16)(sqlite3*,const void*,int,void*,
   91092                              int(*)(void*,int,const void*,int,const void*));
   91093   int  (*create_function)(sqlite3*,const char*,int,int,void*,
   91094                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91095                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91096                           void (*xFinal)(sqlite3_context*));
   91097   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
   91098                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91099                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91100                             void (*xFinal)(sqlite3_context*));
   91101   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   91102   int  (*data_count)(sqlite3_stmt*pStmt);
   91103   sqlite3 * (*db_handle)(sqlite3_stmt*);
   91104   int (*declare_vtab)(sqlite3*,const char*);
   91105   int  (*enable_shared_cache)(int);
   91106   int  (*errcode)(sqlite3*db);
   91107   const char * (*errmsg)(sqlite3*);
   91108   const void * (*errmsg16)(sqlite3*);
   91109   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   91110   int  (*expired)(sqlite3_stmt*);
   91111   int  (*finalize)(sqlite3_stmt*pStmt);
   91112   void  (*free)(void*);
   91113   void  (*free_table)(char**result);
   91114   int  (*get_autocommit)(sqlite3*);
   91115   void * (*get_auxdata)(sqlite3_context*,int);
   91116   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   91117   int  (*global_recover)(void);
   91118   void  (*interruptx)(sqlite3*);
   91119   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   91120   const char * (*libversion)(void);
   91121   int  (*libversion_number)(void);
   91122   void *(*malloc)(int);
   91123   char * (*mprintf)(const char*,...);
   91124   int  (*open)(const char*,sqlite3**);
   91125   int  (*open16)(const void*,sqlite3**);
   91126   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   91127   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   91128   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   91129   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   91130   void *(*realloc)(void*,int);
   91131   int  (*reset)(sqlite3_stmt*pStmt);
   91132   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   91133   void  (*result_double)(sqlite3_context*,double);
   91134   void  (*result_error)(sqlite3_context*,const char*,int);
   91135   void  (*result_error16)(sqlite3_context*,const void*,int);
   91136   void  (*result_int)(sqlite3_context*,int);
   91137   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   91138   void  (*result_null)(sqlite3_context*);
   91139   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   91140   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   91141   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   91142   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   91143   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   91144   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   91145   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   91146                          const char*,const char*),void*);
   91147   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   91148   char * (*snprintf)(int,char*,const char*,...);
   91149   int  (*step)(sqlite3_stmt*);
   91150   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   91151                                 char const**,char const**,int*,int*,int*);
   91152   void  (*thread_cleanup)(void);
   91153   int  (*total_changes)(sqlite3*);
   91154   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   91155   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   91156   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   91157                                          sqlite_int64),void*);
   91158   void * (*user_data)(sqlite3_context*);
   91159   const void * (*value_blob)(sqlite3_value*);
   91160   int  (*value_bytes)(sqlite3_value*);
   91161   int  (*value_bytes16)(sqlite3_value*);
   91162   double  (*value_double)(sqlite3_value*);
   91163   int  (*value_int)(sqlite3_value*);
   91164   sqlite_int64  (*value_int64)(sqlite3_value*);
   91165   int  (*value_numeric_type)(sqlite3_value*);
   91166   const unsigned char * (*value_text)(sqlite3_value*);
   91167   const void * (*value_text16)(sqlite3_value*);
   91168   const void * (*value_text16be)(sqlite3_value*);
   91169   const void * (*value_text16le)(sqlite3_value*);
   91170   int  (*value_type)(sqlite3_value*);
   91171   char *(*vmprintf)(const char*,va_list);
   91172   /* Added ??? */
   91173   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   91174   /* Added by 3.3.13 */
   91175   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   91176   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   91177   int (*clear_bindings)(sqlite3_stmt*);
   91178   /* Added by 3.4.1 */
   91179   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   91180                           void (*xDestroy)(void *));
   91181   /* Added by 3.5.0 */
   91182   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   91183   int (*blob_bytes)(sqlite3_blob*);
   91184   int (*blob_close)(sqlite3_blob*);
   91185   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   91186                    int,sqlite3_blob**);
   91187   int (*blob_read)(sqlite3_blob*,void*,int,int);
   91188   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   91189   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   91190                              int(*)(void*,int,const void*,int,const void*),
   91191                              void(*)(void*));
   91192   int (*file_control)(sqlite3*,const char*,int,void*);
   91193   sqlite3_int64 (*memory_highwater)(int);
   91194   sqlite3_int64 (*memory_used)(void);
   91195   sqlite3_mutex *(*mutex_alloc)(int);
   91196   void (*mutex_enter)(sqlite3_mutex*);
   91197   void (*mutex_free)(sqlite3_mutex*);
   91198   void (*mutex_leave)(sqlite3_mutex*);
   91199   int (*mutex_try)(sqlite3_mutex*);
   91200   int (*open_v2)(const char*,sqlite3**,int,const char*);
   91201   int (*release_memory)(int);
   91202   void (*result_error_nomem)(sqlite3_context*);
   91203   void (*result_error_toobig)(sqlite3_context*);
   91204   int (*sleep)(int);
   91205   void (*soft_heap_limit)(int);
   91206   sqlite3_vfs *(*vfs_find)(const char*);
   91207   int (*vfs_register)(sqlite3_vfs*,int);
   91208   int (*vfs_unregister)(sqlite3_vfs*);
   91209   int (*xthreadsafe)(void);
   91210   void (*result_zeroblob)(sqlite3_context*,int);
   91211   void (*result_error_code)(sqlite3_context*,int);
   91212   int (*test_control)(int, ...);
   91213   void (*randomness)(int,void*);
   91214   sqlite3 *(*context_db_handle)(sqlite3_context*);
   91215   int (*extended_result_codes)(sqlite3*,int);
   91216   int (*limit)(sqlite3*,int,int);
   91217   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   91218   const char *(*sql)(sqlite3_stmt*);
   91219   int (*status)(int,int*,int*,int);
   91220   int (*backup_finish)(sqlite3_backup*);
   91221   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   91222   int (*backup_pagecount)(sqlite3_backup*);
   91223   int (*backup_remaining)(sqlite3_backup*);
   91224   int (*backup_step)(sqlite3_backup*,int);
   91225   const char *(*compileoption_get)(int);
   91226   int (*compileoption_used)(const char*);
   91227   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   91228                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91229                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91230                             void (*xFinal)(sqlite3_context*),
   91231                             void(*xDestroy)(void*));
   91232   int (*db_config)(sqlite3*,int,...);
   91233   sqlite3_mutex *(*db_mutex)(sqlite3*);
   91234   int (*db_status)(sqlite3*,int,int*,int*,int);
   91235   int (*extended_errcode)(sqlite3*);
   91236   void (*log)(int,const char*,...);
   91237   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   91238   const char *(*sourceid)(void);
   91239   int (*stmt_status)(sqlite3_stmt*,int,int);
   91240   int (*strnicmp)(const char*,const char*,int);
   91241   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   91242   int (*wal_autocheckpoint)(sqlite3*,int);
   91243   int (*wal_checkpoint)(sqlite3*,const char*);
   91244   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   91245   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   91246   int (*vtab_config)(sqlite3*,int op,...);
   91247   int (*vtab_on_conflict)(sqlite3*);
   91248 };
   91249 
   91250 /*
   91251 ** The following macros redefine the API routines so that they are
   91252 ** redirected throught the global sqlite3_api structure.
   91253 **
   91254 ** This header file is also used by the loadext.c source file
   91255 ** (part of the main SQLite library - not an extension) so that
   91256 ** it can get access to the sqlite3_api_routines structure
   91257 ** definition.  But the main library does not want to redefine
   91258 ** the API.  So the redefinition macros are only valid if the
   91259 ** SQLITE_CORE macros is undefined.
   91260 */
   91261 #ifndef SQLITE_CORE
   91262 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   91263 #ifndef SQLITE_OMIT_DEPRECATED
   91264 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   91265 #endif
   91266 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   91267 #define sqlite3_bind_double            sqlite3_api->bind_double
   91268 #define sqlite3_bind_int               sqlite3_api->bind_int
   91269 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   91270 #define sqlite3_bind_null              sqlite3_api->bind_null
   91271 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   91272 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   91273 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   91274 #define sqlite3_bind_text              sqlite3_api->bind_text
   91275 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   91276 #define sqlite3_bind_value             sqlite3_api->bind_value
   91277 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   91278 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   91279 #define sqlite3_changes                sqlite3_api->changes
   91280 #define sqlite3_close                  sqlite3_api->close
   91281 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   91282 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   91283 #define sqlite3_column_blob            sqlite3_api->column_blob
   91284 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   91285 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   91286 #define sqlite3_column_count           sqlite3_api->column_count
   91287 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   91288 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   91289 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   91290 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   91291 #define sqlite3_column_double          sqlite3_api->column_double
   91292 #define sqlite3_column_int             sqlite3_api->column_int
   91293 #define sqlite3_column_int64           sqlite3_api->column_int64
   91294 #define sqlite3_column_name            sqlite3_api->column_name
   91295 #define sqlite3_column_name16          sqlite3_api->column_name16
   91296 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   91297 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   91298 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   91299 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   91300 #define sqlite3_column_text            sqlite3_api->column_text
   91301 #define sqlite3_column_text16          sqlite3_api->column_text16
   91302 #define sqlite3_column_type            sqlite3_api->column_type
   91303 #define sqlite3_column_value           sqlite3_api->column_value
   91304 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   91305 #define sqlite3_complete               sqlite3_api->complete
   91306 #define sqlite3_complete16             sqlite3_api->complete16
   91307 #define sqlite3_create_collation       sqlite3_api->create_collation
   91308 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   91309 #define sqlite3_create_function        sqlite3_api->create_function
   91310 #define sqlite3_create_function16      sqlite3_api->create_function16
   91311 #define sqlite3_create_module          sqlite3_api->create_module
   91312 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   91313 #define sqlite3_data_count             sqlite3_api->data_count
   91314 #define sqlite3_db_handle              sqlite3_api->db_handle
   91315 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   91316 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   91317 #define sqlite3_errcode                sqlite3_api->errcode
   91318 #define sqlite3_errmsg                 sqlite3_api->errmsg
   91319 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   91320 #define sqlite3_exec                   sqlite3_api->exec
   91321 #ifndef SQLITE_OMIT_DEPRECATED
   91322 #define sqlite3_expired                sqlite3_api->expired
   91323 #endif
   91324 #define sqlite3_finalize               sqlite3_api->finalize
   91325 #define sqlite3_free                   sqlite3_api->free
   91326 #define sqlite3_free_table             sqlite3_api->free_table
   91327 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   91328 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   91329 #define sqlite3_get_table              sqlite3_api->get_table
   91330 #ifndef SQLITE_OMIT_DEPRECATED
   91331 #define sqlite3_global_recover         sqlite3_api->global_recover
   91332 #endif
   91333 #define sqlite3_interrupt              sqlite3_api->interruptx
   91334 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   91335 #define sqlite3_libversion             sqlite3_api->libversion
   91336 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   91337 #define sqlite3_malloc                 sqlite3_api->malloc
   91338 #define sqlite3_mprintf                sqlite3_api->mprintf
   91339 #define sqlite3_open                   sqlite3_api->open
   91340 #define sqlite3_open16                 sqlite3_api->open16
   91341 #define sqlite3_prepare                sqlite3_api->prepare
   91342 #define sqlite3_prepare16              sqlite3_api->prepare16
   91343 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   91344 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   91345 #define sqlite3_profile                sqlite3_api->profile
   91346 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   91347 #define sqlite3_realloc                sqlite3_api->realloc
   91348 #define sqlite3_reset                  sqlite3_api->reset
   91349 #define sqlite3_result_blob            sqlite3_api->result_blob
   91350 #define sqlite3_result_double          sqlite3_api->result_double
   91351 #define sqlite3_result_error           sqlite3_api->result_error
   91352 #define sqlite3_result_error16         sqlite3_api->result_error16
   91353 #define sqlite3_result_int             sqlite3_api->result_int
   91354 #define sqlite3_result_int64           sqlite3_api->result_int64
   91355 #define sqlite3_result_null            sqlite3_api->result_null
   91356 #define sqlite3_result_text            sqlite3_api->result_text
   91357 #define sqlite3_result_text16          sqlite3_api->result_text16
   91358 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   91359 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   91360 #define sqlite3_result_value           sqlite3_api->result_value
   91361 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   91362 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   91363 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   91364 #define sqlite3_snprintf               sqlite3_api->snprintf
   91365 #define sqlite3_step                   sqlite3_api->step
   91366 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   91367 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   91368 #define sqlite3_total_changes          sqlite3_api->total_changes
   91369 #define sqlite3_trace                  sqlite3_api->trace
   91370 #ifndef SQLITE_OMIT_DEPRECATED
   91371 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   91372 #endif
   91373 #define sqlite3_update_hook            sqlite3_api->update_hook
   91374 #define sqlite3_user_data              sqlite3_api->user_data
   91375 #define sqlite3_value_blob             sqlite3_api->value_blob
   91376 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   91377 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   91378 #define sqlite3_value_double           sqlite3_api->value_double
   91379 #define sqlite3_value_int              sqlite3_api->value_int
   91380 #define sqlite3_value_int64            sqlite3_api->value_int64
   91381 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   91382 #define sqlite3_value_text             sqlite3_api->value_text
   91383 #define sqlite3_value_text16           sqlite3_api->value_text16
   91384 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   91385 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   91386 #define sqlite3_value_type             sqlite3_api->value_type
   91387 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   91388 #define sqlite3_overload_function      sqlite3_api->overload_function
   91389 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   91390 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   91391 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   91392 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   91393 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   91394 #define sqlite3_blob_close             sqlite3_api->blob_close
   91395 #define sqlite3_blob_open              sqlite3_api->blob_open
   91396 #define sqlite3_blob_read              sqlite3_api->blob_read
   91397 #define sqlite3_blob_write             sqlite3_api->blob_write
   91398 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   91399 #define sqlite3_file_control           sqlite3_api->file_control
   91400 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   91401 #define sqlite3_memory_used            sqlite3_api->memory_used
   91402 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   91403 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   91404 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   91405 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   91406 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   91407 #define sqlite3_open_v2                sqlite3_api->open_v2
   91408 #define sqlite3_release_memory         sqlite3_api->release_memory
   91409 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   91410 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   91411 #define sqlite3_sleep                  sqlite3_api->sleep
   91412 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   91413 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   91414 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   91415 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   91416 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   91417 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   91418 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   91419 #define sqlite3_test_control           sqlite3_api->test_control
   91420 #define sqlite3_randomness             sqlite3_api->randomness
   91421 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   91422 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   91423 #define sqlite3_limit                  sqlite3_api->limit
   91424 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   91425 #define sqlite3_sql                    sqlite3_api->sql
   91426 #define sqlite3_status                 sqlite3_api->status
   91427 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   91428 #define sqlite3_backup_init            sqlite3_api->backup_init
   91429 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   91430 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   91431 #define sqlite3_backup_step            sqlite3_api->backup_step
   91432 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   91433 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   91434 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   91435 #define sqlite3_db_config              sqlite3_api->db_config
   91436 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   91437 #define sqlite3_db_status              sqlite3_api->db_status
   91438 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   91439 #define sqlite3_log                    sqlite3_api->log
   91440 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   91441 #define sqlite3_sourceid               sqlite3_api->sourceid
   91442 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   91443 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   91444 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   91445 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   91446 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   91447 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   91448 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   91449 #define sqlite3_vtab_config            sqlite3_api->vtab_config
   91450 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   91451 #endif /* SQLITE_CORE */
   91452 
   91453 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
   91454 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
   91455 
   91456 #endif /* _SQLITE3EXT_H_ */
   91457 
   91458 /************** End of sqlite3ext.h ******************************************/
   91459 /************** Continuing where we left off in loadext.c ********************/
   91460 /* #include <string.h> */
   91461 
   91462 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   91463 
   91464 /*
   91465 ** Some API routines are omitted when various features are
   91466 ** excluded from a build of SQLite.  Substitute a NULL pointer
   91467 ** for any missing APIs.
   91468 */
   91469 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   91470 # define sqlite3_column_database_name   0
   91471 # define sqlite3_column_database_name16 0
   91472 # define sqlite3_column_table_name      0
   91473 # define sqlite3_column_table_name16    0
   91474 # define sqlite3_column_origin_name     0
   91475 # define sqlite3_column_origin_name16   0
   91476 # define sqlite3_table_column_metadata  0
   91477 #endif
   91478 
   91479 #ifdef SQLITE_OMIT_AUTHORIZATION
   91480 # define sqlite3_set_authorizer         0
   91481 #endif
   91482 
   91483 #ifdef SQLITE_OMIT_UTF16
   91484 # define sqlite3_bind_text16            0
   91485 # define sqlite3_collation_needed16     0
   91486 # define sqlite3_column_decltype16      0
   91487 # define sqlite3_column_name16          0
   91488 # define sqlite3_column_text16          0
   91489 # define sqlite3_complete16             0
   91490 # define sqlite3_create_collation16     0
   91491 # define sqlite3_create_function16      0
   91492 # define sqlite3_errmsg16               0
   91493 # define sqlite3_open16                 0
   91494 # define sqlite3_prepare16              0
   91495 # define sqlite3_prepare16_v2           0
   91496 # define sqlite3_result_error16         0
   91497 # define sqlite3_result_text16          0
   91498 # define sqlite3_result_text16be        0
   91499 # define sqlite3_result_text16le        0
   91500 # define sqlite3_value_text16           0
   91501 # define sqlite3_value_text16be         0
   91502 # define sqlite3_value_text16le         0
   91503 # define sqlite3_column_database_name16 0
   91504 # define sqlite3_column_table_name16    0
   91505 # define sqlite3_column_origin_name16   0
   91506 #endif
   91507 
   91508 #ifdef SQLITE_OMIT_COMPLETE
   91509 # define sqlite3_complete 0
   91510 # define sqlite3_complete16 0
   91511 #endif
   91512 
   91513 #ifdef SQLITE_OMIT_DECLTYPE
   91514 # define sqlite3_column_decltype16      0
   91515 # define sqlite3_column_decltype        0
   91516 #endif
   91517 
   91518 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   91519 # define sqlite3_progress_handler 0
   91520 #endif
   91521 
   91522 #ifdef SQLITE_OMIT_VIRTUALTABLE
   91523 # define sqlite3_create_module 0
   91524 # define sqlite3_create_module_v2 0
   91525 # define sqlite3_declare_vtab 0
   91526 # define sqlite3_vtab_config 0
   91527 # define sqlite3_vtab_on_conflict 0
   91528 #endif
   91529 
   91530 #ifdef SQLITE_OMIT_SHARED_CACHE
   91531 # define sqlite3_enable_shared_cache 0
   91532 #endif
   91533 
   91534 #ifdef SQLITE_OMIT_TRACE
   91535 # define sqlite3_profile       0
   91536 # define sqlite3_trace         0
   91537 #endif
   91538 
   91539 #ifdef SQLITE_OMIT_GET_TABLE
   91540 # define sqlite3_free_table    0
   91541 # define sqlite3_get_table     0
   91542 #endif
   91543 
   91544 #ifdef SQLITE_OMIT_INCRBLOB
   91545 #define sqlite3_bind_zeroblob  0
   91546 #define sqlite3_blob_bytes     0
   91547 #define sqlite3_blob_close     0
   91548 #define sqlite3_blob_open      0
   91549 #define sqlite3_blob_read      0
   91550 #define sqlite3_blob_write     0
   91551 #define sqlite3_blob_reopen    0
   91552 #endif
   91553 
   91554 /*
   91555 ** The following structure contains pointers to all SQLite API routines.
   91556 ** A pointer to this structure is passed into extensions when they are
   91557 ** loaded so that the extension can make calls back into the SQLite
   91558 ** library.
   91559 **
   91560 ** When adding new APIs, add them to the bottom of this structure
   91561 ** in order to preserve backwards compatibility.
   91562 **
   91563 ** Extensions that use newer APIs should first call the
   91564 ** sqlite3_libversion_number() to make sure that the API they
   91565 ** intend to use is supported by the library.  Extensions should
   91566 ** also check to make sure that the pointer to the function is
   91567 ** not NULL before calling it.
   91568 */
   91569 static const sqlite3_api_routines sqlite3Apis = {
   91570   sqlite3_aggregate_context,
   91571 #ifndef SQLITE_OMIT_DEPRECATED
   91572   sqlite3_aggregate_count,
   91573 #else
   91574   0,
   91575 #endif
   91576   sqlite3_bind_blob,
   91577   sqlite3_bind_double,
   91578   sqlite3_bind_int,
   91579   sqlite3_bind_int64,
   91580   sqlite3_bind_null,
   91581   sqlite3_bind_parameter_count,
   91582   sqlite3_bind_parameter_index,
   91583   sqlite3_bind_parameter_name,
   91584   sqlite3_bind_text,
   91585   sqlite3_bind_text16,
   91586   sqlite3_bind_value,
   91587   sqlite3_busy_handler,
   91588   sqlite3_busy_timeout,
   91589   sqlite3_changes,
   91590   sqlite3_close,
   91591   sqlite3_collation_needed,
   91592   sqlite3_collation_needed16,
   91593   sqlite3_column_blob,
   91594   sqlite3_column_bytes,
   91595   sqlite3_column_bytes16,
   91596   sqlite3_column_count,
   91597   sqlite3_column_database_name,
   91598   sqlite3_column_database_name16,
   91599   sqlite3_column_decltype,
   91600   sqlite3_column_decltype16,
   91601   sqlite3_column_double,
   91602   sqlite3_column_int,
   91603   sqlite3_column_int64,
   91604   sqlite3_column_name,
   91605   sqlite3_column_name16,
   91606   sqlite3_column_origin_name,
   91607   sqlite3_column_origin_name16,
   91608   sqlite3_column_table_name,
   91609   sqlite3_column_table_name16,
   91610   sqlite3_column_text,
   91611   sqlite3_column_text16,
   91612   sqlite3_column_type,
   91613   sqlite3_column_value,
   91614   sqlite3_commit_hook,
   91615   sqlite3_complete,
   91616   sqlite3_complete16,
   91617   sqlite3_create_collation,
   91618   sqlite3_create_collation16,
   91619   sqlite3_create_function,
   91620   sqlite3_create_function16,
   91621   sqlite3_create_module,
   91622   sqlite3_data_count,
   91623   sqlite3_db_handle,
   91624   sqlite3_declare_vtab,
   91625   sqlite3_enable_shared_cache,
   91626   sqlite3_errcode,
   91627   sqlite3_errmsg,
   91628   sqlite3_errmsg16,
   91629   sqlite3_exec,
   91630 #ifndef SQLITE_OMIT_DEPRECATED
   91631   sqlite3_expired,
   91632 #else
   91633   0,
   91634 #endif
   91635   sqlite3_finalize,
   91636   sqlite3_free,
   91637   sqlite3_free_table,
   91638   sqlite3_get_autocommit,
   91639   sqlite3_get_auxdata,
   91640   sqlite3_get_table,
   91641   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   91642   sqlite3_interrupt,
   91643   sqlite3_last_insert_rowid,
   91644   sqlite3_libversion,
   91645   sqlite3_libversion_number,
   91646   sqlite3_malloc,
   91647   sqlite3_mprintf,
   91648   sqlite3_open,
   91649   sqlite3_open16,
   91650   sqlite3_prepare,
   91651   sqlite3_prepare16,
   91652   sqlite3_profile,
   91653   sqlite3_progress_handler,
   91654   sqlite3_realloc,
   91655   sqlite3_reset,
   91656   sqlite3_result_blob,
   91657   sqlite3_result_double,
   91658   sqlite3_result_error,
   91659   sqlite3_result_error16,
   91660   sqlite3_result_int,
   91661   sqlite3_result_int64,
   91662   sqlite3_result_null,
   91663   sqlite3_result_text,
   91664   sqlite3_result_text16,
   91665   sqlite3_result_text16be,
   91666   sqlite3_result_text16le,
   91667   sqlite3_result_value,
   91668   sqlite3_rollback_hook,
   91669   sqlite3_set_authorizer,
   91670   sqlite3_set_auxdata,
   91671   sqlite3_snprintf,
   91672   sqlite3_step,
   91673   sqlite3_table_column_metadata,
   91674 #ifndef SQLITE_OMIT_DEPRECATED
   91675   sqlite3_thread_cleanup,
   91676 #else
   91677   0,
   91678 #endif
   91679   sqlite3_total_changes,
   91680   sqlite3_trace,
   91681 #ifndef SQLITE_OMIT_DEPRECATED
   91682   sqlite3_transfer_bindings,
   91683 #else
   91684   0,
   91685 #endif
   91686   sqlite3_update_hook,
   91687   sqlite3_user_data,
   91688   sqlite3_value_blob,
   91689   sqlite3_value_bytes,
   91690   sqlite3_value_bytes16,
   91691   sqlite3_value_double,
   91692   sqlite3_value_int,
   91693   sqlite3_value_int64,
   91694   sqlite3_value_numeric_type,
   91695   sqlite3_value_text,
   91696   sqlite3_value_text16,
   91697   sqlite3_value_text16be,
   91698   sqlite3_value_text16le,
   91699   sqlite3_value_type,
   91700   sqlite3_vmprintf,
   91701   /*
   91702   ** The original API set ends here.  All extensions can call any
   91703   ** of the APIs above provided that the pointer is not NULL.  But
   91704   ** before calling APIs that follow, extension should check the
   91705   ** sqlite3_libversion_number() to make sure they are dealing with
   91706   ** a library that is new enough to support that API.
   91707   *************************************************************************
   91708   */
   91709   sqlite3_overload_function,
   91710 
   91711   /*
   91712   ** Added after 3.3.13
   91713   */
   91714   sqlite3_prepare_v2,
   91715   sqlite3_prepare16_v2,
   91716   sqlite3_clear_bindings,
   91717 
   91718   /*
   91719   ** Added for 3.4.1
   91720   */
   91721   sqlite3_create_module_v2,
   91722 
   91723   /*
   91724   ** Added for 3.5.0
   91725   */
   91726   sqlite3_bind_zeroblob,
   91727   sqlite3_blob_bytes,
   91728   sqlite3_blob_close,
   91729   sqlite3_blob_open,
   91730   sqlite3_blob_read,
   91731   sqlite3_blob_write,
   91732   sqlite3_create_collation_v2,
   91733   sqlite3_file_control,
   91734   sqlite3_memory_highwater,
   91735   sqlite3_memory_used,
   91736 #ifdef SQLITE_MUTEX_OMIT
   91737   0,
   91738   0,
   91739   0,
   91740   0,
   91741   0,
   91742 #else
   91743   sqlite3_mutex_alloc,
   91744   sqlite3_mutex_enter,
   91745   sqlite3_mutex_free,
   91746   sqlite3_mutex_leave,
   91747   sqlite3_mutex_try,
   91748 #endif
   91749   sqlite3_open_v2,
   91750   sqlite3_release_memory,
   91751   sqlite3_result_error_nomem,
   91752   sqlite3_result_error_toobig,
   91753   sqlite3_sleep,
   91754   sqlite3_soft_heap_limit,
   91755   sqlite3_vfs_find,
   91756   sqlite3_vfs_register,
   91757   sqlite3_vfs_unregister,
   91758 
   91759   /*
   91760   ** Added for 3.5.8
   91761   */
   91762   sqlite3_threadsafe,
   91763   sqlite3_result_zeroblob,
   91764   sqlite3_result_error_code,
   91765   sqlite3_test_control,
   91766   sqlite3_randomness,
   91767   sqlite3_context_db_handle,
   91768 
   91769   /*
   91770   ** Added for 3.6.0
   91771   */
   91772   sqlite3_extended_result_codes,
   91773   sqlite3_limit,
   91774   sqlite3_next_stmt,
   91775   sqlite3_sql,
   91776   sqlite3_status,
   91777 
   91778   /*
   91779   ** Added for 3.7.4
   91780   */
   91781   sqlite3_backup_finish,
   91782   sqlite3_backup_init,
   91783   sqlite3_backup_pagecount,
   91784   sqlite3_backup_remaining,
   91785   sqlite3_backup_step,
   91786 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   91787   sqlite3_compileoption_get,
   91788   sqlite3_compileoption_used,
   91789 #else
   91790   0,
   91791   0,
   91792 #endif
   91793   sqlite3_create_function_v2,
   91794   sqlite3_db_config,
   91795   sqlite3_db_mutex,
   91796   sqlite3_db_status,
   91797   sqlite3_extended_errcode,
   91798   sqlite3_log,
   91799   sqlite3_soft_heap_limit64,
   91800   sqlite3_sourceid,
   91801   sqlite3_stmt_status,
   91802   sqlite3_strnicmp,
   91803 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   91804   sqlite3_unlock_notify,
   91805 #else
   91806   0,
   91807 #endif
   91808 #ifndef SQLITE_OMIT_WAL
   91809   sqlite3_wal_autocheckpoint,
   91810   sqlite3_wal_checkpoint,
   91811   sqlite3_wal_hook,
   91812 #else
   91813   0,
   91814   0,
   91815   0,
   91816 #endif
   91817   sqlite3_blob_reopen,
   91818   sqlite3_vtab_config,
   91819   sqlite3_vtab_on_conflict,
   91820 };
   91821 
   91822 /*
   91823 ** Attempt to load an SQLite extension library contained in the file
   91824 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   91825 ** default entry point name (sqlite3_extension_init) is used.  Use
   91826 ** of the default name is recommended.
   91827 **
   91828 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   91829 **
   91830 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   91831 ** error message text.  The calling function should free this memory
   91832 ** by calling sqlite3DbFree(db, ).
   91833 */
   91834 static int sqlite3LoadExtension(
   91835   sqlite3 *db,          /* Load the extension into this database connection */
   91836   const char *zFile,    /* Name of the shared library containing extension */
   91837   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   91838   char **pzErrMsg       /* Put error message here if not 0 */
   91839 ){
   91840   sqlite3_vfs *pVfs = db->pVfs;
   91841   void *handle;
   91842   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   91843   char *zErrmsg = 0;
   91844   void **aHandle;
   91845   int nMsg = 300 + sqlite3Strlen30(zFile);
   91846 
   91847   if( pzErrMsg ) *pzErrMsg = 0;
   91848 
   91849   /* Ticket #1863.  To avoid a creating security problems for older
   91850   ** applications that relink against newer versions of SQLite, the
   91851   ** ability to run load_extension is turned off by default.  One
   91852   ** must call sqlite3_enable_load_extension() to turn on extension
   91853   ** loading.  Otherwise you get the following error.
   91854   */
   91855   if( (db->flags & SQLITE_LoadExtension)==0 ){
   91856     if( pzErrMsg ){
   91857       *pzErrMsg = sqlite3_mprintf("not authorized");
   91858     }
   91859     return SQLITE_ERROR;
   91860   }
   91861 
   91862   if( zProc==0 ){
   91863     zProc = "sqlite3_extension_init";
   91864   }
   91865 
   91866   handle = sqlite3OsDlOpen(pVfs, zFile);
   91867   if( handle==0 ){
   91868     if( pzErrMsg ){
   91869       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   91870       if( zErrmsg ){
   91871         sqlite3_snprintf(nMsg, zErrmsg,
   91872             "unable to open shared library [%s]", zFile);
   91873         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   91874       }
   91875     }
   91876     return SQLITE_ERROR;
   91877   }
   91878   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   91879                    sqlite3OsDlSym(pVfs, handle, zProc);
   91880   if( xInit==0 ){
   91881     if( pzErrMsg ){
   91882       nMsg += sqlite3Strlen30(zProc);
   91883       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   91884       if( zErrmsg ){
   91885         sqlite3_snprintf(nMsg, zErrmsg,
   91886             "no entry point [%s] in shared library [%s]", zProc,zFile);
   91887         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   91888       }
   91889       sqlite3OsDlClose(pVfs, handle);
   91890     }
   91891     return SQLITE_ERROR;
   91892   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   91893     if( pzErrMsg ){
   91894       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   91895     }
   91896     sqlite3_free(zErrmsg);
   91897     sqlite3OsDlClose(pVfs, handle);
   91898     return SQLITE_ERROR;
   91899   }
   91900 
   91901   /* Append the new shared library handle to the db->aExtension array. */
   91902   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   91903   if( aHandle==0 ){
   91904     return SQLITE_NOMEM;
   91905   }
   91906   if( db->nExtension>0 ){
   91907     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   91908   }
   91909   sqlite3DbFree(db, db->aExtension);
   91910   db->aExtension = aHandle;
   91911 
   91912   db->aExtension[db->nExtension++] = handle;
   91913   return SQLITE_OK;
   91914 }
   91915 SQLITE_API int sqlite3_load_extension(
   91916   sqlite3 *db,          /* Load the extension into this database connection */
   91917   const char *zFile,    /* Name of the shared library containing extension */
   91918   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   91919   char **pzErrMsg       /* Put error message here if not 0 */
   91920 ){
   91921   int rc;
   91922   sqlite3_mutex_enter(db->mutex);
   91923   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   91924   rc = sqlite3ApiExit(db, rc);
   91925   sqlite3_mutex_leave(db->mutex);
   91926   return rc;
   91927 }
   91928 
   91929 /*
   91930 ** Call this routine when the database connection is closing in order
   91931 ** to clean up loaded extensions
   91932 */
   91933 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   91934   int i;
   91935   assert( sqlite3_mutex_held(db->mutex) );
   91936   for(i=0; i<db->nExtension; i++){
   91937     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   91938   }
   91939   sqlite3DbFree(db, db->aExtension);
   91940 }
   91941 
   91942 /*
   91943 ** Enable or disable extension loading.  Extension loading is disabled by
   91944 ** default so as not to open security holes in older applications.
   91945 */
   91946 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   91947   sqlite3_mutex_enter(db->mutex);
   91948   if( onoff ){
   91949     db->flags |= SQLITE_LoadExtension;
   91950   }else{
   91951     db->flags &= ~SQLITE_LoadExtension;
   91952   }
   91953   sqlite3_mutex_leave(db->mutex);
   91954   return SQLITE_OK;
   91955 }
   91956 
   91957 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   91958 
   91959 /*
   91960 ** The auto-extension code added regardless of whether or not extension
   91961 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   91962 ** code if regular extension loading is not available.  This is that
   91963 ** dummy pointer.
   91964 */
   91965 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   91966 static const sqlite3_api_routines sqlite3Apis = { 0 };
   91967 #endif
   91968 
   91969 
   91970 /*
   91971 ** The following object holds the list of automatically loaded
   91972 ** extensions.
   91973 **
   91974 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   91975 ** mutex must be held while accessing this list.
   91976 */
   91977 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   91978 static SQLITE_WSD struct sqlite3AutoExtList {
   91979   int nExt;              /* Number of entries in aExt[] */
   91980   void (**aExt)(void);   /* Pointers to the extension init functions */
   91981 } sqlite3Autoext = { 0, 0 };
   91982 
   91983 /* The "wsdAutoext" macro will resolve to the autoextension
   91984 ** state vector.  If writable static data is unsupported on the target,
   91985 ** we have to locate the state vector at run-time.  In the more common
   91986 ** case where writable static data is supported, wsdStat can refer directly
   91987 ** to the "sqlite3Autoext" state vector declared above.
   91988 */
   91989 #ifdef SQLITE_OMIT_WSD
   91990 # define wsdAutoextInit \
   91991   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   91992 # define wsdAutoext x[0]
   91993 #else
   91994 # define wsdAutoextInit
   91995 # define wsdAutoext sqlite3Autoext
   91996 #endif
   91997 
   91998 
   91999 /*
   92000 ** Register a statically linked extension that is automatically
   92001 ** loaded by every new database connection.
   92002 */
   92003 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   92004   int rc = SQLITE_OK;
   92005 #ifndef SQLITE_OMIT_AUTOINIT
   92006   rc = sqlite3_initialize();
   92007   if( rc ){
   92008     return rc;
   92009   }else
   92010 #endif
   92011   {
   92012     int i;
   92013 #if SQLITE_THREADSAFE
   92014     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   92015 #endif
   92016     wsdAutoextInit;
   92017     sqlite3_mutex_enter(mutex);
   92018     for(i=0; i<wsdAutoext.nExt; i++){
   92019       if( wsdAutoext.aExt[i]==xInit ) break;
   92020     }
   92021     if( i==wsdAutoext.nExt ){
   92022       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   92023       void (**aNew)(void);
   92024       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   92025       if( aNew==0 ){
   92026         rc = SQLITE_NOMEM;
   92027       }else{
   92028         wsdAutoext.aExt = aNew;
   92029         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   92030         wsdAutoext.nExt++;
   92031       }
   92032     }
   92033     sqlite3_mutex_leave(mutex);
   92034     assert( (rc&0xff)==rc );
   92035     return rc;
   92036   }
   92037 }
   92038 
   92039 /*
   92040 ** Reset the automatic extension loading mechanism.
   92041 */
   92042 SQLITE_API void sqlite3_reset_auto_extension(void){
   92043 #ifndef SQLITE_OMIT_AUTOINIT
   92044   if( sqlite3_initialize()==SQLITE_OK )
   92045 #endif
   92046   {
   92047 #if SQLITE_THREADSAFE
   92048     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   92049 #endif
   92050     wsdAutoextInit;
   92051     sqlite3_mutex_enter(mutex);
   92052     sqlite3_free(wsdAutoext.aExt);
   92053     wsdAutoext.aExt = 0;
   92054     wsdAutoext.nExt = 0;
   92055     sqlite3_mutex_leave(mutex);
   92056   }
   92057 }
   92058 
   92059 /*
   92060 ** Load all automatic extensions.
   92061 **
   92062 ** If anything goes wrong, set an error in the database connection.
   92063 */
   92064 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   92065   int i;
   92066   int go = 1;
   92067   int rc;
   92068   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   92069 
   92070   wsdAutoextInit;
   92071   if( wsdAutoext.nExt==0 ){
   92072     /* Common case: early out without every having to acquire a mutex */
   92073     return;
   92074   }
   92075   for(i=0; go; i++){
   92076     char *zErrmsg;
   92077 #if SQLITE_THREADSAFE
   92078     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   92079 #endif
   92080     sqlite3_mutex_enter(mutex);
   92081     if( i>=wsdAutoext.nExt ){
   92082       xInit = 0;
   92083       go = 0;
   92084     }else{
   92085       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   92086               wsdAutoext.aExt[i];
   92087     }
   92088     sqlite3_mutex_leave(mutex);
   92089     zErrmsg = 0;
   92090     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
   92091       sqlite3Error(db, rc,
   92092             "automatic extension loading failed: %s", zErrmsg);
   92093       go = 0;
   92094     }
   92095     sqlite3_free(zErrmsg);
   92096   }
   92097 }
   92098 
   92099 /************** End of loadext.c *********************************************/
   92100 /************** Begin file pragma.c ******************************************/
   92101 /*
   92102 ** 2003 April 6
   92103 **
   92104 ** The author disclaims copyright to this source code.  In place of
   92105 ** a legal notice, here is a blessing:
   92106 **
   92107 **    May you do good and not evil.
   92108 **    May you find forgiveness for yourself and forgive others.
   92109 **    May you share freely, never taking more than you give.
   92110 **
   92111 *************************************************************************
   92112 ** This file contains code used to implement the PRAGMA command.
   92113 */
   92114 
   92115 /*
   92116 ** Interpret the given string as a safety level.  Return 0 for OFF,
   92117 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   92118 ** unrecognized string argument.  The FULL option is disallowed
   92119 ** if the omitFull parameter it 1.
   92120 **
   92121 ** Note that the values returned are one less that the values that
   92122 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   92123 ** to support legacy SQL code.  The safety level used to be boolean
   92124 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   92125 */
   92126 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
   92127                              /* 123456789 123456789 */
   92128   static const char zText[] = "onoffalseyestruefull";
   92129   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   92130   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   92131   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   92132   int i, n;
   92133   if( sqlite3Isdigit(*z) ){
   92134     return (u8)sqlite3Atoi(z);
   92135   }
   92136   n = sqlite3Strlen30(z);
   92137   for(i=0; i<ArraySize(iLength)-omitFull; i++){
   92138     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   92139       return iValue[i];
   92140     }
   92141   }
   92142   return dflt;
   92143 }
   92144 
   92145 /*
   92146 ** Interpret the given string as a boolean value.
   92147 */
   92148 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
   92149   return getSafetyLevel(z,1,dflt)!=0;
   92150 }
   92151 
   92152 /* The sqlite3GetBoolean() function is used by other modules but the
   92153 ** remainder of this file is specific to PRAGMA processing.  So omit
   92154 ** the rest of the file if PRAGMAs are omitted from the build.
   92155 */
   92156 #if !defined(SQLITE_OMIT_PRAGMA)
   92157 
   92158 /*
   92159 ** Interpret the given string as a locking mode value.
   92160 */
   92161 static int getLockingMode(const char *z){
   92162   if( z ){
   92163     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   92164     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   92165   }
   92166   return PAGER_LOCKINGMODE_QUERY;
   92167 }
   92168 
   92169 #ifndef SQLITE_OMIT_AUTOVACUUM
   92170 /*
   92171 ** Interpret the given string as an auto-vacuum mode value.
   92172 **
   92173 ** The following strings, "none", "full" and "incremental" are
   92174 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   92175 */
   92176 static int getAutoVacuum(const char *z){
   92177   int i;
   92178   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   92179   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   92180   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   92181   i = sqlite3Atoi(z);
   92182   return (u8)((i>=0&&i<=2)?i:0);
   92183 }
   92184 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   92185 
   92186 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92187 /*
   92188 ** Interpret the given string as a temp db location. Return 1 for file
   92189 ** backed temporary databases, 2 for the Red-Black tree in memory database
   92190 ** and 0 to use the compile-time default.
   92191 */
   92192 static int getTempStore(const char *z){
   92193   if( z[0]>='0' && z[0]<='2' ){
   92194     return z[0] - '0';
   92195   }else if( sqlite3StrICmp(z, "file")==0 ){
   92196     return 1;
   92197   }else if( sqlite3StrICmp(z, "memory")==0 ){
   92198     return 2;
   92199   }else{
   92200     return 0;
   92201   }
   92202 }
   92203 #endif /* SQLITE_PAGER_PRAGMAS */
   92204 
   92205 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92206 /*
   92207 ** Invalidate temp storage, either when the temp storage is changed
   92208 ** from default, or when 'file' and the temp_store_directory has changed
   92209 */
   92210 static int invalidateTempStorage(Parse *pParse){
   92211   sqlite3 *db = pParse->db;
   92212   if( db->aDb[1].pBt!=0 ){
   92213     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   92214       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   92215         "from within a transaction");
   92216       return SQLITE_ERROR;
   92217     }
   92218     sqlite3BtreeClose(db->aDb[1].pBt);
   92219     db->aDb[1].pBt = 0;
   92220     sqlite3ResetInternalSchema(db, -1);
   92221   }
   92222   return SQLITE_OK;
   92223 }
   92224 #endif /* SQLITE_PAGER_PRAGMAS */
   92225 
   92226 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92227 /*
   92228 ** If the TEMP database is open, close it and mark the database schema
   92229 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   92230 ** or DEFAULT_TEMP_STORE pragmas.
   92231 */
   92232 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   92233   int ts = getTempStore(zStorageType);
   92234   sqlite3 *db = pParse->db;
   92235   if( db->temp_store==ts ) return SQLITE_OK;
   92236   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   92237     return SQLITE_ERROR;
   92238   }
   92239   db->temp_store = (u8)ts;
   92240   return SQLITE_OK;
   92241 }
   92242 #endif /* SQLITE_PAGER_PRAGMAS */
   92243 
   92244 /*
   92245 ** Generate code to return a single integer value.
   92246 */
   92247 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   92248   Vdbe *v = sqlite3GetVdbe(pParse);
   92249   int mem = ++pParse->nMem;
   92250   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   92251   if( pI64 ){
   92252     memcpy(pI64, &value, sizeof(value));
   92253   }
   92254   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   92255   sqlite3VdbeSetNumCols(v, 1);
   92256   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   92257   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   92258 }
   92259 
   92260 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   92261 /*
   92262 ** Check to see if zRight and zLeft refer to a pragma that queries
   92263 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
   92264 ** Also, implement the pragma.
   92265 */
   92266 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
   92267   static const struct sPragmaType {
   92268     const char *zName;  /* Name of the pragma */
   92269     int mask;           /* Mask for the db->flags value */
   92270   } aPragma[] = {
   92271     { "full_column_names",        SQLITE_FullColNames  },
   92272     { "short_column_names",       SQLITE_ShortColNames },
   92273     { "count_changes",            SQLITE_CountRows     },
   92274     { "empty_result_callbacks",   SQLITE_NullCallback  },
   92275     { "legacy_file_format",       SQLITE_LegacyFileFmt },
   92276     { "fullfsync",                SQLITE_FullFSync     },
   92277     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
   92278     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
   92279 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   92280     { "automatic_index",          SQLITE_AutoIndex     },
   92281 #endif
   92282 #ifdef SQLITE_DEBUG
   92283     { "sql_trace",                SQLITE_SqlTrace      },
   92284     { "vdbe_listing",             SQLITE_VdbeListing   },
   92285     { "vdbe_trace",               SQLITE_VdbeTrace     },
   92286 #endif
   92287 #ifndef SQLITE_OMIT_CHECK
   92288     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
   92289 #endif
   92290     /* The following is VERY experimental */
   92291     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
   92292 
   92293     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
   92294     ** flag if there are any active statements. */
   92295     { "read_uncommitted",         SQLITE_ReadUncommitted },
   92296     { "recursive_triggers",       SQLITE_RecTriggers },
   92297 
   92298     /* This flag may only be set if both foreign-key and trigger support
   92299     ** are present in the build.  */
   92300 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   92301     { "foreign_keys",             SQLITE_ForeignKeys },
   92302 #endif
   92303   };
   92304   int i;
   92305   const struct sPragmaType *p;
   92306   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
   92307     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
   92308       sqlite3 *db = pParse->db;
   92309       Vdbe *v;
   92310       v = sqlite3GetVdbe(pParse);
   92311       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
   92312       if( ALWAYS(v) ){
   92313         if( zRight==0 ){
   92314           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
   92315         }else{
   92316           int mask = p->mask;          /* Mask of bits to set or clear. */
   92317           if( db->autoCommit==0 ){
   92318             /* Foreign key support may not be enabled or disabled while not
   92319             ** in auto-commit mode.  */
   92320             mask &= ~(SQLITE_ForeignKeys);
   92321           }
   92322 
   92323           if( sqlite3GetBoolean(zRight, 0) ){
   92324             db->flags |= mask;
   92325           }else{
   92326             db->flags &= ~mask;
   92327           }
   92328 
   92329           /* Many of the flag-pragmas modify the code generated by the SQL
   92330           ** compiler (eg. count_changes). So add an opcode to expire all
   92331           ** compiled SQL statements after modifying a pragma value.
   92332           */
   92333           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   92334         }
   92335       }
   92336 
   92337       return 1;
   92338     }
   92339   }
   92340   return 0;
   92341 }
   92342 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   92343 
   92344 /*
   92345 ** Return a human-readable name for a constraint resolution action.
   92346 */
   92347 #ifndef SQLITE_OMIT_FOREIGN_KEY
   92348 static const char *actionName(u8 action){
   92349   const char *zName;
   92350   switch( action ){
   92351     case OE_SetNull:  zName = "SET NULL";        break;
   92352     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   92353     case OE_Cascade:  zName = "CASCADE";         break;
   92354     case OE_Restrict: zName = "RESTRICT";        break;
   92355     default:          zName = "NO ACTION";
   92356                       assert( action==OE_None ); break;
   92357   }
   92358   return zName;
   92359 }
   92360 #endif
   92361 
   92362 
   92363 /*
   92364 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   92365 ** defined in pager.h. This function returns the associated lowercase
   92366 ** journal-mode name.
   92367 */
   92368 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   92369   static char * const azModeName[] = {
   92370     "delete", "persist", "off", "truncate", "memory"
   92371 #ifndef SQLITE_OMIT_WAL
   92372      , "wal"
   92373 #endif
   92374   };
   92375   assert( PAGER_JOURNALMODE_DELETE==0 );
   92376   assert( PAGER_JOURNALMODE_PERSIST==1 );
   92377   assert( PAGER_JOURNALMODE_OFF==2 );
   92378   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   92379   assert( PAGER_JOURNALMODE_MEMORY==4 );
   92380   assert( PAGER_JOURNALMODE_WAL==5 );
   92381   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   92382 
   92383   if( eMode==ArraySize(azModeName) ) return 0;
   92384   return azModeName[eMode];
   92385 }
   92386 
   92387 /*
   92388 ** Process a pragma statement.
   92389 **
   92390 ** Pragmas are of this form:
   92391 **
   92392 **      PRAGMA [database.]id [= value]
   92393 **
   92394 ** The identifier might also be a string.  The value is a string, and
   92395 ** identifier, or a number.  If minusFlag is true, then the value is
   92396 ** a number that was preceded by a minus sign.
   92397 **
   92398 ** If the left side is "database.id" then pId1 is the database name
   92399 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   92400 ** id and pId2 is any empty string.
   92401 */
   92402 SQLITE_PRIVATE void sqlite3Pragma(
   92403   Parse *pParse,
   92404   Token *pId1,        /* First part of [database.]id field */
   92405   Token *pId2,        /* Second part of [database.]id field, or NULL */
   92406   Token *pValue,      /* Token for <value>, or NULL */
   92407   int minusFlag       /* True if a '-' sign preceded <value> */
   92408 ){
   92409   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   92410   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   92411   const char *zDb = 0;   /* The database name */
   92412   Token *pId;            /* Pointer to <id> token */
   92413   int iDb;               /* Database index for <database> */
   92414   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
   92415   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
   92416   sqlite3 *db = pParse->db;    /* The database connection */
   92417   Db *pDb;                     /* The specific database being pragmaed */
   92418   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
   92419 
   92420   if( v==0 ) return;
   92421   sqlite3VdbeRunOnlyOnce(v);
   92422   pParse->nMem = 2;
   92423 
   92424   /* Interpret the [database.] part of the pragma statement. iDb is the
   92425   ** index of the database this pragma is being applied to in db.aDb[]. */
   92426   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   92427   if( iDb<0 ) return;
   92428   pDb = &db->aDb[iDb];
   92429 
   92430   /* If the temp database has been explicitly named as part of the
   92431   ** pragma, make sure it is open.
   92432   */
   92433   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   92434     return;
   92435   }
   92436 
   92437   zLeft = sqlite3NameFromToken(db, pId);
   92438   if( !zLeft ) return;
   92439   if( minusFlag ){
   92440     zRight = sqlite3MPrintf(db, "-%T", pValue);
   92441   }else{
   92442     zRight = sqlite3NameFromToken(db, pValue);
   92443   }
   92444 
   92445   assert( pId2 );
   92446   zDb = pId2->n>0 ? pDb->zName : 0;
   92447   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   92448     goto pragma_out;
   92449   }
   92450 
   92451   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   92452   ** connection.  If it returns SQLITE_OK, then assume that the VFS
   92453   ** handled the pragma and generate a no-op prepared statement.
   92454   */
   92455   aFcntl[0] = 0;
   92456   aFcntl[1] = zLeft;
   92457   aFcntl[2] = zRight;
   92458   aFcntl[3] = 0;
   92459   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
   92460   if( rc==SQLITE_OK ){
   92461     if( aFcntl[0] ){
   92462       int mem = ++pParse->nMem;
   92463       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
   92464       sqlite3VdbeSetNumCols(v, 1);
   92465       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
   92466       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   92467       sqlite3_free(aFcntl[0]);
   92468     }
   92469   }else if( rc!=SQLITE_NOTFOUND ){
   92470     if( aFcntl[0] ){
   92471       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
   92472       sqlite3_free(aFcntl[0]);
   92473     }
   92474     pParse->nErr++;
   92475     pParse->rc = rc;
   92476   }else
   92477 
   92478 
   92479 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   92480   /*
   92481   **  PRAGMA [database.]default_cache_size
   92482   **  PRAGMA [database.]default_cache_size=N
   92483   **
   92484   ** The first form reports the current persistent setting for the
   92485   ** page cache size.  The value returned is the maximum number of
   92486   ** pages in the page cache.  The second form sets both the current
   92487   ** page cache size value and the persistent page cache size value
   92488   ** stored in the database file.
   92489   **
   92490   ** Older versions of SQLite would set the default cache size to a
   92491   ** negative number to indicate synchronous=OFF.  These days, synchronous
   92492   ** is always on by default regardless of the sign of the default cache
   92493   ** size.  But continue to take the absolute value of the default cache
   92494   ** size of historical compatibility.
   92495   */
   92496   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
   92497     static const VdbeOpList getCacheSize[] = {
   92498       { OP_Transaction, 0, 0,        0},                         /* 0 */
   92499       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   92500       { OP_IfPos,       1, 7,        0},
   92501       { OP_Integer,     0, 2,        0},
   92502       { OP_Subtract,    1, 2,        1},
   92503       { OP_IfPos,       1, 7,        0},
   92504       { OP_Integer,     0, 1,        0},                         /* 6 */
   92505       { OP_ResultRow,   1, 1,        0},
   92506     };
   92507     int addr;
   92508     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92509     sqlite3VdbeUsesBtree(v, iDb);
   92510     if( !zRight ){
   92511       sqlite3VdbeSetNumCols(v, 1);
   92512       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   92513       pParse->nMem += 2;
   92514       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
   92515       sqlite3VdbeChangeP1(v, addr, iDb);
   92516       sqlite3VdbeChangeP1(v, addr+1, iDb);
   92517       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   92518     }else{
   92519       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   92520       sqlite3BeginWriteOperation(pParse, 0, iDb);
   92521       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   92522       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   92523       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   92524       pDb->pSchema->cache_size = size;
   92525       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   92526     }
   92527   }else
   92528 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   92529 
   92530 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   92531   /*
   92532   **  PRAGMA [database.]page_size
   92533   **  PRAGMA [database.]page_size=N
   92534   **
   92535   ** The first form reports the current setting for the
   92536   ** database page size in bytes.  The second form sets the
   92537   ** database page size value.  The value can only be set if
   92538   ** the database has not yet been created.
   92539   */
   92540   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
   92541     Btree *pBt = pDb->pBt;
   92542     assert( pBt!=0 );
   92543     if( !zRight ){
   92544       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   92545       returnSingleInt(pParse, "page_size", size);
   92546     }else{
   92547       /* Malloc may fail when setting the page-size, as there is an internal
   92548       ** buffer that the pager module resizes using sqlite3_realloc().
   92549       */
   92550       db->nextPagesize = sqlite3Atoi(zRight);
   92551       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   92552         db->mallocFailed = 1;
   92553       }
   92554     }
   92555   }else
   92556 
   92557   /*
   92558   **  PRAGMA [database.]secure_delete
   92559   **  PRAGMA [database.]secure_delete=ON/OFF
   92560   **
   92561   ** The first form reports the current setting for the
   92562   ** secure_delete flag.  The second form changes the secure_delete
   92563   ** flag setting and reports thenew value.
   92564   */
   92565   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
   92566     Btree *pBt = pDb->pBt;
   92567     int b = -1;
   92568     assert( pBt!=0 );
   92569     if( zRight ){
   92570       b = sqlite3GetBoolean(zRight, 0);
   92571     }
   92572     if( pId2->n==0 && b>=0 ){
   92573       int ii;
   92574       for(ii=0; ii<db->nDb; ii++){
   92575         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   92576       }
   92577     }
   92578     b = sqlite3BtreeSecureDelete(pBt, b);
   92579     returnSingleInt(pParse, "secure_delete", b);
   92580   }else
   92581 
   92582   /*
   92583   **  PRAGMA [database.]max_page_count
   92584   **  PRAGMA [database.]max_page_count=N
   92585   **
   92586   ** The first form reports the current setting for the
   92587   ** maximum number of pages in the database file.  The
   92588   ** second form attempts to change this setting.  Both
   92589   ** forms return the current setting.
   92590   **
   92591   ** The absolute value of N is used.  This is undocumented and might
   92592   ** change.  The only purpose is to provide an easy way to test
   92593   ** the sqlite3AbsInt32() function.
   92594   **
   92595   **  PRAGMA [database.]page_count
   92596   **
   92597   ** Return the number of pages in the specified database.
   92598   */
   92599   if( sqlite3StrICmp(zLeft,"page_count")==0
   92600    || sqlite3StrICmp(zLeft,"max_page_count")==0
   92601   ){
   92602     int iReg;
   92603     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92604     sqlite3CodeVerifySchema(pParse, iDb);
   92605     iReg = ++pParse->nMem;
   92606     if( sqlite3Tolower(zLeft[0])=='p' ){
   92607       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   92608     }else{
   92609       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
   92610                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
   92611     }
   92612     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   92613     sqlite3VdbeSetNumCols(v, 1);
   92614     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   92615   }else
   92616 
   92617   /*
   92618   **  PRAGMA [database.]locking_mode
   92619   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   92620   */
   92621   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
   92622     const char *zRet = "normal";
   92623     int eMode = getLockingMode(zRight);
   92624 
   92625     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   92626       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   92627       ** the current default locking mode (which may be different to
   92628       ** the locking-mode of the main database).
   92629       */
   92630       eMode = db->dfltLockMode;
   92631     }else{
   92632       Pager *pPager;
   92633       if( pId2->n==0 ){
   92634         /* This indicates that no database name was specified as part
   92635         ** of the PRAGMA command. In this case the locking-mode must be
   92636         ** set on all attached databases, as well as the main db file.
   92637         **
   92638         ** Also, the sqlite3.dfltLockMode variable is set so that
   92639         ** any subsequently attached databases also use the specified
   92640         ** locking mode.
   92641         */
   92642         int ii;
   92643         assert(pDb==&db->aDb[0]);
   92644         for(ii=2; ii<db->nDb; ii++){
   92645           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   92646           sqlite3PagerLockingMode(pPager, eMode);
   92647         }
   92648         db->dfltLockMode = (u8)eMode;
   92649       }
   92650       pPager = sqlite3BtreePager(pDb->pBt);
   92651       eMode = sqlite3PagerLockingMode(pPager, eMode);
   92652     }
   92653 
   92654     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
   92655     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   92656       zRet = "exclusive";
   92657     }
   92658     sqlite3VdbeSetNumCols(v, 1);
   92659     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   92660     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   92661     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92662   }else
   92663 
   92664   /*
   92665   **  PRAGMA [database.]journal_mode
   92666   **  PRAGMA [database.]journal_mode =
   92667   **                      (delete|persist|off|truncate|memory|wal|off)
   92668   */
   92669   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
   92670     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   92671     int ii;           /* Loop counter */
   92672 
   92673     /* Force the schema to be loaded on all databases.  This causes all
   92674     ** database files to be opened and the journal_modes set.  This is
   92675     ** necessary because subsequent processing must know if the databases
   92676     ** are in WAL mode. */
   92677     if( sqlite3ReadSchema(pParse) ){
   92678       goto pragma_out;
   92679     }
   92680 
   92681     sqlite3VdbeSetNumCols(v, 1);
   92682     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   92683 
   92684     if( zRight==0 ){
   92685       /* If there is no "=MODE" part of the pragma, do a query for the
   92686       ** current mode */
   92687       eMode = PAGER_JOURNALMODE_QUERY;
   92688     }else{
   92689       const char *zMode;
   92690       int n = sqlite3Strlen30(zRight);
   92691       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   92692         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   92693       }
   92694       if( !zMode ){
   92695         /* If the "=MODE" part does not match any known journal mode,
   92696         ** then do a query */
   92697         eMode = PAGER_JOURNALMODE_QUERY;
   92698       }
   92699     }
   92700     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   92701       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   92702       iDb = 0;
   92703       pId2->n = 1;
   92704     }
   92705     for(ii=db->nDb-1; ii>=0; ii--){
   92706       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   92707         sqlite3VdbeUsesBtree(v, ii);
   92708         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   92709       }
   92710     }
   92711     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92712   }else
   92713 
   92714   /*
   92715   **  PRAGMA [database.]journal_size_limit
   92716   **  PRAGMA [database.]journal_size_limit=N
   92717   **
   92718   ** Get or set the size limit on rollback journal files.
   92719   */
   92720   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
   92721     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92722     i64 iLimit = -2;
   92723     if( zRight ){
   92724       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
   92725       if( iLimit<-1 ) iLimit = -1;
   92726     }
   92727     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   92728     returnSingleInt(pParse, "journal_size_limit", iLimit);
   92729   }else
   92730 
   92731 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   92732 
   92733   /*
   92734   **  PRAGMA [database.]auto_vacuum
   92735   **  PRAGMA [database.]auto_vacuum=N
   92736   **
   92737   ** Get or set the value of the database 'auto-vacuum' parameter.
   92738   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   92739   */
   92740 #ifndef SQLITE_OMIT_AUTOVACUUM
   92741   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
   92742     Btree *pBt = pDb->pBt;
   92743     assert( pBt!=0 );
   92744     if( sqlite3ReadSchema(pParse) ){
   92745       goto pragma_out;
   92746     }
   92747     if( !zRight ){
   92748       int auto_vacuum;
   92749       if( ALWAYS(pBt) ){
   92750          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
   92751       }else{
   92752          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
   92753       }
   92754       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
   92755     }else{
   92756       int eAuto = getAutoVacuum(zRight);
   92757       assert( eAuto>=0 && eAuto<=2 );
   92758       db->nextAutovac = (u8)eAuto;
   92759       if( ALWAYS(eAuto>=0) ){
   92760         /* Call SetAutoVacuum() to set initialize the internal auto and
   92761         ** incr-vacuum flags. This is required in case this connection
   92762         ** creates the database file. It is important that it is created
   92763         ** as an auto-vacuum capable db.
   92764         */
   92765         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   92766         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   92767           /* When setting the auto_vacuum mode to either "full" or
   92768           ** "incremental", write the value of meta[6] in the database
   92769           ** file. Before writing to meta[6], check that meta[3] indicates
   92770           ** that this really is an auto-vacuum capable database.
   92771           */
   92772           static const VdbeOpList setMeta6[] = {
   92773             { OP_Transaction,    0,         1,                 0},    /* 0 */
   92774             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   92775             { OP_If,             1,         0,                 0},    /* 2 */
   92776             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   92777             { OP_Integer,        0,         1,                 0},    /* 4 */
   92778             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   92779           };
   92780           int iAddr;
   92781           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
   92782           sqlite3VdbeChangeP1(v, iAddr, iDb);
   92783           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   92784           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   92785           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   92786           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   92787           sqlite3VdbeUsesBtree(v, iDb);
   92788         }
   92789       }
   92790     }
   92791   }else
   92792 #endif
   92793 
   92794   /*
   92795   **  PRAGMA [database.]incremental_vacuum(N)
   92796   **
   92797   ** Do N steps of incremental vacuuming on a database.
   92798   */
   92799 #ifndef SQLITE_OMIT_AUTOVACUUM
   92800   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
   92801     int iLimit, addr;
   92802     if( sqlite3ReadSchema(pParse) ){
   92803       goto pragma_out;
   92804     }
   92805     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   92806       iLimit = 0x7fffffff;
   92807     }
   92808     sqlite3BeginWriteOperation(pParse, 0, iDb);
   92809     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   92810     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
   92811     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   92812     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   92813     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
   92814     sqlite3VdbeJumpHere(v, addr);
   92815   }else
   92816 #endif
   92817 
   92818 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92819   /*
   92820   **  PRAGMA [database.]cache_size
   92821   **  PRAGMA [database.]cache_size=N
   92822   **
   92823   ** The first form reports the current local setting for the
   92824   ** page cache size. The second form sets the local
   92825   ** page cache size value.  If N is positive then that is the
   92826   ** number of pages in the cache.  If N is negative, then the
   92827   ** number of pages is adjusted so that the cache uses -N kibibytes
   92828   ** of memory.
   92829   */
   92830   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
   92831     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92832     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   92833     if( !zRight ){
   92834       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   92835     }else{
   92836       int size = sqlite3Atoi(zRight);
   92837       pDb->pSchema->cache_size = size;
   92838       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   92839     }
   92840   }else
   92841 
   92842   /*
   92843   **   PRAGMA temp_store
   92844   **   PRAGMA temp_store = "default"|"memory"|"file"
   92845   **
   92846   ** Return or set the local value of the temp_store flag.  Changing
   92847   ** the local value does not make changes to the disk file and the default
   92848   ** value will be restored the next time the database is opened.
   92849   **
   92850   ** Note that it is possible for the library compile-time options to
   92851   ** override this setting
   92852   */
   92853   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
   92854     if( !zRight ){
   92855       returnSingleInt(pParse, "temp_store", db->temp_store);
   92856     }else{
   92857       changeTempStorage(pParse, zRight);
   92858     }
   92859   }else
   92860 
   92861   /*
   92862   **   PRAGMA temp_store_directory
   92863   **   PRAGMA temp_store_directory = ""|"directory_name"
   92864   **
   92865   ** Return or set the local value of the temp_store_directory flag.  Changing
   92866   ** the value sets a specific directory to be used for temporary files.
   92867   ** Setting to a null string reverts to the default temporary directory search.
   92868   ** If temporary directory is changed, then invalidateTempStorage.
   92869   **
   92870   */
   92871   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
   92872     if( !zRight ){
   92873       if( sqlite3_temp_directory ){
   92874         sqlite3VdbeSetNumCols(v, 1);
   92875         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   92876             "temp_store_directory", SQLITE_STATIC);
   92877         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   92878         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92879       }
   92880     }else{
   92881 #ifndef SQLITE_OMIT_WSD
   92882       if( zRight[0] ){
   92883         int res;
   92884         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   92885         if( rc!=SQLITE_OK || res==0 ){
   92886           sqlite3ErrorMsg(pParse, "not a writable directory");
   92887           goto pragma_out;
   92888         }
   92889       }
   92890       if( SQLITE_TEMP_STORE==0
   92891        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   92892        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   92893       ){
   92894         invalidateTempStorage(pParse);
   92895       }
   92896       sqlite3_free(sqlite3_temp_directory);
   92897       if( zRight[0] ){
   92898         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   92899       }else{
   92900         sqlite3_temp_directory = 0;
   92901       }
   92902 #endif /* SQLITE_OMIT_WSD */
   92903     }
   92904   }else
   92905 
   92906 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   92907 #  if defined(__APPLE__)
   92908 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   92909 #  else
   92910 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   92911 #  endif
   92912 #endif
   92913 #if SQLITE_ENABLE_LOCKING_STYLE
   92914   /*
   92915    **   PRAGMA [database.]lock_proxy_file
   92916    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   92917    **
   92918    ** Return or set the value of the lock_proxy_file flag.  Changing
   92919    ** the value sets a specific file to be used for database access locks.
   92920    **
   92921    */
   92922   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
   92923     if( !zRight ){
   92924       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92925       char *proxy_file_path = NULL;
   92926       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   92927       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
   92928                            &proxy_file_path);
   92929 
   92930       if( proxy_file_path ){
   92931         sqlite3VdbeSetNumCols(v, 1);
   92932         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   92933                               "lock_proxy_file", SQLITE_STATIC);
   92934         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   92935         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92936       }
   92937     }else{
   92938       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92939       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   92940       int res;
   92941       if( zRight[0] ){
   92942         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   92943                                      zRight);
   92944       } else {
   92945         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   92946                                      NULL);
   92947       }
   92948       if( res!=SQLITE_OK ){
   92949         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   92950         goto pragma_out;
   92951       }
   92952     }
   92953   }else
   92954 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   92955 
   92956   /*
   92957   **   PRAGMA [database.]synchronous
   92958   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   92959   **
   92960   ** Return or set the local value of the synchronous flag.  Changing
   92961   ** the local value does not make changes to the disk file and the
   92962   ** default value will be restored the next time the database is
   92963   ** opened.
   92964   */
   92965   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
   92966     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92967     if( !zRight ){
   92968       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   92969     }else{
   92970       if( !db->autoCommit ){
   92971         sqlite3ErrorMsg(pParse,
   92972             "Safety level may not be changed inside a transaction");
   92973       }else{
   92974         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
   92975       }
   92976     }
   92977   }else
   92978 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   92979 
   92980 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   92981   if( flagPragma(pParse, zLeft, zRight) ){
   92982     /* The flagPragma() subroutine also generates any necessary code
   92983     ** there is nothing more to do here */
   92984   }else
   92985 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   92986 
   92987 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   92988   /*
   92989   **   PRAGMA table_info(<table>)
   92990   **
   92991   ** Return a single row for each column of the named table. The columns of
   92992   ** the returned data set are:
   92993   **
   92994   ** cid:        Column id (numbered from left to right, starting at 0)
   92995   ** name:       Column name
   92996   ** type:       Column declaration type.
   92997   ** notnull:    True if 'NOT NULL' is part of column declaration
   92998   ** dflt_value: The default value for the column, if any.
   92999   */
   93000   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
   93001     Table *pTab;
   93002     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93003     pTab = sqlite3FindTable(db, zRight, zDb);
   93004     if( pTab ){
   93005       int i;
   93006       int nHidden = 0;
   93007       Column *pCol;
   93008       sqlite3VdbeSetNumCols(v, 6);
   93009       pParse->nMem = 6;
   93010       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   93011       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93012       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   93013       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   93014       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   93015       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   93016       sqlite3ViewGetColumnNames(pParse, pTab);
   93017       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   93018         if( IsHiddenColumn(pCol) ){
   93019           nHidden++;
   93020           continue;
   93021         }
   93022         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   93023         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   93024         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93025            pCol->zType ? pCol->zType : "", 0);
   93026         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   93027         if( pCol->zDflt ){
   93028           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   93029         }else{
   93030           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   93031         }
   93032         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
   93033         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   93034       }
   93035     }
   93036   }else
   93037 
   93038   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
   93039     Index *pIdx;
   93040     Table *pTab;
   93041     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93042     pIdx = sqlite3FindIndex(db, zRight, zDb);
   93043     if( pIdx ){
   93044       int i;
   93045       pTab = pIdx->pTable;
   93046       sqlite3VdbeSetNumCols(v, 3);
   93047       pParse->nMem = 3;
   93048       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   93049       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   93050       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   93051       for(i=0; i<pIdx->nColumn; i++){
   93052         int cnum = pIdx->aiColumn[i];
   93053         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93054         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   93055         assert( pTab->nCol>cnum );
   93056         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   93057         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93058       }
   93059     }
   93060   }else
   93061 
   93062   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
   93063     Index *pIdx;
   93064     Table *pTab;
   93065     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93066     pTab = sqlite3FindTable(db, zRight, zDb);
   93067     if( pTab ){
   93068       v = sqlite3GetVdbe(pParse);
   93069       pIdx = pTab->pIndex;
   93070       if( pIdx ){
   93071         int i = 0;
   93072         sqlite3VdbeSetNumCols(v, 3);
   93073         pParse->nMem = 3;
   93074         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93075         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93076         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   93077         while(pIdx){
   93078           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93079           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   93080           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
   93081           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93082           ++i;
   93083           pIdx = pIdx->pNext;
   93084         }
   93085       }
   93086     }
   93087   }else
   93088 
   93089   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
   93090     int i;
   93091     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93092     sqlite3VdbeSetNumCols(v, 3);
   93093     pParse->nMem = 3;
   93094     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93095     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93096     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   93097     for(i=0; i<db->nDb; i++){
   93098       if( db->aDb[i].pBt==0 ) continue;
   93099       assert( db->aDb[i].zName!=0 );
   93100       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93101       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   93102       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93103            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   93104       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93105     }
   93106   }else
   93107 
   93108   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
   93109     int i = 0;
   93110     HashElem *p;
   93111     sqlite3VdbeSetNumCols(v, 2);
   93112     pParse->nMem = 2;
   93113     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93114     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93115     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   93116       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   93117       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   93118       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   93119       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   93120     }
   93121   }else
   93122 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   93123 
   93124 #ifndef SQLITE_OMIT_FOREIGN_KEY
   93125   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
   93126     FKey *pFK;
   93127     Table *pTab;
   93128     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93129     pTab = sqlite3FindTable(db, zRight, zDb);
   93130     if( pTab ){
   93131       v = sqlite3GetVdbe(pParse);
   93132       pFK = pTab->pFKey;
   93133       if( pFK ){
   93134         int i = 0;
   93135         sqlite3VdbeSetNumCols(v, 8);
   93136         pParse->nMem = 8;
   93137         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   93138         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   93139         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   93140         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   93141         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   93142         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   93143         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   93144         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   93145         while(pFK){
   93146           int j;
   93147           for(j=0; j<pFK->nCol; j++){
   93148             char *zCol = pFK->aCol[j].zCol;
   93149             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   93150             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   93151             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93152             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   93153             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   93154             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   93155                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   93156             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   93157             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   93158             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   93159             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   93160             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   93161           }
   93162           ++i;
   93163           pFK = pFK->pNextFrom;
   93164         }
   93165       }
   93166     }
   93167   }else
   93168 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   93169 
   93170 #ifndef NDEBUG
   93171   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
   93172     if( zRight ){
   93173       if( sqlite3GetBoolean(zRight, 0) ){
   93174         sqlite3ParserTrace(stderr, "parser: ");
   93175       }else{
   93176         sqlite3ParserTrace(0, 0);
   93177       }
   93178     }
   93179   }else
   93180 #endif
   93181 
   93182   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   93183   ** used will be case sensitive or not depending on the RHS.
   93184   */
   93185   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
   93186     if( zRight ){
   93187       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
   93188     }
   93189   }else
   93190 
   93191 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   93192 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   93193 #endif
   93194 
   93195 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   93196   /* Pragma "quick_check" is an experimental reduced version of
   93197   ** integrity_check designed to detect most database corruption
   93198   ** without most of the overhead of a full integrity-check.
   93199   */
   93200   if( sqlite3StrICmp(zLeft, "integrity_check")==0
   93201    || sqlite3StrICmp(zLeft, "quick_check")==0
   93202   ){
   93203     int i, j, addr, mxErr;
   93204 
   93205     /* Code that appears at the end of the integrity check.  If no error
   93206     ** messages have been generated, output OK.  Otherwise output the
   93207     ** error message
   93208     */
   93209     static const VdbeOpList endCode[] = {
   93210       { OP_AddImm,      1, 0,        0},    /* 0 */
   93211       { OP_IfNeg,       1, 0,        0},    /* 1 */
   93212       { OP_String8,     0, 3,        0},    /* 2 */
   93213       { OP_ResultRow,   3, 1,        0},
   93214     };
   93215 
   93216     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
   93217 
   93218     /* Initialize the VDBE program */
   93219     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93220     pParse->nMem = 6;
   93221     sqlite3VdbeSetNumCols(v, 1);
   93222     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   93223 
   93224     /* Set the maximum error count */
   93225     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   93226     if( zRight ){
   93227       sqlite3GetInt32(zRight, &mxErr);
   93228       if( mxErr<=0 ){
   93229         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   93230       }
   93231     }
   93232     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   93233 
   93234     /* Do an integrity check on each database file */
   93235     for(i=0; i<db->nDb; i++){
   93236       HashElem *x;
   93237       Hash *pTbls;
   93238       int cnt = 0;
   93239 
   93240       if( OMIT_TEMPDB && i==1 ) continue;
   93241 
   93242       sqlite3CodeVerifySchema(pParse, i);
   93243       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   93244       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93245       sqlite3VdbeJumpHere(v, addr);
   93246 
   93247       /* Do an integrity check of the B-Tree
   93248       **
   93249       ** Begin by filling registers 2, 3, ... with the root pages numbers
   93250       ** for all tables and indices in the database.
   93251       */
   93252       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   93253       pTbls = &db->aDb[i].pSchema->tblHash;
   93254       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   93255         Table *pTab = sqliteHashData(x);
   93256         Index *pIdx;
   93257         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   93258         cnt++;
   93259         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   93260           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   93261           cnt++;
   93262         }
   93263       }
   93264 
   93265       /* Make sure sufficient number of registers have been allocated */
   93266       if( pParse->nMem < cnt+4 ){
   93267         pParse->nMem = cnt+4;
   93268       }
   93269 
   93270       /* Do the b-tree integrity checks */
   93271       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   93272       sqlite3VdbeChangeP5(v, (u8)i);
   93273       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
   93274       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93275          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   93276          P4_DYNAMIC);
   93277       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   93278       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   93279       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   93280       sqlite3VdbeJumpHere(v, addr);
   93281 
   93282       /* Make sure all the indices are constructed correctly.
   93283       */
   93284       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   93285         Table *pTab = sqliteHashData(x);
   93286         Index *pIdx;
   93287         int loopTop;
   93288 
   93289         if( pTab->pIndex==0 ) continue;
   93290         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   93291         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93292         sqlite3VdbeJumpHere(v, addr);
   93293         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
   93294         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
   93295         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
   93296         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
   93297         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   93298           int jmp2;
   93299           int r1;
   93300           static const VdbeOpList idxErr[] = {
   93301             { OP_AddImm,      1, -1,  0},
   93302             { OP_String8,     0,  3,  0},    /* 1 */
   93303             { OP_Rowid,       1,  4,  0},
   93304             { OP_String8,     0,  5,  0},    /* 3 */
   93305             { OP_String8,     0,  6,  0},    /* 4 */
   93306             { OP_Concat,      4,  3,  3},
   93307             { OP_Concat,      5,  3,  3},
   93308             { OP_Concat,      6,  3,  3},
   93309             { OP_ResultRow,   3,  1,  0},
   93310             { OP_IfPos,       1,  0,  0},    /* 9 */
   93311             { OP_Halt,        0,  0,  0},
   93312           };
   93313           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
   93314           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
   93315           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
   93316           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
   93317           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
   93318           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
   93319           sqlite3VdbeJumpHere(v, addr+9);
   93320           sqlite3VdbeJumpHere(v, jmp2);
   93321         }
   93322         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
   93323         sqlite3VdbeJumpHere(v, loopTop);
   93324         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   93325           static const VdbeOpList cntIdx[] = {
   93326              { OP_Integer,      0,  3,  0},
   93327              { OP_Rewind,       0,  0,  0},  /* 1 */
   93328              { OP_AddImm,       3,  1,  0},
   93329              { OP_Next,         0,  0,  0},  /* 3 */
   93330              { OP_Eq,           2,  0,  3},  /* 4 */
   93331              { OP_AddImm,       1, -1,  0},
   93332              { OP_String8,      0,  2,  0},  /* 6 */
   93333              { OP_String8,      0,  3,  0},  /* 7 */
   93334              { OP_Concat,       3,  2,  2},
   93335              { OP_ResultRow,    2,  1,  0},
   93336           };
   93337           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
   93338           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93339           sqlite3VdbeJumpHere(v, addr);
   93340           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
   93341           sqlite3VdbeChangeP1(v, addr+1, j+2);
   93342           sqlite3VdbeChangeP2(v, addr+1, addr+4);
   93343           sqlite3VdbeChangeP1(v, addr+3, j+2);
   93344           sqlite3VdbeChangeP2(v, addr+3, addr+2);
   93345           sqlite3VdbeJumpHere(v, addr+4);
   93346           sqlite3VdbeChangeP4(v, addr+6,
   93347                      "wrong # of entries in index ", P4_STATIC);
   93348           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
   93349         }
   93350       }
   93351     }
   93352     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
   93353     sqlite3VdbeChangeP2(v, addr, -mxErr);
   93354     sqlite3VdbeJumpHere(v, addr+1);
   93355     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
   93356   }else
   93357 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   93358 
   93359 #ifndef SQLITE_OMIT_UTF16
   93360   /*
   93361   **   PRAGMA encoding
   93362   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   93363   **
   93364   ** In its first form, this pragma returns the encoding of the main
   93365   ** database. If the database is not initialized, it is initialized now.
   93366   **
   93367   ** The second form of this pragma is a no-op if the main database file
   93368   ** has not already been initialized. In this case it sets the default
   93369   ** encoding that will be used for the main database file if a new file
   93370   ** is created. If an existing main database file is opened, then the
   93371   ** default text encoding for the existing database is used.
   93372   **
   93373   ** In all cases new databases created using the ATTACH command are
   93374   ** created to use the same default text encoding as the main database. If
   93375   ** the main database has not been initialized and/or created when ATTACH
   93376   ** is executed, this is done before the ATTACH operation.
   93377   **
   93378   ** In the second form this pragma sets the text encoding to be used in
   93379   ** new database files created using this database handle. It is only
   93380   ** useful if invoked immediately after the main database i
   93381   */
   93382   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
   93383     static const struct EncName {
   93384       char *zName;
   93385       u8 enc;
   93386     } encnames[] = {
   93387       { "UTF8",     SQLITE_UTF8        },
   93388       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   93389       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   93390       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   93391       { "UTF16le",  SQLITE_UTF16LE     },
   93392       { "UTF16be",  SQLITE_UTF16BE     },
   93393       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   93394       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   93395       { 0, 0 }
   93396     };
   93397     const struct EncName *pEnc;
   93398     if( !zRight ){    /* "PRAGMA encoding" */
   93399       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93400       sqlite3VdbeSetNumCols(v, 1);
   93401       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   93402       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   93403       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   93404       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   93405       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   93406       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   93407       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   93408     }else{                        /* "PRAGMA encoding = XXX" */
   93409       /* Only change the value of sqlite.enc if the database handle is not
   93410       ** initialized. If the main database exists, the new sqlite.enc value
   93411       ** will be overwritten when the schema is next loaded. If it does not
   93412       ** already exists, it will be created to use the new encoding value.
   93413       */
   93414       if(
   93415         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   93416         DbHasProperty(db, 0, DB_Empty)
   93417       ){
   93418         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   93419           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   93420             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   93421             break;
   93422           }
   93423         }
   93424         if( !pEnc->zName ){
   93425           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   93426         }
   93427       }
   93428     }
   93429   }else
   93430 #endif /* SQLITE_OMIT_UTF16 */
   93431 
   93432 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   93433   /*
   93434   **   PRAGMA [database.]schema_version
   93435   **   PRAGMA [database.]schema_version = <integer>
   93436   **
   93437   **   PRAGMA [database.]user_version
   93438   **   PRAGMA [database.]user_version = <integer>
   93439   **
   93440   ** The pragma's schema_version and user_version are used to set or get
   93441   ** the value of the schema-version and user-version, respectively. Both
   93442   ** the schema-version and the user-version are 32-bit signed integers
   93443   ** stored in the database header.
   93444   **
   93445   ** The schema-cookie is usually only manipulated internally by SQLite. It
   93446   ** is incremented by SQLite whenever the database schema is modified (by
   93447   ** creating or dropping a table or index). The schema version is used by
   93448   ** SQLite each time a query is executed to ensure that the internal cache
   93449   ** of the schema used when compiling the SQL query matches the schema of
   93450   ** the database against which the compiled query is actually executed.
   93451   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   93452   ** the schema-version is potentially dangerous and may lead to program
   93453   ** crashes or database corruption. Use with caution!
   93454   **
   93455   ** The user-version is not used internally by SQLite. It may be used by
   93456   ** applications for any purpose.
   93457   */
   93458   if( sqlite3StrICmp(zLeft, "schema_version")==0
   93459    || sqlite3StrICmp(zLeft, "user_version")==0
   93460    || sqlite3StrICmp(zLeft, "freelist_count")==0
   93461   ){
   93462     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   93463     sqlite3VdbeUsesBtree(v, iDb);
   93464     switch( zLeft[0] ){
   93465       case 'f': case 'F':
   93466         iCookie = BTREE_FREE_PAGE_COUNT;
   93467         break;
   93468       case 's': case 'S':
   93469         iCookie = BTREE_SCHEMA_VERSION;
   93470         break;
   93471       default:
   93472         iCookie = BTREE_USER_VERSION;
   93473         break;
   93474     }
   93475 
   93476     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   93477       /* Write the specified cookie value */
   93478       static const VdbeOpList setCookie[] = {
   93479         { OP_Transaction,    0,  1,  0},    /* 0 */
   93480         { OP_Integer,        0,  1,  0},    /* 1 */
   93481         { OP_SetCookie,      0,  0,  1},    /* 2 */
   93482       };
   93483       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
   93484       sqlite3VdbeChangeP1(v, addr, iDb);
   93485       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
   93486       sqlite3VdbeChangeP1(v, addr+2, iDb);
   93487       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   93488     }else{
   93489       /* Read the specified cookie value */
   93490       static const VdbeOpList readCookie[] = {
   93491         { OP_Transaction,     0,  0,  0},    /* 0 */
   93492         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   93493         { OP_ResultRow,       1,  1,  0}
   93494       };
   93495       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
   93496       sqlite3VdbeChangeP1(v, addr, iDb);
   93497       sqlite3VdbeChangeP1(v, addr+1, iDb);
   93498       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   93499       sqlite3VdbeSetNumCols(v, 1);
   93500       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   93501     }
   93502   }else
   93503 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   93504 
   93505 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   93506   /*
   93507   **   PRAGMA compile_options
   93508   **
   93509   ** Return the names of all compile-time options used in this build,
   93510   ** one option per row.
   93511   */
   93512   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
   93513     int i = 0;
   93514     const char *zOpt;
   93515     sqlite3VdbeSetNumCols(v, 1);
   93516     pParse->nMem = 1;
   93517     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
   93518     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   93519       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
   93520       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   93521     }
   93522   }else
   93523 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   93524 
   93525 #ifndef SQLITE_OMIT_WAL
   93526   /*
   93527   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
   93528   **
   93529   ** Checkpoint the database.
   93530   */
   93531   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
   93532     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
   93533     int eMode = SQLITE_CHECKPOINT_PASSIVE;
   93534     if( zRight ){
   93535       if( sqlite3StrICmp(zRight, "full")==0 ){
   93536         eMode = SQLITE_CHECKPOINT_FULL;
   93537       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
   93538         eMode = SQLITE_CHECKPOINT_RESTART;
   93539       }
   93540     }
   93541     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93542     sqlite3VdbeSetNumCols(v, 3);
   93543     pParse->nMem = 3;
   93544     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
   93545     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
   93546     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
   93547 
   93548     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
   93549     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93550   }else
   93551 
   93552   /*
   93553   **   PRAGMA wal_autocheckpoint
   93554   **   PRAGMA wal_autocheckpoint = N
   93555   **
   93556   ** Configure a database connection to automatically checkpoint a database
   93557   ** after accumulating N frames in the log. Or query for the current value
   93558   ** of N.
   93559   */
   93560   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
   93561     if( zRight ){
   93562       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   93563     }
   93564     returnSingleInt(pParse, "wal_autocheckpoint",
   93565        db->xWalCallback==sqlite3WalDefaultHook ?
   93566            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   93567   }else
   93568 #endif
   93569 
   93570   /*
   93571   **  PRAGMA shrink_memory
   93572   **
   93573   ** This pragma attempts to free as much memory as possible from the
   93574   ** current database connection.
   93575   */
   93576   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
   93577     sqlite3_db_release_memory(db);
   93578   }else
   93579 
   93580 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   93581   /*
   93582   ** Report the current state of file logs for all databases
   93583   */
   93584   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
   93585     static const char *const azLockName[] = {
   93586       "unlocked", "shared", "reserved", "pending", "exclusive"
   93587     };
   93588     int i;
   93589     sqlite3VdbeSetNumCols(v, 2);
   93590     pParse->nMem = 2;
   93591     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   93592     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   93593     for(i=0; i<db->nDb; i++){
   93594       Btree *pBt;
   93595       Pager *pPager;
   93596       const char *zState = "unknown";
   93597       int j;
   93598       if( db->aDb[i].zName==0 ) continue;
   93599       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   93600       pBt = db->aDb[i].pBt;
   93601       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
   93602         zState = "closed";
   93603       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   93604                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   93605          zState = azLockName[j];
   93606       }
   93607       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   93608       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   93609     }
   93610 
   93611   }else
   93612 #endif
   93613 
   93614 #ifdef SQLITE_HAS_CODEC
   93615   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
   93616     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
   93617   }else
   93618   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
   93619     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
   93620   }else
   93621   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
   93622                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
   93623     int i, h1, h2;
   93624     char zKey[40];
   93625     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
   93626       h1 += 9*(1&(h1>>6));
   93627       h2 += 9*(1&(h2>>6));
   93628       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
   93629     }
   93630     if( (zLeft[3] & 0xf)==0xb ){
   93631       sqlite3_key(db, zKey, i/2);
   93632     }else{
   93633       sqlite3_rekey(db, zKey, i/2);
   93634     }
   93635   }else
   93636 #endif
   93637 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   93638   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
   93639 #ifdef SQLITE_HAS_CODEC
   93640     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   93641       sqlite3_activate_see(&zRight[4]);
   93642     }
   93643 #endif
   93644 #ifdef SQLITE_ENABLE_CEROD
   93645     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   93646       sqlite3_activate_cerod(&zRight[6]);
   93647     }
   93648 #endif
   93649   }else
   93650 #endif
   93651 
   93652 
   93653   {/* Empty ELSE clause */}
   93654 
   93655   /*
   93656   ** Reset the safety level, in case the fullfsync flag or synchronous
   93657   ** setting changed.
   93658   */
   93659 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   93660   if( db->autoCommit ){
   93661     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
   93662                (db->flags&SQLITE_FullFSync)!=0,
   93663                (db->flags&SQLITE_CkptFullFSync)!=0);
   93664   }
   93665 #endif
   93666 pragma_out:
   93667   sqlite3DbFree(db, zLeft);
   93668   sqlite3DbFree(db, zRight);
   93669 }
   93670 
   93671 #endif /* SQLITE_OMIT_PRAGMA */
   93672 
   93673 /************** End of pragma.c **********************************************/
   93674 /************** Begin file prepare.c *****************************************/
   93675 /*
   93676 ** 2005 May 25
   93677 **
   93678 ** The author disclaims copyright to this source code.  In place of
   93679 ** a legal notice, here is a blessing:
   93680 **
   93681 **    May you do good and not evil.
   93682 **    May you find forgiveness for yourself and forgive others.
   93683 **    May you share freely, never taking more than you give.
   93684 **
   93685 *************************************************************************
   93686 ** This file contains the implementation of the sqlite3_prepare()
   93687 ** interface, and routines that contribute to loading the database schema
   93688 ** from disk.
   93689 */
   93690 
   93691 /*
   93692 ** Fill the InitData structure with an error message that indicates
   93693 ** that the database is corrupt.
   93694 */
   93695 static void corruptSchema(
   93696   InitData *pData,     /* Initialization context */
   93697   const char *zObj,    /* Object being parsed at the point of error */
   93698   const char *zExtra   /* Error information */
   93699 ){
   93700   sqlite3 *db = pData->db;
   93701   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   93702     if( zObj==0 ) zObj = "?";
   93703     sqlite3SetString(pData->pzErrMsg, db,
   93704       "malformed database schema (%s)", zObj);
   93705     if( zExtra ){
   93706       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   93707                                  "%s - %s", *pData->pzErrMsg, zExtra);
   93708     }
   93709   }
   93710   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
   93711 }
   93712 
   93713 /*
   93714 ** This is the callback routine for the code that initializes the
   93715 ** database.  See sqlite3Init() below for additional information.
   93716 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   93717 **
   93718 ** Each callback contains the following information:
   93719 **
   93720 **     argv[0] = name of thing being created
   93721 **     argv[1] = root page number for table or index. 0 for trigger or view.
   93722 **     argv[2] = SQL text for the CREATE statement.
   93723 **
   93724 */
   93725 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   93726   InitData *pData = (InitData*)pInit;
   93727   sqlite3 *db = pData->db;
   93728   int iDb = pData->iDb;
   93729 
   93730   assert( argc==3 );
   93731   UNUSED_PARAMETER2(NotUsed, argc);
   93732   assert( sqlite3_mutex_held(db->mutex) );
   93733   DbClearProperty(db, iDb, DB_Empty);
   93734   if( db->mallocFailed ){
   93735     corruptSchema(pData, argv[0], 0);
   93736     return 1;
   93737   }
   93738 
   93739   assert( iDb>=0 && iDb<db->nDb );
   93740   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   93741   if( argv[1]==0 ){
   93742     corruptSchema(pData, argv[0], 0);
   93743   }else if( argv[2] && argv[2][0] ){
   93744     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   93745     ** But because db->init.busy is set to 1, no VDBE code is generated
   93746     ** or executed.  All the parser does is build the internal data
   93747     ** structures that describe the table, index, or view.
   93748     */
   93749     int rc;
   93750     sqlite3_stmt *pStmt;
   93751     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   93752 
   93753     assert( db->init.busy );
   93754     db->init.iDb = iDb;
   93755     db->init.newTnum = sqlite3Atoi(argv[1]);
   93756     db->init.orphanTrigger = 0;
   93757     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   93758     rc = db->errCode;
   93759     assert( (rc&0xFF)==(rcp&0xFF) );
   93760     db->init.iDb = 0;
   93761     if( SQLITE_OK!=rc ){
   93762       if( db->init.orphanTrigger ){
   93763         assert( iDb==1 );
   93764       }else{
   93765         pData->rc = rc;
   93766         if( rc==SQLITE_NOMEM ){
   93767           db->mallocFailed = 1;
   93768         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   93769           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   93770         }
   93771       }
   93772     }
   93773     sqlite3_finalize(pStmt);
   93774   }else if( argv[0]==0 ){
   93775     corruptSchema(pData, 0, 0);
   93776   }else{
   93777     /* If the SQL column is blank it means this is an index that
   93778     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   93779     ** constraint for a CREATE TABLE.  The index should have already
   93780     ** been created when we processed the CREATE TABLE.  All we have
   93781     ** to do here is record the root page number for that index.
   93782     */
   93783     Index *pIndex;
   93784     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   93785     if( pIndex==0 ){
   93786       /* This can occur if there exists an index on a TEMP table which
   93787       ** has the same name as another index on a permanent index.  Since
   93788       ** the permanent table is hidden by the TEMP table, we can also
   93789       ** safely ignore the index on the permanent table.
   93790       */
   93791       /* Do Nothing */;
   93792     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   93793       corruptSchema(pData, argv[0], "invalid rootpage");
   93794     }
   93795   }
   93796   return 0;
   93797 }
   93798 
   93799 /*
   93800 ** Attempt to read the database schema and initialize internal
   93801 ** data structures for a single database file.  The index of the
   93802 ** database file is given by iDb.  iDb==0 is used for the main
   93803 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   93804 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   93805 ** indicate success or failure.
   93806 */
   93807 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   93808   int rc;
   93809   int i;
   93810   int size;
   93811   Table *pTab;
   93812   Db *pDb;
   93813   char const *azArg[4];
   93814   int meta[5];
   93815   InitData initData;
   93816   char const *zMasterSchema;
   93817   char const *zMasterName;
   93818   int openedTransaction = 0;
   93819 
   93820   /*
   93821   ** The master database table has a structure like this
   93822   */
   93823   static const char master_schema[] =
   93824      "CREATE TABLE sqlite_master(\n"
   93825      "  type text,\n"
   93826      "  name text,\n"
   93827      "  tbl_name text,\n"
   93828      "  rootpage integer,\n"
   93829      "  sql text\n"
   93830      ")"
   93831   ;
   93832 #ifndef SQLITE_OMIT_TEMPDB
   93833   static const char temp_master_schema[] =
   93834      "CREATE TEMP TABLE sqlite_temp_master(\n"
   93835      "  type text,\n"
   93836      "  name text,\n"
   93837      "  tbl_name text,\n"
   93838      "  rootpage integer,\n"
   93839      "  sql text\n"
   93840      ")"
   93841   ;
   93842 #else
   93843   #define temp_master_schema 0
   93844 #endif
   93845 
   93846   assert( iDb>=0 && iDb<db->nDb );
   93847   assert( db->aDb[iDb].pSchema );
   93848   assert( sqlite3_mutex_held(db->mutex) );
   93849   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   93850 
   93851   /* zMasterSchema and zInitScript are set to point at the master schema
   93852   ** and initialisation script appropriate for the database being
   93853   ** initialised. zMasterName is the name of the master table.
   93854   */
   93855   if( !OMIT_TEMPDB && iDb==1 ){
   93856     zMasterSchema = temp_master_schema;
   93857   }else{
   93858     zMasterSchema = master_schema;
   93859   }
   93860   zMasterName = SCHEMA_TABLE(iDb);
   93861 
   93862   /* Construct the schema tables.  */
   93863   azArg[0] = zMasterName;
   93864   azArg[1] = "1";
   93865   azArg[2] = zMasterSchema;
   93866   azArg[3] = 0;
   93867   initData.db = db;
   93868   initData.iDb = iDb;
   93869   initData.rc = SQLITE_OK;
   93870   initData.pzErrMsg = pzErrMsg;
   93871   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   93872   if( initData.rc ){
   93873     rc = initData.rc;
   93874     goto error_out;
   93875   }
   93876   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   93877   if( ALWAYS(pTab) ){
   93878     pTab->tabFlags |= TF_Readonly;
   93879   }
   93880 
   93881   /* Create a cursor to hold the database open
   93882   */
   93883   pDb = &db->aDb[iDb];
   93884   if( pDb->pBt==0 ){
   93885     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   93886       DbSetProperty(db, 1, DB_SchemaLoaded);
   93887     }
   93888     return SQLITE_OK;
   93889   }
   93890 
   93891   /* If there is not already a read-only (or read-write) transaction opened
   93892   ** on the b-tree database, open one now. If a transaction is opened, it
   93893   ** will be closed before this function returns.  */
   93894   sqlite3BtreeEnter(pDb->pBt);
   93895   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   93896     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   93897     if( rc!=SQLITE_OK ){
   93898       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   93899       goto initone_error_out;
   93900     }
   93901     openedTransaction = 1;
   93902   }
   93903 
   93904   /* Get the database meta information.
   93905   **
   93906   ** Meta values are as follows:
   93907   **    meta[0]   Schema cookie.  Changes with each schema change.
   93908   **    meta[1]   File format of schema layer.
   93909   **    meta[2]   Size of the page cache.
   93910   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   93911   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   93912   **    meta[5]   User version
   93913   **    meta[6]   Incremental vacuum mode
   93914   **    meta[7]   unused
   93915   **    meta[8]   unused
   93916   **    meta[9]   unused
   93917   **
   93918   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   93919   ** the possible values of meta[4].
   93920   */
   93921   for(i=0; i<ArraySize(meta); i++){
   93922     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   93923   }
   93924   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   93925 
   93926   /* If opening a non-empty database, check the text encoding. For the
   93927   ** main database, set sqlite3.enc to the encoding of the main database.
   93928   ** For an attached db, it is an error if the encoding is not the same
   93929   ** as sqlite3.enc.
   93930   */
   93931   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   93932     if( iDb==0 ){
   93933       u8 encoding;
   93934       /* If opening the main database, set ENC(db). */
   93935       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   93936       if( encoding==0 ) encoding = SQLITE_UTF8;
   93937       ENC(db) = encoding;
   93938       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   93939     }else{
   93940       /* If opening an attached database, the encoding much match ENC(db) */
   93941       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   93942         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   93943             " text encoding as main database");
   93944         rc = SQLITE_ERROR;
   93945         goto initone_error_out;
   93946       }
   93947     }
   93948   }else{
   93949     DbSetProperty(db, iDb, DB_Empty);
   93950   }
   93951   pDb->pSchema->enc = ENC(db);
   93952 
   93953   if( pDb->pSchema->cache_size==0 ){
   93954 #ifndef SQLITE_OMIT_DEPRECATED
   93955     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   93956     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   93957     pDb->pSchema->cache_size = size;
   93958 #else
   93959     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
   93960 #endif
   93961     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   93962   }
   93963 
   93964   /*
   93965   ** file_format==1    Version 3.0.0.
   93966   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   93967   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   93968   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   93969   */
   93970   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   93971   if( pDb->pSchema->file_format==0 ){
   93972     pDb->pSchema->file_format = 1;
   93973   }
   93974   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   93975     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   93976     rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
   93977     goto initone_error_out;
   93978   }
   93979 
   93980   /* Ticket #2804:  When we open a database in the newer file format,
   93981   ** clear the legacy_file_format pragma flag so that a VACUUM will
   93982   ** not downgrade the database and thus invalidate any descending
   93983   ** indices that the user might have created.
   93984   */
   93985   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   93986     db->flags &= ~SQLITE_LegacyFileFmt;
   93987   }
   93988 
   93989   /* Read the schema information out of the schema tables
   93990   */
   93991   assert( db->init.busy );
   93992   {
   93993     char *zSql;
   93994     zSql = sqlite3MPrintf(db,
   93995         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
   93996         db->aDb[iDb].zName, zMasterName);
   93997 #ifndef SQLITE_OMIT_AUTHORIZATION
   93998     {
   93999       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   94000       xAuth = db->xAuth;
   94001       db->xAuth = 0;
   94002 #endif
   94003       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   94004 #ifndef SQLITE_OMIT_AUTHORIZATION
   94005       db->xAuth = xAuth;
   94006     }
   94007 #endif
   94008     if( rc==SQLITE_OK ) rc = initData.rc;
   94009     sqlite3DbFree(db, zSql);
   94010 #ifndef SQLITE_OMIT_ANALYZE
   94011     if( rc==SQLITE_OK ){
   94012       sqlite3AnalysisLoad(db, iDb);
   94013     }
   94014 #endif
   94015   }
   94016   if( db->mallocFailed ){
   94017     rc = SQLITE_NOMEM;
   94018     sqlite3ResetInternalSchema(db, -1);
   94019   }
   94020   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   94021     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   94022     ** the schema loaded, even if errors occurred. In this situation the
   94023     ** current sqlite3_prepare() operation will fail, but the following one
   94024     ** will attempt to compile the supplied statement against whatever subset
   94025     ** of the schema was loaded before the error occurred. The primary
   94026     ** purpose of this is to allow access to the sqlite_master table
   94027     ** even when its contents have been corrupted.
   94028     */
   94029     DbSetProperty(db, iDb, DB_SchemaLoaded);
   94030     rc = SQLITE_OK;
   94031   }
   94032 
   94033   /* Jump here for an error that occurs after successfully allocating
   94034   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   94035   ** before that point, jump to error_out.
   94036   */
   94037 initone_error_out:
   94038   if( openedTransaction ){
   94039     sqlite3BtreeCommit(pDb->pBt);
   94040   }
   94041   sqlite3BtreeLeave(pDb->pBt);
   94042 
   94043 error_out:
   94044   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   94045     db->mallocFailed = 1;
   94046   }
   94047   return rc;
   94048 }
   94049 
   94050 /*
   94051 ** Initialize all database files - the main database file, the file
   94052 ** used to store temporary tables, and any additional database files
   94053 ** created using ATTACH statements.  Return a success code.  If an
   94054 ** error occurs, write an error message into *pzErrMsg.
   94055 **
   94056 ** After a database is initialized, the DB_SchemaLoaded bit is set
   94057 ** bit is set in the flags field of the Db structure. If the database
   94058 ** file was of zero-length, then the DB_Empty flag is also set.
   94059 */
   94060 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   94061   int i, rc;
   94062   int commit_internal = !(db->flags&SQLITE_InternChanges);
   94063 
   94064   assert( sqlite3_mutex_held(db->mutex) );
   94065   rc = SQLITE_OK;
   94066   db->init.busy = 1;
   94067   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   94068     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   94069     rc = sqlite3InitOne(db, i, pzErrMsg);
   94070     if( rc ){
   94071       sqlite3ResetInternalSchema(db, i);
   94072     }
   94073   }
   94074 
   94075   /* Once all the other databases have been initialised, load the schema
   94076   ** for the TEMP database. This is loaded last, as the TEMP database
   94077   ** schema may contain references to objects in other databases.
   94078   */
   94079 #ifndef SQLITE_OMIT_TEMPDB
   94080   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   94081                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   94082     rc = sqlite3InitOne(db, 1, pzErrMsg);
   94083     if( rc ){
   94084       sqlite3ResetInternalSchema(db, 1);
   94085     }
   94086   }
   94087 #endif
   94088 
   94089   db->init.busy = 0;
   94090   if( rc==SQLITE_OK && commit_internal ){
   94091     sqlite3CommitInternalChanges(db);
   94092   }
   94093 
   94094   return rc;
   94095 }
   94096 
   94097 /*
   94098 ** This routine is a no-op if the database schema is already initialised.
   94099 ** Otherwise, the schema is loaded. An error code is returned.
   94100 */
   94101 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   94102   int rc = SQLITE_OK;
   94103   sqlite3 *db = pParse->db;
   94104   assert( sqlite3_mutex_held(db->mutex) );
   94105   if( !db->init.busy ){
   94106     rc = sqlite3Init(db, &pParse->zErrMsg);
   94107   }
   94108   if( rc!=SQLITE_OK ){
   94109     pParse->rc = rc;
   94110     pParse->nErr++;
   94111   }
   94112   return rc;
   94113 }
   94114 
   94115 
   94116 /*
   94117 ** Check schema cookies in all databases.  If any cookie is out
   94118 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   94119 ** make no changes to pParse->rc.
   94120 */
   94121 static void schemaIsValid(Parse *pParse){
   94122   sqlite3 *db = pParse->db;
   94123   int iDb;
   94124   int rc;
   94125   int cookie;
   94126 
   94127   assert( pParse->checkSchema );
   94128   assert( sqlite3_mutex_held(db->mutex) );
   94129   for(iDb=0; iDb<db->nDb; iDb++){
   94130     int openedTransaction = 0;         /* True if a transaction is opened */
   94131     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   94132     if( pBt==0 ) continue;
   94133 
   94134     /* If there is not already a read-only (or read-write) transaction opened
   94135     ** on the b-tree database, open one now. If a transaction is opened, it
   94136     ** will be closed immediately after reading the meta-value. */
   94137     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   94138       rc = sqlite3BtreeBeginTrans(pBt, 0);
   94139       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   94140         db->mallocFailed = 1;
   94141       }
   94142       if( rc!=SQLITE_OK ) return;
   94143       openedTransaction = 1;
   94144     }
   94145 
   94146     /* Read the schema cookie from the database. If it does not match the
   94147     ** value stored as part of the in-memory schema representation,
   94148     ** set Parse.rc to SQLITE_SCHEMA. */
   94149     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   94150     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   94151     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   94152       sqlite3ResetInternalSchema(db, iDb);
   94153       pParse->rc = SQLITE_SCHEMA;
   94154     }
   94155 
   94156     /* Close the transaction, if one was opened. */
   94157     if( openedTransaction ){
   94158       sqlite3BtreeCommit(pBt);
   94159     }
   94160   }
   94161 }
   94162 
   94163 /*
   94164 ** Convert a schema pointer into the iDb index that indicates
   94165 ** which database file in db->aDb[] the schema refers to.
   94166 **
   94167 ** If the same database is attached more than once, the first
   94168 ** attached database is returned.
   94169 */
   94170 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   94171   int i = -1000000;
   94172 
   94173   /* If pSchema is NULL, then return -1000000. This happens when code in
   94174   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   94175   ** created by a sub-select). In this case the return value of this
   94176   ** function should never be used.
   94177   **
   94178   ** We return -1000000 instead of the more usual -1 simply because using
   94179   ** -1000000 as the incorrect index into db->aDb[] is much
   94180   ** more likely to cause a segfault than -1 (of course there are assert()
   94181   ** statements too, but it never hurts to play the odds).
   94182   */
   94183   assert( sqlite3_mutex_held(db->mutex) );
   94184   if( pSchema ){
   94185     for(i=0; ALWAYS(i<db->nDb); i++){
   94186       if( db->aDb[i].pSchema==pSchema ){
   94187         break;
   94188       }
   94189     }
   94190     assert( i>=0 && i<db->nDb );
   94191   }
   94192   return i;
   94193 }
   94194 
   94195 /*
   94196 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   94197 */
   94198 static int sqlite3Prepare(
   94199   sqlite3 *db,              /* Database handle. */
   94200   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94201   int nBytes,               /* Length of zSql in bytes. */
   94202   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   94203   Vdbe *pReprepare,         /* VM being reprepared */
   94204   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94205   const char **pzTail       /* OUT: End of parsed string */
   94206 ){
   94207   Parse *pParse;            /* Parsing context */
   94208   char *zErrMsg = 0;        /* Error message */
   94209   int rc = SQLITE_OK;       /* Result code */
   94210   int i;                    /* Loop counter */
   94211 
   94212   /* Allocate the parsing context */
   94213   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   94214   if( pParse==0 ){
   94215     rc = SQLITE_NOMEM;
   94216     goto end_prepare;
   94217   }
   94218   pParse->pReprepare = pReprepare;
   94219   assert( ppStmt && *ppStmt==0 );
   94220   assert( !db->mallocFailed );
   94221   assert( sqlite3_mutex_held(db->mutex) );
   94222 
   94223   /* Check to verify that it is possible to get a read lock on all
   94224   ** database schemas.  The inability to get a read lock indicates that
   94225   ** some other database connection is holding a write-lock, which in
   94226   ** turn means that the other connection has made uncommitted changes
   94227   ** to the schema.
   94228   **
   94229   ** Were we to proceed and prepare the statement against the uncommitted
   94230   ** schema changes and if those schema changes are subsequently rolled
   94231   ** back and different changes are made in their place, then when this
   94232   ** prepared statement goes to run the schema cookie would fail to detect
   94233   ** the schema change.  Disaster would follow.
   94234   **
   94235   ** This thread is currently holding mutexes on all Btrees (because
   94236   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   94237   ** is not possible for another thread to start a new schema change
   94238   ** while this routine is running.  Hence, we do not need to hold
   94239   ** locks on the schema, we just need to make sure nobody else is
   94240   ** holding them.
   94241   **
   94242   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   94243   ** but it does *not* override schema lock detection, so this all still
   94244   ** works even if READ_UNCOMMITTED is set.
   94245   */
   94246   for(i=0; i<db->nDb; i++) {
   94247     Btree *pBt = db->aDb[i].pBt;
   94248     if( pBt ){
   94249       assert( sqlite3BtreeHoldsMutex(pBt) );
   94250       rc = sqlite3BtreeSchemaLocked(pBt);
   94251       if( rc ){
   94252         const char *zDb = db->aDb[i].zName;
   94253         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   94254         testcase( db->flags & SQLITE_ReadUncommitted );
   94255         goto end_prepare;
   94256       }
   94257     }
   94258   }
   94259 
   94260   sqlite3VtabUnlockList(db);
   94261 
   94262   pParse->db = db;
   94263   pParse->nQueryLoop = (double)1;
   94264   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   94265     char *zSqlCopy;
   94266     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   94267     testcase( nBytes==mxLen );
   94268     testcase( nBytes==mxLen+1 );
   94269     if( nBytes>mxLen ){
   94270       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   94271       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   94272       goto end_prepare;
   94273     }
   94274     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   94275     if( zSqlCopy ){
   94276       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   94277       sqlite3DbFree(db, zSqlCopy);
   94278       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   94279     }else{
   94280       pParse->zTail = &zSql[nBytes];
   94281     }
   94282   }else{
   94283     sqlite3RunParser(pParse, zSql, &zErrMsg);
   94284   }
   94285   assert( 1==(int)pParse->nQueryLoop );
   94286 
   94287   if( db->mallocFailed ){
   94288     pParse->rc = SQLITE_NOMEM;
   94289   }
   94290   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   94291   if( pParse->checkSchema ){
   94292     schemaIsValid(pParse);
   94293   }
   94294   if( db->mallocFailed ){
   94295     pParse->rc = SQLITE_NOMEM;
   94296   }
   94297   if( pzTail ){
   94298     *pzTail = pParse->zTail;
   94299   }
   94300   rc = pParse->rc;
   94301 
   94302 #ifndef SQLITE_OMIT_EXPLAIN
   94303   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   94304     static const char * const azColName[] = {
   94305        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   94306        "selectid", "order", "from", "detail"
   94307     };
   94308     int iFirst, mx;
   94309     if( pParse->explain==2 ){
   94310       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
   94311       iFirst = 8;
   94312       mx = 12;
   94313     }else{
   94314       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   94315       iFirst = 0;
   94316       mx = 8;
   94317     }
   94318     for(i=iFirst; i<mx; i++){
   94319       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   94320                             azColName[i], SQLITE_STATIC);
   94321     }
   94322   }
   94323 #endif
   94324 
   94325   assert( db->init.busy==0 || saveSqlFlag==0 );
   94326   if( db->init.busy==0 ){
   94327     Vdbe *pVdbe = pParse->pVdbe;
   94328     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   94329   }
   94330   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   94331     sqlite3VdbeFinalize(pParse->pVdbe);
   94332     assert(!(*ppStmt));
   94333   }else{
   94334     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   94335   }
   94336 
   94337   if( zErrMsg ){
   94338     sqlite3Error(db, rc, "%s", zErrMsg);
   94339     sqlite3DbFree(db, zErrMsg);
   94340   }else{
   94341     sqlite3Error(db, rc, 0);
   94342   }
   94343 
   94344   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   94345   while( pParse->pTriggerPrg ){
   94346     TriggerPrg *pT = pParse->pTriggerPrg;
   94347     pParse->pTriggerPrg = pT->pNext;
   94348     sqlite3DbFree(db, pT);
   94349   }
   94350 
   94351 end_prepare:
   94352 
   94353   sqlite3StackFree(db, pParse);
   94354   rc = sqlite3ApiExit(db, rc);
   94355   assert( (rc&db->errMask)==rc );
   94356   return rc;
   94357 }
   94358 static int sqlite3LockAndPrepare(
   94359   sqlite3 *db,              /* Database handle. */
   94360   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94361   int nBytes,               /* Length of zSql in bytes. */
   94362   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   94363   Vdbe *pOld,               /* VM being reprepared */
   94364   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94365   const char **pzTail       /* OUT: End of parsed string */
   94366 ){
   94367   int rc;
   94368   assert( ppStmt!=0 );
   94369   *ppStmt = 0;
   94370   if( !sqlite3SafetyCheckOk(db) ){
   94371     return SQLITE_MISUSE_BKPT;
   94372   }
   94373   sqlite3_mutex_enter(db->mutex);
   94374   sqlite3BtreeEnterAll(db);
   94375   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   94376   if( rc==SQLITE_SCHEMA ){
   94377     sqlite3_finalize(*ppStmt);
   94378     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   94379   }
   94380   sqlite3BtreeLeaveAll(db);
   94381   sqlite3_mutex_leave(db->mutex);
   94382   return rc;
   94383 }
   94384 
   94385 /*
   94386 ** Rerun the compilation of a statement after a schema change.
   94387 **
   94388 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   94389 ** if the statement cannot be recompiled because another connection has
   94390 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   94391 ** occurs, return SQLITE_SCHEMA.
   94392 */
   94393 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   94394   int rc;
   94395   sqlite3_stmt *pNew;
   94396   const char *zSql;
   94397   sqlite3 *db;
   94398 
   94399   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   94400   zSql = sqlite3_sql((sqlite3_stmt *)p);
   94401   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   94402   db = sqlite3VdbeDb(p);
   94403   assert( sqlite3_mutex_held(db->mutex) );
   94404   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   94405   if( rc ){
   94406     if( rc==SQLITE_NOMEM ){
   94407       db->mallocFailed = 1;
   94408     }
   94409     assert( pNew==0 );
   94410     return rc;
   94411   }else{
   94412     assert( pNew!=0 );
   94413   }
   94414   sqlite3VdbeSwap((Vdbe*)pNew, p);
   94415   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   94416   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   94417   sqlite3VdbeFinalize((Vdbe*)pNew);
   94418   return SQLITE_OK;
   94419 }
   94420 
   94421 
   94422 /*
   94423 ** Two versions of the official API.  Legacy and new use.  In the legacy
   94424 ** version, the original SQL text is not saved in the prepared statement
   94425 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   94426 ** sqlite3_step().  In the new version, the original SQL text is retained
   94427 ** and the statement is automatically recompiled if an schema change
   94428 ** occurs.
   94429 */
   94430 SQLITE_API int sqlite3_prepare(
   94431   sqlite3 *db,              /* Database handle. */
   94432   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94433   int nBytes,               /* Length of zSql in bytes. */
   94434   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94435   const char **pzTail       /* OUT: End of parsed string */
   94436 ){
   94437   int rc;
   94438   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   94439   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94440   return rc;
   94441 }
   94442 SQLITE_API int sqlite3_prepare_v2(
   94443   sqlite3 *db,              /* Database handle. */
   94444   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94445   int nBytes,               /* Length of zSql in bytes. */
   94446   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94447   const char **pzTail       /* OUT: End of parsed string */
   94448 ){
   94449   int rc;
   94450   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   94451   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94452   return rc;
   94453 }
   94454 
   94455 
   94456 #ifndef SQLITE_OMIT_UTF16
   94457 /*
   94458 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   94459 */
   94460 static int sqlite3Prepare16(
   94461   sqlite3 *db,              /* Database handle. */
   94462   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94463   int nBytes,               /* Length of zSql in bytes. */
   94464   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   94465   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94466   const void **pzTail       /* OUT: End of parsed string */
   94467 ){
   94468   /* This function currently works by first transforming the UTF-16
   94469   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   94470   ** tricky bit is figuring out the pointer to return in *pzTail.
   94471   */
   94472   char *zSql8;
   94473   const char *zTail8 = 0;
   94474   int rc = SQLITE_OK;
   94475 
   94476   assert( ppStmt );
   94477   *ppStmt = 0;
   94478   if( !sqlite3SafetyCheckOk(db) ){
   94479     return SQLITE_MISUSE_BKPT;
   94480   }
   94481   sqlite3_mutex_enter(db->mutex);
   94482   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   94483   if( zSql8 ){
   94484     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   94485   }
   94486 
   94487   if( zTail8 && pzTail ){
   94488     /* If sqlite3_prepare returns a tail pointer, we calculate the
   94489     ** equivalent pointer into the UTF-16 string by counting the unicode
   94490     ** characters between zSql8 and zTail8, and then returning a pointer
   94491     ** the same number of characters into the UTF-16 string.
   94492     */
   94493     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   94494     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   94495   }
   94496   sqlite3DbFree(db, zSql8);
   94497   rc = sqlite3ApiExit(db, rc);
   94498   sqlite3_mutex_leave(db->mutex);
   94499   return rc;
   94500 }
   94501 
   94502 /*
   94503 ** Two versions of the official API.  Legacy and new use.  In the legacy
   94504 ** version, the original SQL text is not saved in the prepared statement
   94505 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   94506 ** sqlite3_step().  In the new version, the original SQL text is retained
   94507 ** and the statement is automatically recompiled if an schema change
   94508 ** occurs.
   94509 */
   94510 SQLITE_API int sqlite3_prepare16(
   94511   sqlite3 *db,              /* Database handle. */
   94512   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94513   int nBytes,               /* Length of zSql in bytes. */
   94514   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94515   const void **pzTail       /* OUT: End of parsed string */
   94516 ){
   94517   int rc;
   94518   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   94519   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94520   return rc;
   94521 }
   94522 SQLITE_API int sqlite3_prepare16_v2(
   94523   sqlite3 *db,              /* Database handle. */
   94524   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94525   int nBytes,               /* Length of zSql in bytes. */
   94526   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94527   const void **pzTail       /* OUT: End of parsed string */
   94528 ){
   94529   int rc;
   94530   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   94531   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94532   return rc;
   94533 }
   94534 
   94535 #endif /* SQLITE_OMIT_UTF16 */
   94536 
   94537 /************** End of prepare.c *********************************************/
   94538 /************** Begin file select.c ******************************************/
   94539 /*
   94540 ** 2001 September 15
   94541 **
   94542 ** The author disclaims copyright to this source code.  In place of
   94543 ** a legal notice, here is a blessing:
   94544 **
   94545 **    May you do good and not evil.
   94546 **    May you find forgiveness for yourself and forgive others.
   94547 **    May you share freely, never taking more than you give.
   94548 **
   94549 *************************************************************************
   94550 ** This file contains C code routines that are called by the parser
   94551 ** to handle SELECT statements in SQLite.
   94552 */
   94553 
   94554 
   94555 /*
   94556 ** Delete all the content of a Select structure but do not deallocate
   94557 ** the select structure itself.
   94558 */
   94559 static void clearSelect(sqlite3 *db, Select *p){
   94560   sqlite3ExprListDelete(db, p->pEList);
   94561   sqlite3SrcListDelete(db, p->pSrc);
   94562   sqlite3ExprDelete(db, p->pWhere);
   94563   sqlite3ExprListDelete(db, p->pGroupBy);
   94564   sqlite3ExprDelete(db, p->pHaving);
   94565   sqlite3ExprListDelete(db, p->pOrderBy);
   94566   sqlite3SelectDelete(db, p->pPrior);
   94567   sqlite3ExprDelete(db, p->pLimit);
   94568   sqlite3ExprDelete(db, p->pOffset);
   94569 }
   94570 
   94571 /*
   94572 ** Initialize a SelectDest structure.
   94573 */
   94574 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   94575   pDest->eDest = (u8)eDest;
   94576   pDest->iParm = iParm;
   94577   pDest->affinity = 0;
   94578   pDest->iMem = 0;
   94579   pDest->nMem = 0;
   94580 }
   94581 
   94582 
   94583 /*
   94584 ** Allocate a new Select structure and return a pointer to that
   94585 ** structure.
   94586 */
   94587 SQLITE_PRIVATE Select *sqlite3SelectNew(
   94588   Parse *pParse,        /* Parsing context */
   94589   ExprList *pEList,     /* which columns to include in the result */
   94590   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   94591   Expr *pWhere,         /* the WHERE clause */
   94592   ExprList *pGroupBy,   /* the GROUP BY clause */
   94593   Expr *pHaving,        /* the HAVING clause */
   94594   ExprList *pOrderBy,   /* the ORDER BY clause */
   94595   int isDistinct,       /* true if the DISTINCT keyword is present */
   94596   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   94597   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   94598 ){
   94599   Select *pNew;
   94600   Select standin;
   94601   sqlite3 *db = pParse->db;
   94602   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   94603   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   94604   if( pNew==0 ){
   94605     assert( db->mallocFailed );
   94606     pNew = &standin;
   94607     memset(pNew, 0, sizeof(*pNew));
   94608   }
   94609   if( pEList==0 ){
   94610     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   94611   }
   94612   pNew->pEList = pEList;
   94613   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
   94614   pNew->pSrc = pSrc;
   94615   pNew->pWhere = pWhere;
   94616   pNew->pGroupBy = pGroupBy;
   94617   pNew->pHaving = pHaving;
   94618   pNew->pOrderBy = pOrderBy;
   94619   pNew->selFlags = isDistinct ? SF_Distinct : 0;
   94620   pNew->op = TK_SELECT;
   94621   pNew->pLimit = pLimit;
   94622   pNew->pOffset = pOffset;
   94623   assert( pOffset==0 || pLimit!=0 );
   94624   pNew->addrOpenEphm[0] = -1;
   94625   pNew->addrOpenEphm[1] = -1;
   94626   pNew->addrOpenEphm[2] = -1;
   94627   if( db->mallocFailed ) {
   94628     clearSelect(db, pNew);
   94629     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   94630     pNew = 0;
   94631   }else{
   94632     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   94633   }
   94634   assert( pNew!=&standin );
   94635   return pNew;
   94636 }
   94637 
   94638 /*
   94639 ** Delete the given Select structure and all of its substructures.
   94640 */
   94641 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   94642   if( p ){
   94643     clearSelect(db, p);
   94644     sqlite3DbFree(db, p);
   94645   }
   94646 }
   94647 
   94648 /*
   94649 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   94650 ** type of join.  Return an integer constant that expresses that type
   94651 ** in terms of the following bit values:
   94652 **
   94653 **     JT_INNER
   94654 **     JT_CROSS
   94655 **     JT_OUTER
   94656 **     JT_NATURAL
   94657 **     JT_LEFT
   94658 **     JT_RIGHT
   94659 **
   94660 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   94661 **
   94662 ** If an illegal or unsupported join type is seen, then still return
   94663 ** a join type, but put an error in the pParse structure.
   94664 */
   94665 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   94666   int jointype = 0;
   94667   Token *apAll[3];
   94668   Token *p;
   94669                              /*   0123456789 123456789 123456789 123 */
   94670   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   94671   static const struct {
   94672     u8 i;        /* Beginning of keyword text in zKeyText[] */
   94673     u8 nChar;    /* Length of the keyword in characters */
   94674     u8 code;     /* Join type mask */
   94675   } aKeyword[] = {
   94676     /* natural */ { 0,  7, JT_NATURAL                },
   94677     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   94678     /* outer   */ { 10, 5, JT_OUTER                  },
   94679     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   94680     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   94681     /* inner   */ { 23, 5, JT_INNER                  },
   94682     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   94683   };
   94684   int i, j;
   94685   apAll[0] = pA;
   94686   apAll[1] = pB;
   94687   apAll[2] = pC;
   94688   for(i=0; i<3 && apAll[i]; i++){
   94689     p = apAll[i];
   94690     for(j=0; j<ArraySize(aKeyword); j++){
   94691       if( p->n==aKeyword[j].nChar
   94692           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   94693         jointype |= aKeyword[j].code;
   94694         break;
   94695       }
   94696     }
   94697     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   94698     if( j>=ArraySize(aKeyword) ){
   94699       jointype |= JT_ERROR;
   94700       break;
   94701     }
   94702   }
   94703   if(
   94704      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   94705      (jointype & JT_ERROR)!=0
   94706   ){
   94707     const char *zSp = " ";
   94708     assert( pB!=0 );
   94709     if( pC==0 ){ zSp++; }
   94710     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   94711        "%T %T%s%T", pA, pB, zSp, pC);
   94712     jointype = JT_INNER;
   94713   }else if( (jointype & JT_OUTER)!=0
   94714          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   94715     sqlite3ErrorMsg(pParse,
   94716       "RIGHT and FULL OUTER JOINs are not currently supported");
   94717     jointype = JT_INNER;
   94718   }
   94719   return jointype;
   94720 }
   94721 
   94722 /*
   94723 ** Return the index of a column in a table.  Return -1 if the column
   94724 ** is not contained in the table.
   94725 */
   94726 static int columnIndex(Table *pTab, const char *zCol){
   94727   int i;
   94728   for(i=0; i<pTab->nCol; i++){
   94729     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   94730   }
   94731   return -1;
   94732 }
   94733 
   94734 /*
   94735 ** Search the first N tables in pSrc, from left to right, looking for a
   94736 ** table that has a column named zCol.
   94737 **
   94738 ** When found, set *piTab and *piCol to the table index and column index
   94739 ** of the matching column and return TRUE.
   94740 **
   94741 ** If not found, return FALSE.
   94742 */
   94743 static int tableAndColumnIndex(
   94744   SrcList *pSrc,       /* Array of tables to search */
   94745   int N,               /* Number of tables in pSrc->a[] to search */
   94746   const char *zCol,    /* Name of the column we are looking for */
   94747   int *piTab,          /* Write index of pSrc->a[] here */
   94748   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   94749 ){
   94750   int i;               /* For looping over tables in pSrc */
   94751   int iCol;            /* Index of column matching zCol */
   94752 
   94753   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   94754   for(i=0; i<N; i++){
   94755     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   94756     if( iCol>=0 ){
   94757       if( piTab ){
   94758         *piTab = i;
   94759         *piCol = iCol;
   94760       }
   94761       return 1;
   94762     }
   94763   }
   94764   return 0;
   94765 }
   94766 
   94767 /*
   94768 ** This function is used to add terms implied by JOIN syntax to the
   94769 ** WHERE clause expression of a SELECT statement. The new term, which
   94770 ** is ANDed with the existing WHERE clause, is of the form:
   94771 **
   94772 **    (tab1.col1 = tab2.col2)
   94773 **
   94774 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   94775 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   94776 ** column iColRight of tab2.
   94777 */
   94778 static void addWhereTerm(
   94779   Parse *pParse,                  /* Parsing context */
   94780   SrcList *pSrc,                  /* List of tables in FROM clause */
   94781   int iLeft,                      /* Index of first table to join in pSrc */
   94782   int iColLeft,                   /* Index of column in first table */
   94783   int iRight,                     /* Index of second table in pSrc */
   94784   int iColRight,                  /* Index of column in second table */
   94785   int isOuterJoin,                /* True if this is an OUTER join */
   94786   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   94787 ){
   94788   sqlite3 *db = pParse->db;
   94789   Expr *pE1;
   94790   Expr *pE2;
   94791   Expr *pEq;
   94792 
   94793   assert( iLeft<iRight );
   94794   assert( pSrc->nSrc>iRight );
   94795   assert( pSrc->a[iLeft].pTab );
   94796   assert( pSrc->a[iRight].pTab );
   94797 
   94798   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   94799   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   94800 
   94801   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   94802   if( pEq && isOuterJoin ){
   94803     ExprSetProperty(pEq, EP_FromJoin);
   94804     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
   94805     ExprSetIrreducible(pEq);
   94806     pEq->iRightJoinTable = (i16)pE2->iTable;
   94807   }
   94808   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   94809 }
   94810 
   94811 /*
   94812 ** Set the EP_FromJoin property on all terms of the given expression.
   94813 ** And set the Expr.iRightJoinTable to iTable for every term in the
   94814 ** expression.
   94815 **
   94816 ** The EP_FromJoin property is used on terms of an expression to tell
   94817 ** the LEFT OUTER JOIN processing logic that this term is part of the
   94818 ** join restriction specified in the ON or USING clause and not a part
   94819 ** of the more general WHERE clause.  These terms are moved over to the
   94820 ** WHERE clause during join processing but we need to remember that they
   94821 ** originated in the ON or USING clause.
   94822 **
   94823 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   94824 ** expression depends on table iRightJoinTable even if that table is not
   94825 ** explicitly mentioned in the expression.  That information is needed
   94826 ** for cases like this:
   94827 **
   94828 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   94829 **
   94830 ** The where clause needs to defer the handling of the t1.x=5
   94831 ** term until after the t2 loop of the join.  In that way, a
   94832 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   94833 ** defer the handling of t1.x=5, it will be processed immediately
   94834 ** after the t1 loop and rows with t1.x!=5 will never appear in
   94835 ** the output, which is incorrect.
   94836 */
   94837 static void setJoinExpr(Expr *p, int iTable){
   94838   while( p ){
   94839     ExprSetProperty(p, EP_FromJoin);
   94840     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   94841     ExprSetIrreducible(p);
   94842     p->iRightJoinTable = (i16)iTable;
   94843     setJoinExpr(p->pLeft, iTable);
   94844     p = p->pRight;
   94845   }
   94846 }
   94847 
   94848 /*
   94849 ** This routine processes the join information for a SELECT statement.
   94850 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   94851 ** NATURAL joins also create extra WHERE clause terms.
   94852 **
   94853 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   94854 ** The left most table is the first entry in Select.pSrc.  The right-most
   94855 ** table is the last entry.  The join operator is held in the entry to
   94856 ** the left.  Thus entry 0 contains the join operator for the join between
   94857 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   94858 ** also attached to the left entry.
   94859 **
   94860 ** This routine returns the number of errors encountered.
   94861 */
   94862 static int sqliteProcessJoin(Parse *pParse, Select *p){
   94863   SrcList *pSrc;                  /* All tables in the FROM clause */
   94864   int i, j;                       /* Loop counters */
   94865   struct SrcList_item *pLeft;     /* Left table being joined */
   94866   struct SrcList_item *pRight;    /* Right table being joined */
   94867 
   94868   pSrc = p->pSrc;
   94869   pLeft = &pSrc->a[0];
   94870   pRight = &pLeft[1];
   94871   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   94872     Table *pLeftTab = pLeft->pTab;
   94873     Table *pRightTab = pRight->pTab;
   94874     int isOuter;
   94875 
   94876     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   94877     isOuter = (pRight->jointype & JT_OUTER)!=0;
   94878 
   94879     /* When the NATURAL keyword is present, add WHERE clause terms for
   94880     ** every column that the two tables have in common.
   94881     */
   94882     if( pRight->jointype & JT_NATURAL ){
   94883       if( pRight->pOn || pRight->pUsing ){
   94884         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   94885            "an ON or USING clause", 0);
   94886         return 1;
   94887       }
   94888       for(j=0; j<pRightTab->nCol; j++){
   94889         char *zName;   /* Name of column in the right table */
   94890         int iLeft;     /* Matching left table */
   94891         int iLeftCol;  /* Matching column in the left table */
   94892 
   94893         zName = pRightTab->aCol[j].zName;
   94894         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   94895           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   94896                        isOuter, &p->pWhere);
   94897         }
   94898       }
   94899     }
   94900 
   94901     /* Disallow both ON and USING clauses in the same join
   94902     */
   94903     if( pRight->pOn && pRight->pUsing ){
   94904       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   94905         "clauses in the same join");
   94906       return 1;
   94907     }
   94908 
   94909     /* Add the ON clause to the end of the WHERE clause, connected by
   94910     ** an AND operator.
   94911     */
   94912     if( pRight->pOn ){
   94913       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   94914       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   94915       pRight->pOn = 0;
   94916     }
   94917 
   94918     /* Create extra terms on the WHERE clause for each column named
   94919     ** in the USING clause.  Example: If the two tables to be joined are
   94920     ** A and B and the USING clause names X, Y, and Z, then add this
   94921     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   94922     ** Report an error if any column mentioned in the USING clause is
   94923     ** not contained in both tables to be joined.
   94924     */
   94925     if( pRight->pUsing ){
   94926       IdList *pList = pRight->pUsing;
   94927       for(j=0; j<pList->nId; j++){
   94928         char *zName;     /* Name of the term in the USING clause */
   94929         int iLeft;       /* Table on the left with matching column name */
   94930         int iLeftCol;    /* Column number of matching column on the left */
   94931         int iRightCol;   /* Column number of matching column on the right */
   94932 
   94933         zName = pList->a[j].zName;
   94934         iRightCol = columnIndex(pRightTab, zName);
   94935         if( iRightCol<0
   94936          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   94937         ){
   94938           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   94939             "not present in both tables", zName);
   94940           return 1;
   94941         }
   94942         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   94943                      isOuter, &p->pWhere);
   94944       }
   94945     }
   94946   }
   94947   return 0;
   94948 }
   94949 
   94950 /*
   94951 ** Insert code into "v" that will push the record on the top of the
   94952 ** stack into the sorter.
   94953 */
   94954 static void pushOntoSorter(
   94955   Parse *pParse,         /* Parser context */
   94956   ExprList *pOrderBy,    /* The ORDER BY clause */
   94957   Select *pSelect,       /* The whole SELECT statement */
   94958   int regData            /* Register holding data to be sorted */
   94959 ){
   94960   Vdbe *v = pParse->pVdbe;
   94961   int nExpr = pOrderBy->nExpr;
   94962   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
   94963   int regRecord = sqlite3GetTempReg(pParse);
   94964   int op;
   94965   sqlite3ExprCacheClear(pParse);
   94966   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
   94967   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
   94968   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   94969   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
   94970   if( pSelect->selFlags & SF_UseSorter ){
   94971     op = OP_SorterInsert;
   94972   }else{
   94973     op = OP_IdxInsert;
   94974   }
   94975   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
   94976   sqlite3ReleaseTempReg(pParse, regRecord);
   94977   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
   94978   if( pSelect->iLimit ){
   94979     int addr1, addr2;
   94980     int iLimit;
   94981     if( pSelect->iOffset ){
   94982       iLimit = pSelect->iOffset+1;
   94983     }else{
   94984       iLimit = pSelect->iLimit;
   94985     }
   94986     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
   94987     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   94988     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   94989     sqlite3VdbeJumpHere(v, addr1);
   94990     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   94991     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   94992     sqlite3VdbeJumpHere(v, addr2);
   94993   }
   94994 }
   94995 
   94996 /*
   94997 ** Add code to implement the OFFSET
   94998 */
   94999 static void codeOffset(
   95000   Vdbe *v,          /* Generate code into this VM */
   95001   Select *p,        /* The SELECT statement being coded */
   95002   int iContinue     /* Jump here to skip the current record */
   95003 ){
   95004   if( p->iOffset && iContinue!=0 ){
   95005     int addr;
   95006     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
   95007     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
   95008     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   95009     VdbeComment((v, "skip OFFSET records"));
   95010     sqlite3VdbeJumpHere(v, addr);
   95011   }
   95012 }
   95013 
   95014 /*
   95015 ** Add code that will check to make sure the N registers starting at iMem
   95016 ** form a distinct entry.  iTab is a sorting index that holds previously
   95017 ** seen combinations of the N values.  A new entry is made in iTab
   95018 ** if the current N values are new.
   95019 **
   95020 ** A jump to addrRepeat is made and the N+1 values are popped from the
   95021 ** stack if the top N elements are not distinct.
   95022 */
   95023 static void codeDistinct(
   95024   Parse *pParse,     /* Parsing and code generating context */
   95025   int iTab,          /* A sorting index used to test for distinctness */
   95026   int addrRepeat,    /* Jump to here if not distinct */
   95027   int N,             /* Number of elements */
   95028   int iMem           /* First element */
   95029 ){
   95030   Vdbe *v;
   95031   int r1;
   95032 
   95033   v = pParse->pVdbe;
   95034   r1 = sqlite3GetTempReg(pParse);
   95035   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
   95036   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   95037   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   95038   sqlite3ReleaseTempReg(pParse, r1);
   95039 }
   95040 
   95041 #ifndef SQLITE_OMIT_SUBQUERY
   95042 /*
   95043 ** Generate an error message when a SELECT is used within a subexpression
   95044 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   95045 ** column.  We do this in a subroutine because the error used to occur
   95046 ** in multiple places.  (The error only occurs in one place now, but we
   95047 ** retain the subroutine to minimize code disruption.)
   95048 */
   95049 static int checkForMultiColumnSelectError(
   95050   Parse *pParse,       /* Parse context. */
   95051   SelectDest *pDest,   /* Destination of SELECT results */
   95052   int nExpr            /* Number of result columns returned by SELECT */
   95053 ){
   95054   int eDest = pDest->eDest;
   95055   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   95056     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   95057        "a SELECT that is part of an expression");
   95058     return 1;
   95059   }else{
   95060     return 0;
   95061   }
   95062 }
   95063 #endif
   95064 
   95065 /*
   95066 ** This routine generates the code for the inside of the inner loop
   95067 ** of a SELECT.
   95068 **
   95069 ** If srcTab and nColumn are both zero, then the pEList expressions
   95070 ** are evaluated in order to get the data for this row.  If nColumn>0
   95071 ** then data is pulled from srcTab and pEList is used only to get the
   95072 ** datatypes for each column.
   95073 */
   95074 static void selectInnerLoop(
   95075   Parse *pParse,          /* The parser context */
   95076   Select *p,              /* The complete select statement being coded */
   95077   ExprList *pEList,       /* List of values being extracted */
   95078   int srcTab,             /* Pull data from this table */
   95079   int nColumn,            /* Number of columns in the source table */
   95080   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   95081   int distinct,           /* If >=0, make sure results are distinct */
   95082   SelectDest *pDest,      /* How to dispose of the results */
   95083   int iContinue,          /* Jump here to continue with next row */
   95084   int iBreak              /* Jump here to break out of the inner loop */
   95085 ){
   95086   Vdbe *v = pParse->pVdbe;
   95087   int i;
   95088   int hasDistinct;        /* True if the DISTINCT keyword is present */
   95089   int regResult;              /* Start of memory holding result set */
   95090   int eDest = pDest->eDest;   /* How to dispose of results */
   95091   int iParm = pDest->iParm;   /* First argument to disposal method */
   95092   int nResultCol;             /* Number of result columns */
   95093 
   95094   assert( v );
   95095   if( NEVER(v==0) ) return;
   95096   assert( pEList!=0 );
   95097   hasDistinct = distinct>=0;
   95098   if( pOrderBy==0 && !hasDistinct ){
   95099     codeOffset(v, p, iContinue);
   95100   }
   95101 
   95102   /* Pull the requested columns.
   95103   */
   95104   if( nColumn>0 ){
   95105     nResultCol = nColumn;
   95106   }else{
   95107     nResultCol = pEList->nExpr;
   95108   }
   95109   if( pDest->iMem==0 ){
   95110     pDest->iMem = pParse->nMem+1;
   95111     pDest->nMem = nResultCol;
   95112     pParse->nMem += nResultCol;
   95113   }else{
   95114     assert( pDest->nMem==nResultCol );
   95115   }
   95116   regResult = pDest->iMem;
   95117   if( nColumn>0 ){
   95118     for(i=0; i<nColumn; i++){
   95119       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   95120     }
   95121   }else if( eDest!=SRT_Exists ){
   95122     /* If the destination is an EXISTS(...) expression, the actual
   95123     ** values returned by the SELECT are not required.
   95124     */
   95125     sqlite3ExprCacheClear(pParse);
   95126     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
   95127   }
   95128   nColumn = nResultCol;
   95129 
   95130   /* If the DISTINCT keyword was present on the SELECT statement
   95131   ** and this row has been seen before, then do not make this row
   95132   ** part of the result.
   95133   */
   95134   if( hasDistinct ){
   95135     assert( pEList!=0 );
   95136     assert( pEList->nExpr==nColumn );
   95137     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
   95138     if( pOrderBy==0 ){
   95139       codeOffset(v, p, iContinue);
   95140     }
   95141   }
   95142 
   95143   switch( eDest ){
   95144     /* In this mode, write each query result to the key of the temporary
   95145     ** table iParm.
   95146     */
   95147 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   95148     case SRT_Union: {
   95149       int r1;
   95150       r1 = sqlite3GetTempReg(pParse);
   95151       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95152       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   95153       sqlite3ReleaseTempReg(pParse, r1);
   95154       break;
   95155     }
   95156 
   95157     /* Construct a record from the query result, but instead of
   95158     ** saving that record, use it as a key to delete elements from
   95159     ** the temporary table iParm.
   95160     */
   95161     case SRT_Except: {
   95162       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
   95163       break;
   95164     }
   95165 #endif
   95166 
   95167     /* Store the result as data using a unique key.
   95168     */
   95169     case SRT_Table:
   95170     case SRT_EphemTab: {
   95171       int r1 = sqlite3GetTempReg(pParse);
   95172       testcase( eDest==SRT_Table );
   95173       testcase( eDest==SRT_EphemTab );
   95174       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95175       if( pOrderBy ){
   95176         pushOntoSorter(pParse, pOrderBy, p, r1);
   95177       }else{
   95178         int r2 = sqlite3GetTempReg(pParse);
   95179         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   95180         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   95181         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95182         sqlite3ReleaseTempReg(pParse, r2);
   95183       }
   95184       sqlite3ReleaseTempReg(pParse, r1);
   95185       break;
   95186     }
   95187 
   95188 #ifndef SQLITE_OMIT_SUBQUERY
   95189     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   95190     ** then there should be a single item on the stack.  Write this
   95191     ** item into the set table with bogus data.
   95192     */
   95193     case SRT_Set: {
   95194       assert( nColumn==1 );
   95195       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
   95196       if( pOrderBy ){
   95197         /* At first glance you would think we could optimize out the
   95198         ** ORDER BY in this case since the order of entries in the set
   95199         ** does not matter.  But there might be a LIMIT clause, in which
   95200         ** case the order does matter */
   95201         pushOntoSorter(pParse, pOrderBy, p, regResult);
   95202       }else{
   95203         int r1 = sqlite3GetTempReg(pParse);
   95204         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
   95205         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   95206         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   95207         sqlite3ReleaseTempReg(pParse, r1);
   95208       }
   95209       break;
   95210     }
   95211 
   95212     /* If any row exist in the result set, record that fact and abort.
   95213     */
   95214     case SRT_Exists: {
   95215       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   95216       /* The LIMIT clause will terminate the loop for us */
   95217       break;
   95218     }
   95219 
   95220     /* If this is a scalar select that is part of an expression, then
   95221     ** store the results in the appropriate memory cell and break out
   95222     ** of the scan loop.
   95223     */
   95224     case SRT_Mem: {
   95225       assert( nColumn==1 );
   95226       if( pOrderBy ){
   95227         pushOntoSorter(pParse, pOrderBy, p, regResult);
   95228       }else{
   95229         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   95230         /* The LIMIT clause will jump out of the loop for us */
   95231       }
   95232       break;
   95233     }
   95234 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   95235 
   95236     /* Send the data to the callback function or to a subroutine.  In the
   95237     ** case of a subroutine, the subroutine itself is responsible for
   95238     ** popping the data from the stack.
   95239     */
   95240     case SRT_Coroutine:
   95241     case SRT_Output: {
   95242       testcase( eDest==SRT_Coroutine );
   95243       testcase( eDest==SRT_Output );
   95244       if( pOrderBy ){
   95245         int r1 = sqlite3GetTempReg(pParse);
   95246         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95247         pushOntoSorter(pParse, pOrderBy, p, r1);
   95248         sqlite3ReleaseTempReg(pParse, r1);
   95249       }else if( eDest==SRT_Coroutine ){
   95250         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   95251       }else{
   95252         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
   95253         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
   95254       }
   95255       break;
   95256     }
   95257 
   95258 #if !defined(SQLITE_OMIT_TRIGGER)
   95259     /* Discard the results.  This is used for SELECT statements inside
   95260     ** the body of a TRIGGER.  The purpose of such selects is to call
   95261     ** user-defined functions that have side effects.  We do not care
   95262     ** about the actual results of the select.
   95263     */
   95264     default: {
   95265       assert( eDest==SRT_Discard );
   95266       break;
   95267     }
   95268 #endif
   95269   }
   95270 
   95271   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   95272   ** there is a sorter, in which case the sorter has already limited
   95273   ** the output for us.
   95274   */
   95275   if( pOrderBy==0 && p->iLimit ){
   95276     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   95277   }
   95278 }
   95279 
   95280 /*
   95281 ** Given an expression list, generate a KeyInfo structure that records
   95282 ** the collating sequence for each expression in that expression list.
   95283 **
   95284 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   95285 ** KeyInfo structure is appropriate for initializing a virtual index to
   95286 ** implement that clause.  If the ExprList is the result set of a SELECT
   95287 ** then the KeyInfo structure is appropriate for initializing a virtual
   95288 ** index to implement a DISTINCT test.
   95289 **
   95290 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   95291 ** function is responsible for seeing that this structure is eventually
   95292 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   95293 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   95294 */
   95295 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   95296   sqlite3 *db = pParse->db;
   95297   int nExpr;
   95298   KeyInfo *pInfo;
   95299   struct ExprList_item *pItem;
   95300   int i;
   95301 
   95302   nExpr = pList->nExpr;
   95303   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   95304   if( pInfo ){
   95305     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   95306     pInfo->nField = (u16)nExpr;
   95307     pInfo->enc = ENC(db);
   95308     pInfo->db = db;
   95309     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   95310       CollSeq *pColl;
   95311       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   95312       if( !pColl ){
   95313         pColl = db->pDfltColl;
   95314       }
   95315       pInfo->aColl[i] = pColl;
   95316       pInfo->aSortOrder[i] = pItem->sortOrder;
   95317     }
   95318   }
   95319   return pInfo;
   95320 }
   95321 
   95322 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   95323 /*
   95324 ** Name of the connection operator, used for error messages.
   95325 */
   95326 static const char *selectOpName(int id){
   95327   char *z;
   95328   switch( id ){
   95329     case TK_ALL:       z = "UNION ALL";   break;
   95330     case TK_INTERSECT: z = "INTERSECT";   break;
   95331     case TK_EXCEPT:    z = "EXCEPT";      break;
   95332     default:           z = "UNION";       break;
   95333   }
   95334   return z;
   95335 }
   95336 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   95337 
   95338 #ifndef SQLITE_OMIT_EXPLAIN
   95339 /*
   95340 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   95341 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   95342 ** where the caption is of the form:
   95343 **
   95344 **   "USE TEMP B-TREE FOR xxx"
   95345 **
   95346 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   95347 ** is determined by the zUsage argument.
   95348 */
   95349 static void explainTempTable(Parse *pParse, const char *zUsage){
   95350   if( pParse->explain==2 ){
   95351     Vdbe *v = pParse->pVdbe;
   95352     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   95353     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   95354   }
   95355 }
   95356 
   95357 /*
   95358 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   95359 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   95360 ** in sqlite3Select() to assign values to structure member variables that
   95361 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   95362 ** code with #ifndef directives.
   95363 */
   95364 # define explainSetInteger(a, b) a = b
   95365 
   95366 #else
   95367 /* No-op versions of the explainXXX() functions and macros. */
   95368 # define explainTempTable(y,z)
   95369 # define explainSetInteger(y,z)
   95370 #endif
   95371 
   95372 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
   95373 /*
   95374 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   95375 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   95376 ** where the caption is of one of the two forms:
   95377 **
   95378 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   95379 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   95380 **
   95381 ** where iSub1 and iSub2 are the integers passed as the corresponding
   95382 ** function parameters, and op is the text representation of the parameter
   95383 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   95384 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   95385 ** false, or the second form if it is true.
   95386 */
   95387 static void explainComposite(
   95388   Parse *pParse,                  /* Parse context */
   95389   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   95390   int iSub1,                      /* Subquery id 1 */
   95391   int iSub2,                      /* Subquery id 2 */
   95392   int bUseTmp                     /* True if a temp table was used */
   95393 ){
   95394   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   95395   if( pParse->explain==2 ){
   95396     Vdbe *v = pParse->pVdbe;
   95397     char *zMsg = sqlite3MPrintf(
   95398         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   95399         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   95400     );
   95401     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   95402   }
   95403 }
   95404 #else
   95405 /* No-op versions of the explainXXX() functions and macros. */
   95406 # define explainComposite(v,w,x,y,z)
   95407 #endif
   95408 
   95409 /*
   95410 ** If the inner loop was generated using a non-null pOrderBy argument,
   95411 ** then the results were placed in a sorter.  After the loop is terminated
   95412 ** we need to run the sorter and output the results.  The following
   95413 ** routine generates the code needed to do that.
   95414 */
   95415 static void generateSortTail(
   95416   Parse *pParse,    /* Parsing context */
   95417   Select *p,        /* The SELECT statement */
   95418   Vdbe *v,          /* Generate code into this VDBE */
   95419   int nColumn,      /* Number of columns of data */
   95420   SelectDest *pDest /* Write the sorted results here */
   95421 ){
   95422   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   95423   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   95424   int addr;
   95425   int iTab;
   95426   int pseudoTab = 0;
   95427   ExprList *pOrderBy = p->pOrderBy;
   95428 
   95429   int eDest = pDest->eDest;
   95430   int iParm = pDest->iParm;
   95431 
   95432   int regRow;
   95433   int regRowid;
   95434 
   95435   iTab = pOrderBy->iECursor;
   95436   regRow = sqlite3GetTempReg(pParse);
   95437   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   95438     pseudoTab = pParse->nTab++;
   95439     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   95440     regRowid = 0;
   95441   }else{
   95442     regRowid = sqlite3GetTempReg(pParse);
   95443   }
   95444   if( p->selFlags & SF_UseSorter ){
   95445     int regSortOut = ++pParse->nMem;
   95446     int ptab2 = pParse->nTab++;
   95447     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
   95448     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
   95449     codeOffset(v, p, addrContinue);
   95450     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
   95451     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
   95452     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   95453   }else{
   95454     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
   95455     codeOffset(v, p, addrContinue);
   95456     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
   95457   }
   95458   switch( eDest ){
   95459     case SRT_Table:
   95460     case SRT_EphemTab: {
   95461       testcase( eDest==SRT_Table );
   95462       testcase( eDest==SRT_EphemTab );
   95463       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   95464       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   95465       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95466       break;
   95467     }
   95468 #ifndef SQLITE_OMIT_SUBQUERY
   95469     case SRT_Set: {
   95470       assert( nColumn==1 );
   95471       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
   95472       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   95473       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   95474       break;
   95475     }
   95476     case SRT_Mem: {
   95477       assert( nColumn==1 );
   95478       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   95479       /* The LIMIT clause will terminate the loop for us */
   95480       break;
   95481     }
   95482 #endif
   95483     default: {
   95484       int i;
   95485       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   95486       testcase( eDest==SRT_Output );
   95487       testcase( eDest==SRT_Coroutine );
   95488       for(i=0; i<nColumn; i++){
   95489         assert( regRow!=pDest->iMem+i );
   95490         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
   95491         if( i==0 ){
   95492           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   95493         }
   95494       }
   95495       if( eDest==SRT_Output ){
   95496         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
   95497         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
   95498       }else{
   95499         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   95500       }
   95501       break;
   95502     }
   95503   }
   95504   sqlite3ReleaseTempReg(pParse, regRow);
   95505   sqlite3ReleaseTempReg(pParse, regRowid);
   95506 
   95507   /* The bottom of the loop
   95508   */
   95509   sqlite3VdbeResolveLabel(v, addrContinue);
   95510   if( p->selFlags & SF_UseSorter ){
   95511     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
   95512   }else{
   95513     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
   95514   }
   95515   sqlite3VdbeResolveLabel(v, addrBreak);
   95516   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   95517     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
   95518   }
   95519 }
   95520 
   95521 /*
   95522 ** Return a pointer to a string containing the 'declaration type' of the
   95523 ** expression pExpr. The string may be treated as static by the caller.
   95524 **
   95525 ** The declaration type is the exact datatype definition extracted from the
   95526 ** original CREATE TABLE statement if the expression is a column. The
   95527 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   95528 ** is considered a column can be complex in the presence of subqueries. The
   95529 ** result-set expression in all of the following SELECT statements is
   95530 ** considered a column by this function.
   95531 **
   95532 **   SELECT col FROM tbl;
   95533 **   SELECT (SELECT col FROM tbl;
   95534 **   SELECT (SELECT col FROM tbl);
   95535 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   95536 **
   95537 ** The declaration type for any expression other than a column is NULL.
   95538 */
   95539 static const char *columnType(
   95540   NameContext *pNC,
   95541   Expr *pExpr,
   95542   const char **pzOriginDb,
   95543   const char **pzOriginTab,
   95544   const char **pzOriginCol
   95545 ){
   95546   char const *zType = 0;
   95547   char const *zOriginDb = 0;
   95548   char const *zOriginTab = 0;
   95549   char const *zOriginCol = 0;
   95550   int j;
   95551   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   95552 
   95553   switch( pExpr->op ){
   95554     case TK_AGG_COLUMN:
   95555     case TK_COLUMN: {
   95556       /* The expression is a column. Locate the table the column is being
   95557       ** extracted from in NameContext.pSrcList. This table may be real
   95558       ** database table or a subquery.
   95559       */
   95560       Table *pTab = 0;            /* Table structure column is extracted from */
   95561       Select *pS = 0;             /* Select the column is extracted from */
   95562       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   95563       testcase( pExpr->op==TK_AGG_COLUMN );
   95564       testcase( pExpr->op==TK_COLUMN );
   95565       while( pNC && !pTab ){
   95566         SrcList *pTabList = pNC->pSrcList;
   95567         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   95568         if( j<pTabList->nSrc ){
   95569           pTab = pTabList->a[j].pTab;
   95570           pS = pTabList->a[j].pSelect;
   95571         }else{
   95572           pNC = pNC->pNext;
   95573         }
   95574       }
   95575 
   95576       if( pTab==0 ){
   95577         /* At one time, code such as "SELECT new.x" within a trigger would
   95578         ** cause this condition to run.  Since then, we have restructured how
   95579         ** trigger code is generated and so this condition is no longer
   95580         ** possible. However, it can still be true for statements like
   95581         ** the following:
   95582         **
   95583         **   CREATE TABLE t1(col INTEGER);
   95584         **   SELECT (SELECT t1.col) FROM FROM t1;
   95585         **
   95586         ** when columnType() is called on the expression "t1.col" in the
   95587         ** sub-select. In this case, set the column type to NULL, even
   95588         ** though it should really be "INTEGER".
   95589         **
   95590         ** This is not a problem, as the column type of "t1.col" is never
   95591         ** used. When columnType() is called on the expression
   95592         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   95593         ** branch below.  */
   95594         break;
   95595       }
   95596 
   95597       assert( pTab && pExpr->pTab==pTab );
   95598       if( pS ){
   95599         /* The "table" is actually a sub-select or a view in the FROM clause
   95600         ** of the SELECT statement. Return the declaration type and origin
   95601         ** data for the result-set column of the sub-select.
   95602         */
   95603         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   95604           /* If iCol is less than zero, then the expression requests the
   95605           ** rowid of the sub-select or view. This expression is legal (see
   95606           ** test case misc2.2.2) - it always evaluates to NULL.
   95607           */
   95608           NameContext sNC;
   95609           Expr *p = pS->pEList->a[iCol].pExpr;
   95610           sNC.pSrcList = pS->pSrc;
   95611           sNC.pNext = pNC;
   95612           sNC.pParse = pNC->pParse;
   95613           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   95614         }
   95615       }else if( ALWAYS(pTab->pSchema) ){
   95616         /* A real table */
   95617         assert( !pS );
   95618         if( iCol<0 ) iCol = pTab->iPKey;
   95619         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   95620         if( iCol<0 ){
   95621           zType = "INTEGER";
   95622           zOriginCol = "rowid";
   95623         }else{
   95624           zType = pTab->aCol[iCol].zType;
   95625           zOriginCol = pTab->aCol[iCol].zName;
   95626         }
   95627         zOriginTab = pTab->zName;
   95628         if( pNC->pParse ){
   95629           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   95630           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   95631         }
   95632       }
   95633       break;
   95634     }
   95635 #ifndef SQLITE_OMIT_SUBQUERY
   95636     case TK_SELECT: {
   95637       /* The expression is a sub-select. Return the declaration type and
   95638       ** origin info for the single column in the result set of the SELECT
   95639       ** statement.
   95640       */
   95641       NameContext sNC;
   95642       Select *pS = pExpr->x.pSelect;
   95643       Expr *p = pS->pEList->a[0].pExpr;
   95644       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   95645       sNC.pSrcList = pS->pSrc;
   95646       sNC.pNext = pNC;
   95647       sNC.pParse = pNC->pParse;
   95648       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   95649       break;
   95650     }
   95651 #endif
   95652   }
   95653 
   95654   if( pzOriginDb ){
   95655     assert( pzOriginTab && pzOriginCol );
   95656     *pzOriginDb = zOriginDb;
   95657     *pzOriginTab = zOriginTab;
   95658     *pzOriginCol = zOriginCol;
   95659   }
   95660   return zType;
   95661 }
   95662 
   95663 /*
   95664 ** Generate code that will tell the VDBE the declaration types of columns
   95665 ** in the result set.
   95666 */
   95667 static void generateColumnTypes(
   95668   Parse *pParse,      /* Parser context */
   95669   SrcList *pTabList,  /* List of tables */
   95670   ExprList *pEList    /* Expressions defining the result set */
   95671 ){
   95672 #ifndef SQLITE_OMIT_DECLTYPE
   95673   Vdbe *v = pParse->pVdbe;
   95674   int i;
   95675   NameContext sNC;
   95676   sNC.pSrcList = pTabList;
   95677   sNC.pParse = pParse;
   95678   for(i=0; i<pEList->nExpr; i++){
   95679     Expr *p = pEList->a[i].pExpr;
   95680     const char *zType;
   95681 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   95682     const char *zOrigDb = 0;
   95683     const char *zOrigTab = 0;
   95684     const char *zOrigCol = 0;
   95685     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   95686 
   95687     /* The vdbe must make its own copy of the column-type and other
   95688     ** column specific strings, in case the schema is reset before this
   95689     ** virtual machine is deleted.
   95690     */
   95691     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   95692     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   95693     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   95694 #else
   95695     zType = columnType(&sNC, p, 0, 0, 0);
   95696 #endif
   95697     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   95698   }
   95699 #endif /* SQLITE_OMIT_DECLTYPE */
   95700 }
   95701 
   95702 /*
   95703 ** Generate code that will tell the VDBE the names of columns
   95704 ** in the result set.  This information is used to provide the
   95705 ** azCol[] values in the callback.
   95706 */
   95707 static void generateColumnNames(
   95708   Parse *pParse,      /* Parser context */
   95709   SrcList *pTabList,  /* List of tables */
   95710   ExprList *pEList    /* Expressions defining the result set */
   95711 ){
   95712   Vdbe *v = pParse->pVdbe;
   95713   int i, j;
   95714   sqlite3 *db = pParse->db;
   95715   int fullNames, shortNames;
   95716 
   95717 #ifndef SQLITE_OMIT_EXPLAIN
   95718   /* If this is an EXPLAIN, skip this step */
   95719   if( pParse->explain ){
   95720     return;
   95721   }
   95722 #endif
   95723 
   95724   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   95725   pParse->colNamesSet = 1;
   95726   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   95727   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   95728   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   95729   for(i=0; i<pEList->nExpr; i++){
   95730     Expr *p;
   95731     p = pEList->a[i].pExpr;
   95732     if( NEVER(p==0) ) continue;
   95733     if( pEList->a[i].zName ){
   95734       char *zName = pEList->a[i].zName;
   95735       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   95736     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   95737       Table *pTab;
   95738       char *zCol;
   95739       int iCol = p->iColumn;
   95740       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   95741         if( pTabList->a[j].iCursor==p->iTable ) break;
   95742       }
   95743       assert( j<pTabList->nSrc );
   95744       pTab = pTabList->a[j].pTab;
   95745       if( iCol<0 ) iCol = pTab->iPKey;
   95746       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   95747       if( iCol<0 ){
   95748         zCol = "rowid";
   95749       }else{
   95750         zCol = pTab->aCol[iCol].zName;
   95751       }
   95752       if( !shortNames && !fullNames ){
   95753         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   95754             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   95755       }else if( fullNames ){
   95756         char *zName = 0;
   95757         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   95758         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   95759       }else{
   95760         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   95761       }
   95762     }else{
   95763       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   95764           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   95765     }
   95766   }
   95767   generateColumnTypes(pParse, pTabList, pEList);
   95768 }
   95769 
   95770 /*
   95771 ** Given a an expression list (which is really the list of expressions
   95772 ** that form the result set of a SELECT statement) compute appropriate
   95773 ** column names for a table that would hold the expression list.
   95774 **
   95775 ** All column names will be unique.
   95776 **
   95777 ** Only the column names are computed.  Column.zType, Column.zColl,
   95778 ** and other fields of Column are zeroed.
   95779 **
   95780 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   95781 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   95782 */
   95783 static int selectColumnsFromExprList(
   95784   Parse *pParse,          /* Parsing context */
   95785   ExprList *pEList,       /* Expr list from which to derive column names */
   95786   int *pnCol,             /* Write the number of columns here */
   95787   Column **paCol          /* Write the new column list here */
   95788 ){
   95789   sqlite3 *db = pParse->db;   /* Database connection */
   95790   int i, j;                   /* Loop counters */
   95791   int cnt;                    /* Index added to make the name unique */
   95792   Column *aCol, *pCol;        /* For looping over result columns */
   95793   int nCol;                   /* Number of columns in the result set */
   95794   Expr *p;                    /* Expression for a single result column */
   95795   char *zName;                /* Column name */
   95796   int nName;                  /* Size of name in zName[] */
   95797 
   95798   *pnCol = nCol = pEList ? pEList->nExpr : 0;
   95799   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   95800   if( aCol==0 ) return SQLITE_NOMEM;
   95801   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   95802     /* Get an appropriate name for the column
   95803     */
   95804     p = pEList->a[i].pExpr;
   95805     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
   95806                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
   95807     if( (zName = pEList->a[i].zName)!=0 ){
   95808       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   95809       zName = sqlite3DbStrDup(db, zName);
   95810     }else{
   95811       Expr *pColExpr = p;  /* The expression that is the result column name */
   95812       Table *pTab;         /* Table associated with this expression */
   95813       while( pColExpr->op==TK_DOT ){
   95814         pColExpr = pColExpr->pRight;
   95815         assert( pColExpr!=0 );
   95816       }
   95817       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   95818         /* For columns use the column name name */
   95819         int iCol = pColExpr->iColumn;
   95820         pTab = pColExpr->pTab;
   95821         if( iCol<0 ) iCol = pTab->iPKey;
   95822         zName = sqlite3MPrintf(db, "%s",
   95823                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   95824       }else if( pColExpr->op==TK_ID ){
   95825         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   95826         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   95827       }else{
   95828         /* Use the original text of the column expression as its name */
   95829         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   95830       }
   95831     }
   95832     if( db->mallocFailed ){
   95833       sqlite3DbFree(db, zName);
   95834       break;
   95835     }
   95836 
   95837     /* Make sure the column name is unique.  If the name is not unique,
   95838     ** append a integer to the name so that it becomes unique.
   95839     */
   95840     nName = sqlite3Strlen30(zName);
   95841     for(j=cnt=0; j<i; j++){
   95842       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   95843         char *zNewName;
   95844         zName[nName] = 0;
   95845         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   95846         sqlite3DbFree(db, zName);
   95847         zName = zNewName;
   95848         j = -1;
   95849         if( zName==0 ) break;
   95850       }
   95851     }
   95852     pCol->zName = zName;
   95853   }
   95854   if( db->mallocFailed ){
   95855     for(j=0; j<i; j++){
   95856       sqlite3DbFree(db, aCol[j].zName);
   95857     }
   95858     sqlite3DbFree(db, aCol);
   95859     *paCol = 0;
   95860     *pnCol = 0;
   95861     return SQLITE_NOMEM;
   95862   }
   95863   return SQLITE_OK;
   95864 }
   95865 
   95866 /*
   95867 ** Add type and collation information to a column list based on
   95868 ** a SELECT statement.
   95869 **
   95870 ** The column list presumably came from selectColumnNamesFromExprList().
   95871 ** The column list has only names, not types or collations.  This
   95872 ** routine goes through and adds the types and collations.
   95873 **
   95874 ** This routine requires that all identifiers in the SELECT
   95875 ** statement be resolved.
   95876 */
   95877 static void selectAddColumnTypeAndCollation(
   95878   Parse *pParse,        /* Parsing contexts */
   95879   int nCol,             /* Number of columns */
   95880   Column *aCol,         /* List of columns */
   95881   Select *pSelect       /* SELECT used to determine types and collations */
   95882 ){
   95883   sqlite3 *db = pParse->db;
   95884   NameContext sNC;
   95885   Column *pCol;
   95886   CollSeq *pColl;
   95887   int i;
   95888   Expr *p;
   95889   struct ExprList_item *a;
   95890 
   95891   assert( pSelect!=0 );
   95892   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   95893   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
   95894   if( db->mallocFailed ) return;
   95895   memset(&sNC, 0, sizeof(sNC));
   95896   sNC.pSrcList = pSelect->pSrc;
   95897   a = pSelect->pEList->a;
   95898   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   95899     p = a[i].pExpr;
   95900     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
   95901     pCol->affinity = sqlite3ExprAffinity(p);
   95902     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   95903     pColl = sqlite3ExprCollSeq(pParse, p);
   95904     if( pColl ){
   95905       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   95906     }
   95907   }
   95908 }
   95909 
   95910 /*
   95911 ** Given a SELECT statement, generate a Table structure that describes
   95912 ** the result set of that SELECT.
   95913 */
   95914 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   95915   Table *pTab;
   95916   sqlite3 *db = pParse->db;
   95917   int savedFlags;
   95918 
   95919   savedFlags = db->flags;
   95920   db->flags &= ~SQLITE_FullColNames;
   95921   db->flags |= SQLITE_ShortColNames;
   95922   sqlite3SelectPrep(pParse, pSelect, 0);
   95923   if( pParse->nErr ) return 0;
   95924   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   95925   db->flags = savedFlags;
   95926   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   95927   if( pTab==0 ){
   95928     return 0;
   95929   }
   95930   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   95931   ** is disabled */
   95932   assert( db->lookaside.bEnabled==0 );
   95933   pTab->nRef = 1;
   95934   pTab->zName = 0;
   95935   pTab->nRowEst = 1000000;
   95936   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   95937   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
   95938   pTab->iPKey = -1;
   95939   if( db->mallocFailed ){
   95940     sqlite3DeleteTable(db, pTab);
   95941     return 0;
   95942   }
   95943   return pTab;
   95944 }
   95945 
   95946 /*
   95947 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   95948 ** If an error occurs, return NULL and leave a message in pParse.
   95949 */
   95950 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   95951   Vdbe *v = pParse->pVdbe;
   95952   if( v==0 ){
   95953     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
   95954 #ifndef SQLITE_OMIT_TRACE
   95955     if( v ){
   95956       sqlite3VdbeAddOp0(v, OP_Trace);
   95957     }
   95958 #endif
   95959   }
   95960   return v;
   95961 }
   95962 
   95963 
   95964 /*
   95965 ** Compute the iLimit and iOffset fields of the SELECT based on the
   95966 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   95967 ** that appear in the original SQL statement after the LIMIT and OFFSET
   95968 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   95969 ** are the integer memory register numbers for counters used to compute
   95970 ** the limit and offset.  If there is no limit and/or offset, then
   95971 ** iLimit and iOffset are negative.
   95972 **
   95973 ** This routine changes the values of iLimit and iOffset only if
   95974 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   95975 ** iOffset should have been preset to appropriate default values
   95976 ** (usually but not always -1) prior to calling this routine.
   95977 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   95978 ** redefined.  The UNION ALL operator uses this property to force
   95979 ** the reuse of the same limit and offset registers across multiple
   95980 ** SELECT statements.
   95981 */
   95982 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   95983   Vdbe *v = 0;
   95984   int iLimit = 0;
   95985   int iOffset;
   95986   int addr1, n;
   95987   if( p->iLimit ) return;
   95988 
   95989   /*
   95990   ** "LIMIT -1" always shows all rows.  There is some
   95991   ** contraversy about what the correct behavior should be.
   95992   ** The current implementation interprets "LIMIT 0" to mean
   95993   ** no rows.
   95994   */
   95995   sqlite3ExprCacheClear(pParse);
   95996   assert( p->pOffset==0 || p->pLimit!=0 );
   95997   if( p->pLimit ){
   95998     p->iLimit = iLimit = ++pParse->nMem;
   95999     v = sqlite3GetVdbe(pParse);
   96000     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
   96001     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   96002       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   96003       VdbeComment((v, "LIMIT counter"));
   96004       if( n==0 ){
   96005         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   96006       }else{
   96007         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
   96008       }
   96009     }else{
   96010       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   96011       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
   96012       VdbeComment((v, "LIMIT counter"));
   96013       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
   96014     }
   96015     if( p->pOffset ){
   96016       p->iOffset = iOffset = ++pParse->nMem;
   96017       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   96018       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   96019       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
   96020       VdbeComment((v, "OFFSET counter"));
   96021       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
   96022       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   96023       sqlite3VdbeJumpHere(v, addr1);
   96024       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   96025       VdbeComment((v, "LIMIT+OFFSET"));
   96026       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
   96027       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   96028       sqlite3VdbeJumpHere(v, addr1);
   96029     }
   96030   }
   96031 }
   96032 
   96033 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96034 /*
   96035 ** Return the appropriate collating sequence for the iCol-th column of
   96036 ** the result set for the compound-select statement "p".  Return NULL if
   96037 ** the column has no default collating sequence.
   96038 **
   96039 ** The collating sequence for the compound select is taken from the
   96040 ** left-most term of the select that has a collating sequence.
   96041 */
   96042 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   96043   CollSeq *pRet;
   96044   if( p->pPrior ){
   96045     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   96046   }else{
   96047     pRet = 0;
   96048   }
   96049   assert( iCol>=0 );
   96050   if( pRet==0 && iCol<p->pEList->nExpr ){
   96051     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   96052   }
   96053   return pRet;
   96054 }
   96055 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   96056 
   96057 /* Forward reference */
   96058 static int multiSelectOrderBy(
   96059   Parse *pParse,        /* Parsing context */
   96060   Select *p,            /* The right-most of SELECTs to be coded */
   96061   SelectDest *pDest     /* What to do with query results */
   96062 );
   96063 
   96064 
   96065 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96066 /*
   96067 ** This routine is called to process a compound query form from
   96068 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   96069 ** INTERSECT
   96070 **
   96071 ** "p" points to the right-most of the two queries.  the query on the
   96072 ** left is p->pPrior.  The left query could also be a compound query
   96073 ** in which case this routine will be called recursively.
   96074 **
   96075 ** The results of the total query are to be written into a destination
   96076 ** of type eDest with parameter iParm.
   96077 **
   96078 ** Example 1:  Consider a three-way compound SQL statement.
   96079 **
   96080 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   96081 **
   96082 ** This statement is parsed up as follows:
   96083 **
   96084 **     SELECT c FROM t3
   96085 **      |
   96086 **      `----->  SELECT b FROM t2
   96087 **                |
   96088 **                `------>  SELECT a FROM t1
   96089 **
   96090 ** The arrows in the diagram above represent the Select.pPrior pointer.
   96091 ** So if this routine is called with p equal to the t3 query, then
   96092 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   96093 **
   96094 ** Notice that because of the way SQLite parses compound SELECTs, the
   96095 ** individual selects always group from left to right.
   96096 */
   96097 static int multiSelect(
   96098   Parse *pParse,        /* Parsing context */
   96099   Select *p,            /* The right-most of SELECTs to be coded */
   96100   SelectDest *pDest     /* What to do with query results */
   96101 ){
   96102   int rc = SQLITE_OK;   /* Success code from a subroutine */
   96103   Select *pPrior;       /* Another SELECT immediately to our left */
   96104   Vdbe *v;              /* Generate code to this VDBE */
   96105   SelectDest dest;      /* Alternative data destination */
   96106   Select *pDelete = 0;  /* Chain of simple selects to delete */
   96107   sqlite3 *db;          /* Database connection */
   96108 #ifndef SQLITE_OMIT_EXPLAIN
   96109   int iSub1;            /* EQP id of left-hand query */
   96110   int iSub2;            /* EQP id of right-hand query */
   96111 #endif
   96112 
   96113   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   96114   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   96115   */
   96116   assert( p && p->pPrior );  /* Calling function guarantees this much */
   96117   db = pParse->db;
   96118   pPrior = p->pPrior;
   96119   assert( pPrior->pRightmost!=pPrior );
   96120   assert( pPrior->pRightmost==p->pRightmost );
   96121   dest = *pDest;
   96122   if( pPrior->pOrderBy ){
   96123     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   96124       selectOpName(p->op));
   96125     rc = 1;
   96126     goto multi_select_end;
   96127   }
   96128   if( pPrior->pLimit ){
   96129     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   96130       selectOpName(p->op));
   96131     rc = 1;
   96132     goto multi_select_end;
   96133   }
   96134 
   96135   v = sqlite3GetVdbe(pParse);
   96136   assert( v!=0 );  /* The VDBE already created by calling function */
   96137 
   96138   /* Create the destination temporary table if necessary
   96139   */
   96140   if( dest.eDest==SRT_EphemTab ){
   96141     assert( p->pEList );
   96142     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
   96143     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   96144     dest.eDest = SRT_Table;
   96145   }
   96146 
   96147   /* Make sure all SELECTs in the statement have the same number of elements
   96148   ** in their result sets.
   96149   */
   96150   assert( p->pEList && pPrior->pEList );
   96151   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   96152     if( p->selFlags & SF_Values ){
   96153       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   96154     }else{
   96155       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   96156         " do not have the same number of result columns", selectOpName(p->op));
   96157     }
   96158     rc = 1;
   96159     goto multi_select_end;
   96160   }
   96161 
   96162   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   96163   */
   96164   if( p->pOrderBy ){
   96165     return multiSelectOrderBy(pParse, p, pDest);
   96166   }
   96167 
   96168   /* Generate code for the left and right SELECT statements.
   96169   */
   96170   switch( p->op ){
   96171     case TK_ALL: {
   96172       int addr = 0;
   96173       int nLimit;
   96174       assert( !pPrior->pLimit );
   96175       pPrior->pLimit = p->pLimit;
   96176       pPrior->pOffset = p->pOffset;
   96177       explainSetInteger(iSub1, pParse->iNextSelectId);
   96178       rc = sqlite3Select(pParse, pPrior, &dest);
   96179       p->pLimit = 0;
   96180       p->pOffset = 0;
   96181       if( rc ){
   96182         goto multi_select_end;
   96183       }
   96184       p->pPrior = 0;
   96185       p->iLimit = pPrior->iLimit;
   96186       p->iOffset = pPrior->iOffset;
   96187       if( p->iLimit ){
   96188         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
   96189         VdbeComment((v, "Jump ahead if LIMIT reached"));
   96190       }
   96191       explainSetInteger(iSub2, pParse->iNextSelectId);
   96192       rc = sqlite3Select(pParse, p, &dest);
   96193       testcase( rc!=SQLITE_OK );
   96194       pDelete = p->pPrior;
   96195       p->pPrior = pPrior;
   96196       p->nSelectRow += pPrior->nSelectRow;
   96197       if( pPrior->pLimit
   96198        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
   96199        && p->nSelectRow > (double)nLimit
   96200       ){
   96201         p->nSelectRow = (double)nLimit;
   96202       }
   96203       if( addr ){
   96204         sqlite3VdbeJumpHere(v, addr);
   96205       }
   96206       break;
   96207     }
   96208     case TK_EXCEPT:
   96209     case TK_UNION: {
   96210       int unionTab;    /* Cursor number of the temporary table holding result */
   96211       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   96212       int priorOp;     /* The SRT_ operation to apply to prior selects */
   96213       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   96214       int addr;
   96215       SelectDest uniondest;
   96216 
   96217       testcase( p->op==TK_EXCEPT );
   96218       testcase( p->op==TK_UNION );
   96219       priorOp = SRT_Union;
   96220       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
   96221         /* We can reuse a temporary table generated by a SELECT to our
   96222         ** right.
   96223         */
   96224         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
   96225                                      ** of a 3-way or more compound */
   96226         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   96227         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   96228         unionTab = dest.iParm;
   96229       }else{
   96230         /* We will need to create our own temporary table to hold the
   96231         ** intermediate results.
   96232         */
   96233         unionTab = pParse->nTab++;
   96234         assert( p->pOrderBy==0 );
   96235         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   96236         assert( p->addrOpenEphm[0] == -1 );
   96237         p->addrOpenEphm[0] = addr;
   96238         p->pRightmost->selFlags |= SF_UsesEphemeral;
   96239         assert( p->pEList );
   96240       }
   96241 
   96242       /* Code the SELECT statements to our left
   96243       */
   96244       assert( !pPrior->pOrderBy );
   96245       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   96246       explainSetInteger(iSub1, pParse->iNextSelectId);
   96247       rc = sqlite3Select(pParse, pPrior, &uniondest);
   96248       if( rc ){
   96249         goto multi_select_end;
   96250       }
   96251 
   96252       /* Code the current SELECT statement
   96253       */
   96254       if( p->op==TK_EXCEPT ){
   96255         op = SRT_Except;
   96256       }else{
   96257         assert( p->op==TK_UNION );
   96258         op = SRT_Union;
   96259       }
   96260       p->pPrior = 0;
   96261       pLimit = p->pLimit;
   96262       p->pLimit = 0;
   96263       pOffset = p->pOffset;
   96264       p->pOffset = 0;
   96265       uniondest.eDest = op;
   96266       explainSetInteger(iSub2, pParse->iNextSelectId);
   96267       rc = sqlite3Select(pParse, p, &uniondest);
   96268       testcase( rc!=SQLITE_OK );
   96269       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   96270       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   96271       sqlite3ExprListDelete(db, p->pOrderBy);
   96272       pDelete = p->pPrior;
   96273       p->pPrior = pPrior;
   96274       p->pOrderBy = 0;
   96275       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
   96276       sqlite3ExprDelete(db, p->pLimit);
   96277       p->pLimit = pLimit;
   96278       p->pOffset = pOffset;
   96279       p->iLimit = 0;
   96280       p->iOffset = 0;
   96281 
   96282       /* Convert the data in the temporary table into whatever form
   96283       ** it is that we currently need.
   96284       */
   96285       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
   96286       if( dest.eDest!=priorOp ){
   96287         int iCont, iBreak, iStart;
   96288         assert( p->pEList );
   96289         if( dest.eDest==SRT_Output ){
   96290           Select *pFirst = p;
   96291           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   96292           generateColumnNames(pParse, 0, pFirst->pEList);
   96293         }
   96294         iBreak = sqlite3VdbeMakeLabel(v);
   96295         iCont = sqlite3VdbeMakeLabel(v);
   96296         computeLimitRegisters(pParse, p, iBreak);
   96297         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
   96298         iStart = sqlite3VdbeCurrentAddr(v);
   96299         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
   96300                         0, -1, &dest, iCont, iBreak);
   96301         sqlite3VdbeResolveLabel(v, iCont);
   96302         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
   96303         sqlite3VdbeResolveLabel(v, iBreak);
   96304         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   96305       }
   96306       break;
   96307     }
   96308     default: assert( p->op==TK_INTERSECT ); {
   96309       int tab1, tab2;
   96310       int iCont, iBreak, iStart;
   96311       Expr *pLimit, *pOffset;
   96312       int addr;
   96313       SelectDest intersectdest;
   96314       int r1;
   96315 
   96316       /* INTERSECT is different from the others since it requires
   96317       ** two temporary tables.  Hence it has its own case.  Begin
   96318       ** by allocating the tables we will need.
   96319       */
   96320       tab1 = pParse->nTab++;
   96321       tab2 = pParse->nTab++;
   96322       assert( p->pOrderBy==0 );
   96323 
   96324       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   96325       assert( p->addrOpenEphm[0] == -1 );
   96326       p->addrOpenEphm[0] = addr;
   96327       p->pRightmost->selFlags |= SF_UsesEphemeral;
   96328       assert( p->pEList );
   96329 
   96330       /* Code the SELECTs to our left into temporary table "tab1".
   96331       */
   96332       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   96333       explainSetInteger(iSub1, pParse->iNextSelectId);
   96334       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   96335       if( rc ){
   96336         goto multi_select_end;
   96337       }
   96338 
   96339       /* Code the current SELECT into temporary table "tab2"
   96340       */
   96341       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   96342       assert( p->addrOpenEphm[1] == -1 );
   96343       p->addrOpenEphm[1] = addr;
   96344       p->pPrior = 0;
   96345       pLimit = p->pLimit;
   96346       p->pLimit = 0;
   96347       pOffset = p->pOffset;
   96348       p->pOffset = 0;
   96349       intersectdest.iParm = tab2;
   96350       explainSetInteger(iSub2, pParse->iNextSelectId);
   96351       rc = sqlite3Select(pParse, p, &intersectdest);
   96352       testcase( rc!=SQLITE_OK );
   96353       pDelete = p->pPrior;
   96354       p->pPrior = pPrior;
   96355       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   96356       sqlite3ExprDelete(db, p->pLimit);
   96357       p->pLimit = pLimit;
   96358       p->pOffset = pOffset;
   96359 
   96360       /* Generate code to take the intersection of the two temporary
   96361       ** tables.
   96362       */
   96363       assert( p->pEList );
   96364       if( dest.eDest==SRT_Output ){
   96365         Select *pFirst = p;
   96366         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   96367         generateColumnNames(pParse, 0, pFirst->pEList);
   96368       }
   96369       iBreak = sqlite3VdbeMakeLabel(v);
   96370       iCont = sqlite3VdbeMakeLabel(v);
   96371       computeLimitRegisters(pParse, p, iBreak);
   96372       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
   96373       r1 = sqlite3GetTempReg(pParse);
   96374       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   96375       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
   96376       sqlite3ReleaseTempReg(pParse, r1);
   96377       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
   96378                       0, -1, &dest, iCont, iBreak);
   96379       sqlite3VdbeResolveLabel(v, iCont);
   96380       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
   96381       sqlite3VdbeResolveLabel(v, iBreak);
   96382       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   96383       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   96384       break;
   96385     }
   96386   }
   96387 
   96388   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   96389 
   96390   /* Compute collating sequences used by
   96391   ** temporary tables needed to implement the compound select.
   96392   ** Attach the KeyInfo structure to all temporary tables.
   96393   **
   96394   ** This section is run by the right-most SELECT statement only.
   96395   ** SELECT statements to the left always skip this part.  The right-most
   96396   ** SELECT might also skip this part if it has no ORDER BY clause and
   96397   ** no temp tables are required.
   96398   */
   96399   if( p->selFlags & SF_UsesEphemeral ){
   96400     int i;                        /* Loop counter */
   96401     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   96402     Select *pLoop;                /* For looping through SELECT statements */
   96403     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   96404     int nCol;                     /* Number of columns in result set */
   96405 
   96406     assert( p->pRightmost==p );
   96407     nCol = p->pEList->nExpr;
   96408     pKeyInfo = sqlite3DbMallocZero(db,
   96409                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
   96410     if( !pKeyInfo ){
   96411       rc = SQLITE_NOMEM;
   96412       goto multi_select_end;
   96413     }
   96414 
   96415     pKeyInfo->enc = ENC(db);
   96416     pKeyInfo->nField = (u16)nCol;
   96417 
   96418     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   96419       *apColl = multiSelectCollSeq(pParse, p, i);
   96420       if( 0==*apColl ){
   96421         *apColl = db->pDfltColl;
   96422       }
   96423     }
   96424 
   96425     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   96426       for(i=0; i<2; i++){
   96427         int addr = pLoop->addrOpenEphm[i];
   96428         if( addr<0 ){
   96429           /* If [0] is unused then [1] is also unused.  So we can
   96430           ** always safely abort as soon as the first unused slot is found */
   96431           assert( pLoop->addrOpenEphm[1]<0 );
   96432           break;
   96433         }
   96434         sqlite3VdbeChangeP2(v, addr, nCol);
   96435         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
   96436         pLoop->addrOpenEphm[i] = -1;
   96437       }
   96438     }
   96439     sqlite3DbFree(db, pKeyInfo);
   96440   }
   96441 
   96442 multi_select_end:
   96443   pDest->iMem = dest.iMem;
   96444   pDest->nMem = dest.nMem;
   96445   sqlite3SelectDelete(db, pDelete);
   96446   return rc;
   96447 }
   96448 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   96449 
   96450 /*
   96451 ** Code an output subroutine for a coroutine implementation of a
   96452 ** SELECT statment.
   96453 **
   96454 ** The data to be output is contained in pIn->iMem.  There are
   96455 ** pIn->nMem columns to be output.  pDest is where the output should
   96456 ** be sent.
   96457 **
   96458 ** regReturn is the number of the register holding the subroutine
   96459 ** return address.
   96460 **
   96461 ** If regPrev>0 then it is the first register in a vector that
   96462 ** records the previous output.  mem[regPrev] is a flag that is false
   96463 ** if there has been no previous output.  If regPrev>0 then code is
   96464 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   96465 ** keys.
   96466 **
   96467 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   96468 ** iBreak.
   96469 */
   96470 static int generateOutputSubroutine(
   96471   Parse *pParse,          /* Parsing context */
   96472   Select *p,              /* The SELECT statement */
   96473   SelectDest *pIn,        /* Coroutine supplying data */
   96474   SelectDest *pDest,      /* Where to send the data */
   96475   int regReturn,          /* The return address register */
   96476   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   96477   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   96478   int p4type,             /* The p4 type for pKeyInfo */
   96479   int iBreak              /* Jump here if we hit the LIMIT */
   96480 ){
   96481   Vdbe *v = pParse->pVdbe;
   96482   int iContinue;
   96483   int addr;
   96484 
   96485   addr = sqlite3VdbeCurrentAddr(v);
   96486   iContinue = sqlite3VdbeMakeLabel(v);
   96487 
   96488   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   96489   */
   96490   if( regPrev ){
   96491     int j1, j2;
   96492     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
   96493     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
   96494                               (char*)pKeyInfo, p4type);
   96495     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
   96496     sqlite3VdbeJumpHere(v, j1);
   96497     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
   96498     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   96499   }
   96500   if( pParse->db->mallocFailed ) return 0;
   96501 
   96502   /* Suppress the the first OFFSET entries if there is an OFFSET clause
   96503   */
   96504   codeOffset(v, p, iContinue);
   96505 
   96506   switch( pDest->eDest ){
   96507     /* Store the result as data using a unique key.
   96508     */
   96509     case SRT_Table:
   96510     case SRT_EphemTab: {
   96511       int r1 = sqlite3GetTempReg(pParse);
   96512       int r2 = sqlite3GetTempReg(pParse);
   96513       testcase( pDest->eDest==SRT_Table );
   96514       testcase( pDest->eDest==SRT_EphemTab );
   96515       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
   96516       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
   96517       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
   96518       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   96519       sqlite3ReleaseTempReg(pParse, r2);
   96520       sqlite3ReleaseTempReg(pParse, r1);
   96521       break;
   96522     }
   96523 
   96524 #ifndef SQLITE_OMIT_SUBQUERY
   96525     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   96526     ** then there should be a single item on the stack.  Write this
   96527     ** item into the set table with bogus data.
   96528     */
   96529     case SRT_Set: {
   96530       int r1;
   96531       assert( pIn->nMem==1 );
   96532       p->affinity =
   96533          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
   96534       r1 = sqlite3GetTempReg(pParse);
   96535       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
   96536       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
   96537       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
   96538       sqlite3ReleaseTempReg(pParse, r1);
   96539       break;
   96540     }
   96541 
   96542 #if 0  /* Never occurs on an ORDER BY query */
   96543     /* If any row exist in the result set, record that fact and abort.
   96544     */
   96545     case SRT_Exists: {
   96546       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
   96547       /* The LIMIT clause will terminate the loop for us */
   96548       break;
   96549     }
   96550 #endif
   96551 
   96552     /* If this is a scalar select that is part of an expression, then
   96553     ** store the results in the appropriate memory cell and break out
   96554     ** of the scan loop.
   96555     */
   96556     case SRT_Mem: {
   96557       assert( pIn->nMem==1 );
   96558       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
   96559       /* The LIMIT clause will jump out of the loop for us */
   96560       break;
   96561     }
   96562 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   96563 
   96564     /* The results are stored in a sequence of registers
   96565     ** starting at pDest->iMem.  Then the co-routine yields.
   96566     */
   96567     case SRT_Coroutine: {
   96568       if( pDest->iMem==0 ){
   96569         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
   96570         pDest->nMem = pIn->nMem;
   96571       }
   96572       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
   96573       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   96574       break;
   96575     }
   96576 
   96577     /* If none of the above, then the result destination must be
   96578     ** SRT_Output.  This routine is never called with any other
   96579     ** destination other than the ones handled above or SRT_Output.
   96580     **
   96581     ** For SRT_Output, results are stored in a sequence of registers.
   96582     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   96583     ** return the next row of result.
   96584     */
   96585     default: {
   96586       assert( pDest->eDest==SRT_Output );
   96587       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
   96588       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
   96589       break;
   96590     }
   96591   }
   96592 
   96593   /* Jump to the end of the loop if the LIMIT is reached.
   96594   */
   96595   if( p->iLimit ){
   96596     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   96597   }
   96598 
   96599   /* Generate the subroutine return
   96600   */
   96601   sqlite3VdbeResolveLabel(v, iContinue);
   96602   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   96603 
   96604   return addr;
   96605 }
   96606 
   96607 /*
   96608 ** Alternative compound select code generator for cases when there
   96609 ** is an ORDER BY clause.
   96610 **
   96611 ** We assume a query of the following form:
   96612 **
   96613 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   96614 **
   96615 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   96616 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   96617 ** co-routines.  Then run the co-routines in parallel and merge the results
   96618 ** into the output.  In addition to the two coroutines (called selectA and
   96619 ** selectB) there are 7 subroutines:
   96620 **
   96621 **    outA:    Move the output of the selectA coroutine into the output
   96622 **             of the compound query.
   96623 **
   96624 **    outB:    Move the output of the selectB coroutine into the output
   96625 **             of the compound query.  (Only generated for UNION and
   96626 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   96627 **             appears only in B.)
   96628 **
   96629 **    AltB:    Called when there is data from both coroutines and A<B.
   96630 **
   96631 **    AeqB:    Called when there is data from both coroutines and A==B.
   96632 **
   96633 **    AgtB:    Called when there is data from both coroutines and A>B.
   96634 **
   96635 **    EofA:    Called when data is exhausted from selectA.
   96636 **
   96637 **    EofB:    Called when data is exhausted from selectB.
   96638 **
   96639 ** The implementation of the latter five subroutines depend on which
   96640 ** <operator> is used:
   96641 **
   96642 **
   96643 **             UNION ALL         UNION            EXCEPT          INTERSECT
   96644 **          -------------  -----------------  --------------  -----------------
   96645 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   96646 **
   96647 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   96648 **
   96649 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   96650 **
   96651 **   EofA:   outB, nextB      outB, nextB          halt             halt
   96652 **
   96653 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   96654 **
   96655 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   96656 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   96657 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   96658 ** following nextX causes a jump to the end of the select processing.
   96659 **
   96660 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   96661 ** within the output subroutine.  The regPrev register set holds the previously
   96662 ** output value.  A comparison is made against this value and the output
   96663 ** is skipped if the next results would be the same as the previous.
   96664 **
   96665 ** The implementation plan is to implement the two coroutines and seven
   96666 ** subroutines first, then put the control logic at the bottom.  Like this:
   96667 **
   96668 **          goto Init
   96669 **     coA: coroutine for left query (A)
   96670 **     coB: coroutine for right query (B)
   96671 **    outA: output one row of A
   96672 **    outB: output one row of B (UNION and UNION ALL only)
   96673 **    EofA: ...
   96674 **    EofB: ...
   96675 **    AltB: ...
   96676 **    AeqB: ...
   96677 **    AgtB: ...
   96678 **    Init: initialize coroutine registers
   96679 **          yield coA
   96680 **          if eof(A) goto EofA
   96681 **          yield coB
   96682 **          if eof(B) goto EofB
   96683 **    Cmpr: Compare A, B
   96684 **          Jump AltB, AeqB, AgtB
   96685 **     End: ...
   96686 **
   96687 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   96688 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   96689 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   96690 ** and AgtB jump to either L2 or to one of EofA or EofB.
   96691 */
   96692 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96693 static int multiSelectOrderBy(
   96694   Parse *pParse,        /* Parsing context */
   96695   Select *p,            /* The right-most of SELECTs to be coded */
   96696   SelectDest *pDest     /* What to do with query results */
   96697 ){
   96698   int i, j;             /* Loop counters */
   96699   Select *pPrior;       /* Another SELECT immediately to our left */
   96700   Vdbe *v;              /* Generate code to this VDBE */
   96701   SelectDest destA;     /* Destination for coroutine A */
   96702   SelectDest destB;     /* Destination for coroutine B */
   96703   int regAddrA;         /* Address register for select-A coroutine */
   96704   int regEofA;          /* Flag to indicate when select-A is complete */
   96705   int regAddrB;         /* Address register for select-B coroutine */
   96706   int regEofB;          /* Flag to indicate when select-B is complete */
   96707   int addrSelectA;      /* Address of the select-A coroutine */
   96708   int addrSelectB;      /* Address of the select-B coroutine */
   96709   int regOutA;          /* Address register for the output-A subroutine */
   96710   int regOutB;          /* Address register for the output-B subroutine */
   96711   int addrOutA;         /* Address of the output-A subroutine */
   96712   int addrOutB = 0;     /* Address of the output-B subroutine */
   96713   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   96714   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   96715   int addrAltB;         /* Address of the A<B subroutine */
   96716   int addrAeqB;         /* Address of the A==B subroutine */
   96717   int addrAgtB;         /* Address of the A>B subroutine */
   96718   int regLimitA;        /* Limit register for select-A */
   96719   int regLimitB;        /* Limit register for select-A */
   96720   int regPrev;          /* A range of registers to hold previous output */
   96721   int savedLimit;       /* Saved value of p->iLimit */
   96722   int savedOffset;      /* Saved value of p->iOffset */
   96723   int labelCmpr;        /* Label for the start of the merge algorithm */
   96724   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   96725   int j1;               /* Jump instructions that get retargetted */
   96726   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   96727   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   96728   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   96729   sqlite3 *db;          /* Database connection */
   96730   ExprList *pOrderBy;   /* The ORDER BY clause */
   96731   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   96732   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   96733 #ifndef SQLITE_OMIT_EXPLAIN
   96734   int iSub1;            /* EQP id of left-hand query */
   96735   int iSub2;            /* EQP id of right-hand query */
   96736 #endif
   96737 
   96738   assert( p->pOrderBy!=0 );
   96739   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   96740   db = pParse->db;
   96741   v = pParse->pVdbe;
   96742   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   96743   labelEnd = sqlite3VdbeMakeLabel(v);
   96744   labelCmpr = sqlite3VdbeMakeLabel(v);
   96745 
   96746 
   96747   /* Patch up the ORDER BY clause
   96748   */
   96749   op = p->op;
   96750   pPrior = p->pPrior;
   96751   assert( pPrior->pOrderBy==0 );
   96752   pOrderBy = p->pOrderBy;
   96753   assert( pOrderBy );
   96754   nOrderBy = pOrderBy->nExpr;
   96755 
   96756   /* For operators other than UNION ALL we have to make sure that
   96757   ** the ORDER BY clause covers every term of the result set.  Add
   96758   ** terms to the ORDER BY clause as necessary.
   96759   */
   96760   if( op!=TK_ALL ){
   96761     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   96762       struct ExprList_item *pItem;
   96763       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   96764         assert( pItem->iOrderByCol>0 );
   96765         if( pItem->iOrderByCol==i ) break;
   96766       }
   96767       if( j==nOrderBy ){
   96768         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   96769         if( pNew==0 ) return SQLITE_NOMEM;
   96770         pNew->flags |= EP_IntValue;
   96771         pNew->u.iValue = i;
   96772         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   96773         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
   96774       }
   96775     }
   96776   }
   96777 
   96778   /* Compute the comparison permutation and keyinfo that is used with
   96779   ** the permutation used to determine if the next
   96780   ** row of results comes from selectA or selectB.  Also add explicit
   96781   ** collations to the ORDER BY clause terms so that when the subqueries
   96782   ** to the right and the left are evaluated, they use the correct
   96783   ** collation.
   96784   */
   96785   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   96786   if( aPermute ){
   96787     struct ExprList_item *pItem;
   96788     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   96789       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
   96790       aPermute[i] = pItem->iOrderByCol - 1;
   96791     }
   96792     pKeyMerge =
   96793       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
   96794     if( pKeyMerge ){
   96795       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
   96796       pKeyMerge->nField = (u16)nOrderBy;
   96797       pKeyMerge->enc = ENC(db);
   96798       for(i=0; i<nOrderBy; i++){
   96799         CollSeq *pColl;
   96800         Expr *pTerm = pOrderBy->a[i].pExpr;
   96801         if( pTerm->flags & EP_ExpCollate ){
   96802           pColl = pTerm->pColl;
   96803         }else{
   96804           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
   96805           pTerm->flags |= EP_ExpCollate;
   96806           pTerm->pColl = pColl;
   96807         }
   96808         pKeyMerge->aColl[i] = pColl;
   96809         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   96810       }
   96811     }
   96812   }else{
   96813     pKeyMerge = 0;
   96814   }
   96815 
   96816   /* Reattach the ORDER BY clause to the query.
   96817   */
   96818   p->pOrderBy = pOrderBy;
   96819   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   96820 
   96821   /* Allocate a range of temporary registers and the KeyInfo needed
   96822   ** for the logic that removes duplicate result rows when the
   96823   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   96824   */
   96825   if( op==TK_ALL ){
   96826     regPrev = 0;
   96827   }else{
   96828     int nExpr = p->pEList->nExpr;
   96829     assert( nOrderBy>=nExpr || db->mallocFailed );
   96830     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
   96831     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   96832     pKeyDup = sqlite3DbMallocZero(db,
   96833                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
   96834     if( pKeyDup ){
   96835       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
   96836       pKeyDup->nField = (u16)nExpr;
   96837       pKeyDup->enc = ENC(db);
   96838       for(i=0; i<nExpr; i++){
   96839         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   96840         pKeyDup->aSortOrder[i] = 0;
   96841       }
   96842     }
   96843   }
   96844 
   96845   /* Separate the left and the right query from one another
   96846   */
   96847   p->pPrior = 0;
   96848   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   96849   if( pPrior->pPrior==0 ){
   96850     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   96851   }
   96852 
   96853   /* Compute the limit registers */
   96854   computeLimitRegisters(pParse, p, labelEnd);
   96855   if( p->iLimit && op==TK_ALL ){
   96856     regLimitA = ++pParse->nMem;
   96857     regLimitB = ++pParse->nMem;
   96858     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   96859                                   regLimitA);
   96860     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   96861   }else{
   96862     regLimitA = regLimitB = 0;
   96863   }
   96864   sqlite3ExprDelete(db, p->pLimit);
   96865   p->pLimit = 0;
   96866   sqlite3ExprDelete(db, p->pOffset);
   96867   p->pOffset = 0;
   96868 
   96869   regAddrA = ++pParse->nMem;
   96870   regEofA = ++pParse->nMem;
   96871   regAddrB = ++pParse->nMem;
   96872   regEofB = ++pParse->nMem;
   96873   regOutA = ++pParse->nMem;
   96874   regOutB = ++pParse->nMem;
   96875   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   96876   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   96877 
   96878   /* Jump past the various subroutines and coroutines to the main
   96879   ** merge loop
   96880   */
   96881   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
   96882   addrSelectA = sqlite3VdbeCurrentAddr(v);
   96883 
   96884 
   96885   /* Generate a coroutine to evaluate the SELECT statement to the
   96886   ** left of the compound operator - the "A" select.
   96887   */
   96888   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
   96889   pPrior->iLimit = regLimitA;
   96890   explainSetInteger(iSub1, pParse->iNextSelectId);
   96891   sqlite3Select(pParse, pPrior, &destA);
   96892   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
   96893   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96894   VdbeNoopComment((v, "End coroutine for left SELECT"));
   96895 
   96896   /* Generate a coroutine to evaluate the SELECT statement on
   96897   ** the right - the "B" select
   96898   */
   96899   addrSelectB = sqlite3VdbeCurrentAddr(v);
   96900   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
   96901   savedLimit = p->iLimit;
   96902   savedOffset = p->iOffset;
   96903   p->iLimit = regLimitB;
   96904   p->iOffset = 0;
   96905   explainSetInteger(iSub2, pParse->iNextSelectId);
   96906   sqlite3Select(pParse, p, &destB);
   96907   p->iLimit = savedLimit;
   96908   p->iOffset = savedOffset;
   96909   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
   96910   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96911   VdbeNoopComment((v, "End coroutine for right SELECT"));
   96912 
   96913   /* Generate a subroutine that outputs the current row of the A
   96914   ** select as the next output row of the compound select.
   96915   */
   96916   VdbeNoopComment((v, "Output routine for A"));
   96917   addrOutA = generateOutputSubroutine(pParse,
   96918                  p, &destA, pDest, regOutA,
   96919                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
   96920 
   96921   /* Generate a subroutine that outputs the current row of the B
   96922   ** select as the next output row of the compound select.
   96923   */
   96924   if( op==TK_ALL || op==TK_UNION ){
   96925     VdbeNoopComment((v, "Output routine for B"));
   96926     addrOutB = generateOutputSubroutine(pParse,
   96927                  p, &destB, pDest, regOutB,
   96928                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
   96929   }
   96930 
   96931   /* Generate a subroutine to run when the results from select A
   96932   ** are exhausted and only data in select B remains.
   96933   */
   96934   VdbeNoopComment((v, "eof-A subroutine"));
   96935   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   96936     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
   96937   }else{
   96938     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
   96939     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   96940     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96941     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   96942     p->nSelectRow += pPrior->nSelectRow;
   96943   }
   96944 
   96945   /* Generate a subroutine to run when the results from select B
   96946   ** are exhausted and only data in select A remains.
   96947   */
   96948   if( op==TK_INTERSECT ){
   96949     addrEofB = addrEofA;
   96950     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   96951   }else{
   96952     VdbeNoopComment((v, "eof-B subroutine"));
   96953     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
   96954     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   96955     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96956     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   96957   }
   96958 
   96959   /* Generate code to handle the case of A<B
   96960   */
   96961   VdbeNoopComment((v, "A-lt-B subroutine"));
   96962   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   96963   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96964   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   96965   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96966 
   96967   /* Generate code to handle the case of A==B
   96968   */
   96969   if( op==TK_ALL ){
   96970     addrAeqB = addrAltB;
   96971   }else if( op==TK_INTERSECT ){
   96972     addrAeqB = addrAltB;
   96973     addrAltB++;
   96974   }else{
   96975     VdbeNoopComment((v, "A-eq-B subroutine"));
   96976     addrAeqB =
   96977     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96978     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   96979     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96980   }
   96981 
   96982   /* Generate code to handle the case of A>B
   96983   */
   96984   VdbeNoopComment((v, "A-gt-B subroutine"));
   96985   addrAgtB = sqlite3VdbeCurrentAddr(v);
   96986   if( op==TK_ALL || op==TK_UNION ){
   96987     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   96988   }
   96989   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96990   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   96991   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96992 
   96993   /* This code runs once to initialize everything.
   96994   */
   96995   sqlite3VdbeJumpHere(v, j1);
   96996   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
   96997   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
   96998   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
   96999   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
   97000   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   97001   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   97002 
   97003   /* Implement the main merge loop
   97004   */
   97005   sqlite3VdbeResolveLabel(v, labelCmpr);
   97006   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   97007   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
   97008                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
   97009   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
   97010 
   97011   /* Release temporary registers
   97012   */
   97013   if( regPrev ){
   97014     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
   97015   }
   97016 
   97017   /* Jump to the this point in order to terminate the query.
   97018   */
   97019   sqlite3VdbeResolveLabel(v, labelEnd);
   97020 
   97021   /* Set the number of output columns
   97022   */
   97023   if( pDest->eDest==SRT_Output ){
   97024     Select *pFirst = pPrior;
   97025     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   97026     generateColumnNames(pParse, 0, pFirst->pEList);
   97027   }
   97028 
   97029   /* Reassembly the compound query so that it will be freed correctly
   97030   ** by the calling function */
   97031   if( p->pPrior ){
   97032     sqlite3SelectDelete(db, p->pPrior);
   97033   }
   97034   p->pPrior = pPrior;
   97035 
   97036   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   97037   **** subqueries ****/
   97038   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   97039   return SQLITE_OK;
   97040 }
   97041 #endif
   97042 
   97043 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   97044 /* Forward Declarations */
   97045 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   97046 static void substSelect(sqlite3*, Select *, int, ExprList *);
   97047 
   97048 /*
   97049 ** Scan through the expression pExpr.  Replace every reference to
   97050 ** a column in table number iTable with a copy of the iColumn-th
   97051 ** entry in pEList.  (But leave references to the ROWID column
   97052 ** unchanged.)
   97053 **
   97054 ** This routine is part of the flattening procedure.  A subquery
   97055 ** whose result set is defined by pEList appears as entry in the
   97056 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   97057 ** FORM clause entry is iTable.  This routine make the necessary
   97058 ** changes to pExpr so that it refers directly to the source table
   97059 ** of the subquery rather the result set of the subquery.
   97060 */
   97061 static Expr *substExpr(
   97062   sqlite3 *db,        /* Report malloc errors to this connection */
   97063   Expr *pExpr,        /* Expr in which substitution occurs */
   97064   int iTable,         /* Table to be substituted */
   97065   ExprList *pEList    /* Substitute expressions */
   97066 ){
   97067   if( pExpr==0 ) return 0;
   97068   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   97069     if( pExpr->iColumn<0 ){
   97070       pExpr->op = TK_NULL;
   97071     }else{
   97072       Expr *pNew;
   97073       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   97074       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   97075       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   97076       if( pNew && pExpr->pColl ){
   97077         pNew->pColl = pExpr->pColl;
   97078       }
   97079       sqlite3ExprDelete(db, pExpr);
   97080       pExpr = pNew;
   97081     }
   97082   }else{
   97083     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   97084     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   97085     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   97086       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   97087     }else{
   97088       substExprList(db, pExpr->x.pList, iTable, pEList);
   97089     }
   97090   }
   97091   return pExpr;
   97092 }
   97093 static void substExprList(
   97094   sqlite3 *db,         /* Report malloc errors here */
   97095   ExprList *pList,     /* List to scan and in which to make substitutes */
   97096   int iTable,          /* Table to be substituted */
   97097   ExprList *pEList     /* Substitute values */
   97098 ){
   97099   int i;
   97100   if( pList==0 ) return;
   97101   for(i=0; i<pList->nExpr; i++){
   97102     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   97103   }
   97104 }
   97105 static void substSelect(
   97106   sqlite3 *db,         /* Report malloc errors here */
   97107   Select *p,           /* SELECT statement in which to make substitutions */
   97108   int iTable,          /* Table to be replaced */
   97109   ExprList *pEList     /* Substitute values */
   97110 ){
   97111   SrcList *pSrc;
   97112   struct SrcList_item *pItem;
   97113   int i;
   97114   if( !p ) return;
   97115   substExprList(db, p->pEList, iTable, pEList);
   97116   substExprList(db, p->pGroupBy, iTable, pEList);
   97117   substExprList(db, p->pOrderBy, iTable, pEList);
   97118   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   97119   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   97120   substSelect(db, p->pPrior, iTable, pEList);
   97121   pSrc = p->pSrc;
   97122   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   97123   if( ALWAYS(pSrc) ){
   97124     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   97125       substSelect(db, pItem->pSelect, iTable, pEList);
   97126     }
   97127   }
   97128 }
   97129 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   97130 
   97131 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   97132 /*
   97133 ** This routine attempts to flatten subqueries as a performance optimization.
   97134 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
   97135 **
   97136 ** To understand the concept of flattening, consider the following
   97137 ** query:
   97138 **
   97139 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   97140 **
   97141 ** The default way of implementing this query is to execute the
   97142 ** subquery first and store the results in a temporary table, then
   97143 ** run the outer query on that temporary table.  This requires two
   97144 ** passes over the data.  Furthermore, because the temporary table
   97145 ** has no indices, the WHERE clause on the outer query cannot be
   97146 ** optimized.
   97147 **
   97148 ** This routine attempts to rewrite queries such as the above into
   97149 ** a single flat select, like this:
   97150 **
   97151 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   97152 **
   97153 ** The code generated for this simpification gives the same result
   97154 ** but only has to scan the data once.  And because indices might
   97155 ** exist on the table t1, a complete scan of the data might be
   97156 ** avoided.
   97157 **
   97158 ** Flattening is only attempted if all of the following are true:
   97159 **
   97160 **   (1)  The subquery and the outer query do not both use aggregates.
   97161 **
   97162 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   97163 **
   97164 **   (3)  The subquery is not the right operand of a left outer join
   97165 **        (Originally ticket #306.  Strengthened by ticket #3300)
   97166 **
   97167 **   (4)  The subquery is not DISTINCT.
   97168 **
   97169 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   97170 **        sub-queries that were excluded from this optimization. Restriction
   97171 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   97172 **
   97173 **   (6)  The subquery does not use aggregates or the outer query is not
   97174 **        DISTINCT.
   97175 **
   97176 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
   97177 **        A FROM clause, consider adding a FROM close with the special
   97178 **        table sqlite_once that consists of a single row containing a
   97179 **        single NULL.
   97180 **
   97181 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   97182 **
   97183 **   (9)  The subquery does not use LIMIT or the outer query does not use
   97184 **        aggregates.
   97185 **
   97186 **  (10)  The subquery does not use aggregates or the outer query does not
   97187 **        use LIMIT.
   97188 **
   97189 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   97190 **
   97191 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   97192 **        a separate restriction deriving from ticket #350.
   97193 **
   97194 **  (13)  The subquery and outer query do not both use LIMIT.
   97195 **
   97196 **  (14)  The subquery does not use OFFSET.
   97197 **
   97198 **  (15)  The outer query is not part of a compound select or the
   97199 **        subquery does not have a LIMIT clause.
   97200 **        (See ticket #2339 and ticket [02a8e81d44]).
   97201 **
   97202 **  (16)  The outer query is not an aggregate or the subquery does
   97203 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   97204 **        until we introduced the group_concat() function.
   97205 **
   97206 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   97207 **        compound clause made up entirely of non-aggregate queries, and
   97208 **        the parent query:
   97209 **
   97210 **          * is not itself part of a compound select,
   97211 **          * is not an aggregate or DISTINCT query, and
   97212 **          * is not a join
   97213 **
   97214 **        The parent and sub-query may contain WHERE clauses. Subject to
   97215 **        rules (11), (13) and (14), they may also contain ORDER BY,
   97216 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
   97217 **        operator other than UNION ALL because all the other compound
   97218 **        operators have an implied DISTINCT which is disallowed by
   97219 **        restriction (4).
   97220 **
   97221 **  (18)  If the sub-query is a compound select, then all terms of the
   97222 **        ORDER by clause of the parent must be simple references to
   97223 **        columns of the sub-query.
   97224 **
   97225 **  (19)  The subquery does not use LIMIT or the outer query does not
   97226 **        have a WHERE clause.
   97227 **
   97228 **  (20)  If the sub-query is a compound select, then it must not use
   97229 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   97230 **        somewhat by saying that the terms of the ORDER BY clause must
   97231 **        appear as unmodified result columns in the outer query.  But we
   97232 **        have other optimizations in mind to deal with that case.
   97233 **
   97234 **  (21)  The subquery does not use LIMIT or the outer query is not
   97235 **        DISTINCT.  (See ticket [752e1646fc]).
   97236 **
   97237 ** In this routine, the "p" parameter is a pointer to the outer query.
   97238 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   97239 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   97240 **
   97241 ** If flattening is not attempted, this routine is a no-op and returns 0.
   97242 ** If flattening is attempted this routine returns 1.
   97243 **
   97244 ** All of the expression analysis must occur on both the outer query and
   97245 ** the subquery before this routine runs.
   97246 */
   97247 static int flattenSubquery(
   97248   Parse *pParse,       /* Parsing context */
   97249   Select *p,           /* The parent or outer SELECT statement */
   97250   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   97251   int isAgg,           /* True if outer SELECT uses aggregate functions */
   97252   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   97253 ){
   97254   const char *zSavedAuthContext = pParse->zAuthContext;
   97255   Select *pParent;
   97256   Select *pSub;       /* The inner query or "subquery" */
   97257   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   97258   SrcList *pSrc;      /* The FROM clause of the outer query */
   97259   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   97260   ExprList *pList;    /* The result set of the outer query */
   97261   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   97262   int i;              /* Loop counter */
   97263   Expr *pWhere;                    /* The WHERE clause */
   97264   struct SrcList_item *pSubitem;   /* The subquery */
   97265   sqlite3 *db = pParse->db;
   97266 
   97267   /* Check to see if flattening is permitted.  Return 0 if not.
   97268   */
   97269   assert( p!=0 );
   97270   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   97271   if( db->flags & SQLITE_QueryFlattener ) return 0;
   97272   pSrc = p->pSrc;
   97273   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   97274   pSubitem = &pSrc->a[iFrom];
   97275   iParent = pSubitem->iCursor;
   97276   pSub = pSubitem->pSelect;
   97277   assert( pSub!=0 );
   97278   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   97279   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   97280   pSubSrc = pSub->pSrc;
   97281   assert( pSubSrc );
   97282   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   97283   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   97284   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   97285   ** became arbitrary expressions, we were forced to add restrictions (13)
   97286   ** and (14). */
   97287   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   97288   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   97289   if( p->pRightmost && pSub->pLimit ){
   97290     return 0;                                            /* Restriction (15) */
   97291   }
   97292   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   97293   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
   97294   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   97295      return 0;         /* Restrictions (8)(9) */
   97296   }
   97297   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   97298      return 0;         /* Restriction (6)  */
   97299   }
   97300   if( p->pOrderBy && pSub->pOrderBy ){
   97301      return 0;                                           /* Restriction (11) */
   97302   }
   97303   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   97304   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   97305   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
   97306      return 0;         /* Restriction (21) */
   97307   }
   97308 
   97309   /* OBSOLETE COMMENT 1:
   97310   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   97311   ** not used as the right operand of an outer join.  Examples of why this
   97312   ** is not allowed:
   97313   **
   97314   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   97315   **
   97316   ** If we flatten the above, we would get
   97317   **
   97318   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   97319   **
   97320   ** which is not at all the same thing.
   97321   **
   97322   ** OBSOLETE COMMENT 2:
   97323   ** Restriction 12:  If the subquery is the right operand of a left outer
   97324   ** join, make sure the subquery has no WHERE clause.
   97325   ** An examples of why this is not allowed:
   97326   **
   97327   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   97328   **
   97329   ** If we flatten the above, we would get
   97330   **
   97331   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   97332   **
   97333   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   97334   ** effectively converts the OUTER JOIN into an INNER JOIN.
   97335   **
   97336   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   97337   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   97338   ** is fraught with danger.  Best to avoid the whole thing.  If the
   97339   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   97340   */
   97341   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   97342     return 0;
   97343   }
   97344 
   97345   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   97346   ** use only the UNION ALL operator. And none of the simple select queries
   97347   ** that make up the compound SELECT are allowed to be aggregate or distinct
   97348   ** queries.
   97349   */
   97350   if( pSub->pPrior ){
   97351     if( pSub->pOrderBy ){
   97352       return 0;  /* Restriction 20 */
   97353     }
   97354     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   97355       return 0;
   97356     }
   97357     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   97358       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   97359       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   97360       assert( pSub->pSrc!=0 );
   97361       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   97362        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   97363        || pSub1->pSrc->nSrc<1
   97364       ){
   97365         return 0;
   97366       }
   97367       testcase( pSub1->pSrc->nSrc>1 );
   97368     }
   97369 
   97370     /* Restriction 18. */
   97371     if( p->pOrderBy ){
   97372       int ii;
   97373       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   97374         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
   97375       }
   97376     }
   97377   }
   97378 
   97379   /***** If we reach this point, flattening is permitted. *****/
   97380 
   97381   /* Authorize the subquery */
   97382   pParse->zAuthContext = pSubitem->zName;
   97383   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   97384   pParse->zAuthContext = zSavedAuthContext;
   97385 
   97386   /* If the sub-query is a compound SELECT statement, then (by restrictions
   97387   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   97388   ** be of the form:
   97389   **
   97390   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   97391   **
   97392   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   97393   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   97394   ** OFFSET clauses and joins them to the left-hand-side of the original
   97395   ** using UNION ALL operators. In this case N is the number of simple
   97396   ** select statements in the compound sub-query.
   97397   **
   97398   ** Example:
   97399   **
   97400   **     SELECT a+1 FROM (
   97401   **        SELECT x FROM tab
   97402   **        UNION ALL
   97403   **        SELECT y FROM tab
   97404   **        UNION ALL
   97405   **        SELECT abs(z*2) FROM tab2
   97406   **     ) WHERE a!=5 ORDER BY 1
   97407   **
   97408   ** Transformed into:
   97409   **
   97410   **     SELECT x+1 FROM tab WHERE x+1!=5
   97411   **     UNION ALL
   97412   **     SELECT y+1 FROM tab WHERE y+1!=5
   97413   **     UNION ALL
   97414   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   97415   **     ORDER BY 1
   97416   **
   97417   ** We call this the "compound-subquery flattening".
   97418   */
   97419   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   97420     Select *pNew;
   97421     ExprList *pOrderBy = p->pOrderBy;
   97422     Expr *pLimit = p->pLimit;
   97423     Select *pPrior = p->pPrior;
   97424     p->pOrderBy = 0;
   97425     p->pSrc = 0;
   97426     p->pPrior = 0;
   97427     p->pLimit = 0;
   97428     pNew = sqlite3SelectDup(db, p, 0);
   97429     p->pLimit = pLimit;
   97430     p->pOrderBy = pOrderBy;
   97431     p->pSrc = pSrc;
   97432     p->op = TK_ALL;
   97433     p->pRightmost = 0;
   97434     if( pNew==0 ){
   97435       pNew = pPrior;
   97436     }else{
   97437       pNew->pPrior = pPrior;
   97438       pNew->pRightmost = 0;
   97439     }
   97440     p->pPrior = pNew;
   97441     if( db->mallocFailed ) return 1;
   97442   }
   97443 
   97444   /* Begin flattening the iFrom-th entry of the FROM clause
   97445   ** in the outer query.
   97446   */
   97447   pSub = pSub1 = pSubitem->pSelect;
   97448 
   97449   /* Delete the transient table structure associated with the
   97450   ** subquery
   97451   */
   97452   sqlite3DbFree(db, pSubitem->zDatabase);
   97453   sqlite3DbFree(db, pSubitem->zName);
   97454   sqlite3DbFree(db, pSubitem->zAlias);
   97455   pSubitem->zDatabase = 0;
   97456   pSubitem->zName = 0;
   97457   pSubitem->zAlias = 0;
   97458   pSubitem->pSelect = 0;
   97459 
   97460   /* Defer deleting the Table object associated with the
   97461   ** subquery until code generation is
   97462   ** complete, since there may still exist Expr.pTab entries that
   97463   ** refer to the subquery even after flattening.  Ticket #3346.
   97464   **
   97465   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   97466   */
   97467   if( ALWAYS(pSubitem->pTab!=0) ){
   97468     Table *pTabToDel = pSubitem->pTab;
   97469     if( pTabToDel->nRef==1 ){
   97470       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   97471       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   97472       pToplevel->pZombieTab = pTabToDel;
   97473     }else{
   97474       pTabToDel->nRef--;
   97475     }
   97476     pSubitem->pTab = 0;
   97477   }
   97478 
   97479   /* The following loop runs once for each term in a compound-subquery
   97480   ** flattening (as described above).  If we are doing a different kind
   97481   ** of flattening - a flattening other than a compound-subquery flattening -
   97482   ** then this loop only runs once.
   97483   **
   97484   ** This loop moves all of the FROM elements of the subquery into the
   97485   ** the FROM clause of the outer query.  Before doing this, remember
   97486   ** the cursor number for the original outer query FROM element in
   97487   ** iParent.  The iParent cursor will never be used.  Subsequent code
   97488   ** will scan expressions looking for iParent references and replace
   97489   ** those references with expressions that resolve to the subquery FROM
   97490   ** elements we are now copying in.
   97491   */
   97492   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   97493     int nSubSrc;
   97494     u8 jointype = 0;
   97495     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   97496     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   97497     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   97498 
   97499     if( pSrc ){
   97500       assert( pParent==p );  /* First time through the loop */
   97501       jointype = pSubitem->jointype;
   97502     }else{
   97503       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   97504       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   97505       if( pSrc==0 ){
   97506         assert( db->mallocFailed );
   97507         break;
   97508       }
   97509     }
   97510 
   97511     /* The subquery uses a single slot of the FROM clause of the outer
   97512     ** query.  If the subquery has more than one element in its FROM clause,
   97513     ** then expand the outer query to make space for it to hold all elements
   97514     ** of the subquery.
   97515     **
   97516     ** Example:
   97517     **
   97518     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   97519     **
   97520     ** The outer query has 3 slots in its FROM clause.  One slot of the
   97521     ** outer query (the middle slot) is used by the subquery.  The next
   97522     ** block of code will expand the out query to 4 slots.  The middle
   97523     ** slot is expanded to two slots in order to make space for the
   97524     ** two elements in the FROM clause of the subquery.
   97525     */
   97526     if( nSubSrc>1 ){
   97527       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   97528       if( db->mallocFailed ){
   97529         break;
   97530       }
   97531     }
   97532 
   97533     /* Transfer the FROM clause terms from the subquery into the
   97534     ** outer query.
   97535     */
   97536     for(i=0; i<nSubSrc; i++){
   97537       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   97538       pSrc->a[i+iFrom] = pSubSrc->a[i];
   97539       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   97540     }
   97541     pSrc->a[iFrom].jointype = jointype;
   97542 
   97543     /* Now begin substituting subquery result set expressions for
   97544     ** references to the iParent in the outer query.
   97545     **
   97546     ** Example:
   97547     **
   97548     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   97549     **   \                     \_____________ subquery __________/          /
   97550     **    \_____________________ outer query ______________________________/
   97551     **
   97552     ** We look at every expression in the outer query and every place we see
   97553     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   97554     */
   97555     pList = pParent->pEList;
   97556     for(i=0; i<pList->nExpr; i++){
   97557       if( pList->a[i].zName==0 ){
   97558         const char *zSpan = pList->a[i].zSpan;
   97559         if( ALWAYS(zSpan) ){
   97560           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
   97561         }
   97562       }
   97563     }
   97564     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   97565     if( isAgg ){
   97566       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   97567       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   97568     }
   97569     if( pSub->pOrderBy ){
   97570       assert( pParent->pOrderBy==0 );
   97571       pParent->pOrderBy = pSub->pOrderBy;
   97572       pSub->pOrderBy = 0;
   97573     }else if( pParent->pOrderBy ){
   97574       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   97575     }
   97576     if( pSub->pWhere ){
   97577       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   97578     }else{
   97579       pWhere = 0;
   97580     }
   97581     if( subqueryIsAgg ){
   97582       assert( pParent->pHaving==0 );
   97583       pParent->pHaving = pParent->pWhere;
   97584       pParent->pWhere = pWhere;
   97585       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   97586       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   97587                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   97588       assert( pParent->pGroupBy==0 );
   97589       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   97590     }else{
   97591       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   97592       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   97593     }
   97594 
   97595     /* The flattened query is distinct if either the inner or the
   97596     ** outer query is distinct.
   97597     */
   97598     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   97599 
   97600     /*
   97601     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   97602     **
   97603     ** One is tempted to try to add a and b to combine the limits.  But this
   97604     ** does not work if either limit is negative.
   97605     */
   97606     if( pSub->pLimit ){
   97607       pParent->pLimit = pSub->pLimit;
   97608       pSub->pLimit = 0;
   97609     }
   97610   }
   97611 
   97612   /* Finially, delete what is left of the subquery and return
   97613   ** success.
   97614   */
   97615   sqlite3SelectDelete(db, pSub1);
   97616 
   97617   return 1;
   97618 }
   97619 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   97620 
   97621 /*
   97622 ** Analyze the SELECT statement passed as an argument to see if it
   97623 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
   97624 ** it is, or 0 otherwise. At present, a query is considered to be
   97625 ** a min()/max() query if:
   97626 **
   97627 **   1. There is a single object in the FROM clause.
   97628 **
   97629 **   2. There is a single expression in the result set, and it is
   97630 **      either min(x) or max(x), where x is a column reference.
   97631 */
   97632 static u8 minMaxQuery(Select *p){
   97633   Expr *pExpr;
   97634   ExprList *pEList = p->pEList;
   97635 
   97636   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
   97637   pExpr = pEList->a[0].pExpr;
   97638   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   97639   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
   97640   pEList = pExpr->x.pList;
   97641   if( pEList==0 || pEList->nExpr!=1 ) return 0;
   97642   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
   97643   assert( !ExprHasProperty(pExpr, EP_IntValue) );
   97644   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
   97645     return WHERE_ORDERBY_MIN;
   97646   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
   97647     return WHERE_ORDERBY_MAX;
   97648   }
   97649   return WHERE_ORDERBY_NORMAL;
   97650 }
   97651 
   97652 /*
   97653 ** The select statement passed as the first argument is an aggregate query.
   97654 ** The second argment is the associated aggregate-info object. This
   97655 ** function tests if the SELECT is of the form:
   97656 **
   97657 **   SELECT count(*) FROM <tbl>
   97658 **
   97659 ** where table is a database table, not a sub-select or view. If the query
   97660 ** does match this pattern, then a pointer to the Table object representing
   97661 ** <tbl> is returned. Otherwise, 0 is returned.
   97662 */
   97663 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   97664   Table *pTab;
   97665   Expr *pExpr;
   97666 
   97667   assert( !p->pGroupBy );
   97668 
   97669   if( p->pWhere || p->pEList->nExpr!=1
   97670    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   97671   ){
   97672     return 0;
   97673   }
   97674   pTab = p->pSrc->a[0].pTab;
   97675   pExpr = p->pEList->a[0].pExpr;
   97676   assert( pTab && !pTab->pSelect && pExpr );
   97677 
   97678   if( IsVirtual(pTab) ) return 0;
   97679   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   97680   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
   97681   if( pExpr->flags&EP_Distinct ) return 0;
   97682 
   97683   return pTab;
   97684 }
   97685 
   97686 /*
   97687 ** If the source-list item passed as an argument was augmented with an
   97688 ** INDEXED BY clause, then try to locate the specified index. If there
   97689 ** was such a clause and the named index cannot be found, return
   97690 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   97691 ** pFrom->pIndex and return SQLITE_OK.
   97692 */
   97693 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   97694   if( pFrom->pTab && pFrom->zIndex ){
   97695     Table *pTab = pFrom->pTab;
   97696     char *zIndex = pFrom->zIndex;
   97697     Index *pIdx;
   97698     for(pIdx=pTab->pIndex;
   97699         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   97700         pIdx=pIdx->pNext
   97701     );
   97702     if( !pIdx ){
   97703       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   97704       pParse->checkSchema = 1;
   97705       return SQLITE_ERROR;
   97706     }
   97707     pFrom->pIndex = pIdx;
   97708   }
   97709   return SQLITE_OK;
   97710 }
   97711 
   97712 /*
   97713 ** This routine is a Walker callback for "expanding" a SELECT statement.
   97714 ** "Expanding" means to do the following:
   97715 **
   97716 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   97717 **         element of the FROM clause.
   97718 **
   97719 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   97720 **         defines FROM clause.  When views appear in the FROM clause,
   97721 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   97722 **         that implements the view.  A copy is made of the view's SELECT
   97723 **         statement so that we can freely modify or delete that statement
   97724 **         without worrying about messing up the presistent representation
   97725 **         of the view.
   97726 **
   97727 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   97728 **         on joins and the ON and USING clause of joins.
   97729 **
   97730 **    (4)  Scan the list of columns in the result set (pEList) looking
   97731 **         for instances of the "*" operator or the TABLE.* operator.
   97732 **         If found, expand each "*" to be every column in every table
   97733 **         and TABLE.* to be every column in TABLE.
   97734 **
   97735 */
   97736 static int selectExpander(Walker *pWalker, Select *p){
   97737   Parse *pParse = pWalker->pParse;
   97738   int i, j, k;
   97739   SrcList *pTabList;
   97740   ExprList *pEList;
   97741   struct SrcList_item *pFrom;
   97742   sqlite3 *db = pParse->db;
   97743 
   97744   if( db->mallocFailed  ){
   97745     return WRC_Abort;
   97746   }
   97747   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
   97748     return WRC_Prune;
   97749   }
   97750   p->selFlags |= SF_Expanded;
   97751   pTabList = p->pSrc;
   97752   pEList = p->pEList;
   97753 
   97754   /* Make sure cursor numbers have been assigned to all entries in
   97755   ** the FROM clause of the SELECT statement.
   97756   */
   97757   sqlite3SrcListAssignCursors(pParse, pTabList);
   97758 
   97759   /* Look up every table named in the FROM clause of the select.  If
   97760   ** an entry of the FROM clause is a subquery instead of a table or view,
   97761   ** then create a transient table structure to describe the subquery.
   97762   */
   97763   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   97764     Table *pTab;
   97765     if( pFrom->pTab!=0 ){
   97766       /* This statement has already been prepared.  There is no need
   97767       ** to go further. */
   97768       assert( i==0 );
   97769       return WRC_Prune;
   97770     }
   97771     if( pFrom->zName==0 ){
   97772 #ifndef SQLITE_OMIT_SUBQUERY
   97773       Select *pSel = pFrom->pSelect;
   97774       /* A sub-query in the FROM clause of a SELECT */
   97775       assert( pSel!=0 );
   97776       assert( pFrom->pTab==0 );
   97777       sqlite3WalkSelect(pWalker, pSel);
   97778       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   97779       if( pTab==0 ) return WRC_Abort;
   97780       pTab->nRef = 1;
   97781       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
   97782       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   97783       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   97784       pTab->iPKey = -1;
   97785       pTab->nRowEst = 1000000;
   97786       pTab->tabFlags |= TF_Ephemeral;
   97787 #endif
   97788     }else{
   97789       /* An ordinary table or view name in the FROM clause */
   97790       assert( pFrom->pTab==0 );
   97791       pFrom->pTab = pTab =
   97792         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
   97793       if( pTab==0 ) return WRC_Abort;
   97794       pTab->nRef++;
   97795 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   97796       if( pTab->pSelect || IsVirtual(pTab) ){
   97797         /* We reach here if the named table is a really a view */
   97798         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   97799         assert( pFrom->pSelect==0 );
   97800         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   97801         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   97802       }
   97803 #endif
   97804     }
   97805 
   97806     /* Locate the index named by the INDEXED BY clause, if any. */
   97807     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   97808       return WRC_Abort;
   97809     }
   97810   }
   97811 
   97812   /* Process NATURAL keywords, and ON and USING clauses of joins.
   97813   */
   97814   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   97815     return WRC_Abort;
   97816   }
   97817 
   97818   /* For every "*" that occurs in the column list, insert the names of
   97819   ** all columns in all tables.  And for every TABLE.* insert the names
   97820   ** of all columns in TABLE.  The parser inserted a special expression
   97821   ** with the TK_ALL operator for each "*" that it found in the column list.
   97822   ** The following code just has to locate the TK_ALL expressions and expand
   97823   ** each one to the list of all columns in all tables.
   97824   **
   97825   ** The first loop just checks to see if there are any "*" operators
   97826   ** that need expanding.
   97827   */
   97828   for(k=0; k<pEList->nExpr; k++){
   97829     Expr *pE = pEList->a[k].pExpr;
   97830     if( pE->op==TK_ALL ) break;
   97831     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   97832     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   97833     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   97834   }
   97835   if( k<pEList->nExpr ){
   97836     /*
   97837     ** If we get here it means the result set contains one or more "*"
   97838     ** operators that need to be expanded.  Loop through each expression
   97839     ** in the result set and expand them one by one.
   97840     */
   97841     struct ExprList_item *a = pEList->a;
   97842     ExprList *pNew = 0;
   97843     int flags = pParse->db->flags;
   97844     int longNames = (flags & SQLITE_FullColNames)!=0
   97845                       && (flags & SQLITE_ShortColNames)==0;
   97846 
   97847     for(k=0; k<pEList->nExpr; k++){
   97848       Expr *pE = a[k].pExpr;
   97849       assert( pE->op!=TK_DOT || pE->pRight!=0 );
   97850       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
   97851         /* This particular expression does not need to be expanded.
   97852         */
   97853         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   97854         if( pNew ){
   97855           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   97856           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   97857           a[k].zName = 0;
   97858           a[k].zSpan = 0;
   97859         }
   97860         a[k].pExpr = 0;
   97861       }else{
   97862         /* This expression is a "*" or a "TABLE.*" and needs to be
   97863         ** expanded. */
   97864         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   97865         char *zTName;            /* text of name of TABLE */
   97866         if( pE->op==TK_DOT ){
   97867           assert( pE->pLeft!=0 );
   97868           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   97869           zTName = pE->pLeft->u.zToken;
   97870         }else{
   97871           zTName = 0;
   97872         }
   97873         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   97874           Table *pTab = pFrom->pTab;
   97875           char *zTabName = pFrom->zAlias;
   97876           if( zTabName==0 ){
   97877             zTabName = pTab->zName;
   97878           }
   97879           if( db->mallocFailed ) break;
   97880           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   97881             continue;
   97882           }
   97883           tableSeen = 1;
   97884           for(j=0; j<pTab->nCol; j++){
   97885             Expr *pExpr, *pRight;
   97886             char *zName = pTab->aCol[j].zName;
   97887             char *zColname;  /* The computed column name */
   97888             char *zToFree;   /* Malloced string that needs to be freed */
   97889             Token sColname;  /* Computed column name as a token */
   97890 
   97891             /* If a column is marked as 'hidden' (currently only possible
   97892             ** for virtual tables), do not include it in the expanded
   97893             ** result-set list.
   97894             */
   97895             if( IsHiddenColumn(&pTab->aCol[j]) ){
   97896               assert(IsVirtual(pTab));
   97897               continue;
   97898             }
   97899 
   97900             if( i>0 && zTName==0 ){
   97901               if( (pFrom->jointype & JT_NATURAL)!=0
   97902                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   97903               ){
   97904                 /* In a NATURAL join, omit the join columns from the
   97905                 ** table to the right of the join */
   97906                 continue;
   97907               }
   97908               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   97909                 /* In a join with a USING clause, omit columns in the
   97910                 ** using clause from the table on the right. */
   97911                 continue;
   97912               }
   97913             }
   97914             pRight = sqlite3Expr(db, TK_ID, zName);
   97915             zColname = zName;
   97916             zToFree = 0;
   97917             if( longNames || pTabList->nSrc>1 ){
   97918               Expr *pLeft;
   97919               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   97920               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   97921               if( longNames ){
   97922                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   97923                 zToFree = zColname;
   97924               }
   97925             }else{
   97926               pExpr = pRight;
   97927             }
   97928             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   97929             sColname.z = zColname;
   97930             sColname.n = sqlite3Strlen30(zColname);
   97931             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   97932             sqlite3DbFree(db, zToFree);
   97933           }
   97934         }
   97935         if( !tableSeen ){
   97936           if( zTName ){
   97937             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   97938           }else{
   97939             sqlite3ErrorMsg(pParse, "no tables specified");
   97940           }
   97941         }
   97942       }
   97943     }
   97944     sqlite3ExprListDelete(db, pEList);
   97945     p->pEList = pNew;
   97946   }
   97947 #if SQLITE_MAX_COLUMN
   97948   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   97949     sqlite3ErrorMsg(pParse, "too many columns in result set");
   97950   }
   97951 #endif
   97952   return WRC_Continue;
   97953 }
   97954 
   97955 /*
   97956 ** No-op routine for the parse-tree walker.
   97957 **
   97958 ** When this routine is the Walker.xExprCallback then expression trees
   97959 ** are walked without any actions being taken at each node.  Presumably,
   97960 ** when this routine is used for Walker.xExprCallback then
   97961 ** Walker.xSelectCallback is set to do something useful for every
   97962 ** subquery in the parser tree.
   97963 */
   97964 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   97965   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   97966   return WRC_Continue;
   97967 }
   97968 
   97969 /*
   97970 ** This routine "expands" a SELECT statement and all of its subqueries.
   97971 ** For additional information on what it means to "expand" a SELECT
   97972 ** statement, see the comment on the selectExpand worker callback above.
   97973 **
   97974 ** Expanding a SELECT statement is the first step in processing a
   97975 ** SELECT statement.  The SELECT statement must be expanded before
   97976 ** name resolution is performed.
   97977 **
   97978 ** If anything goes wrong, an error message is written into pParse.
   97979 ** The calling function can detect the problem by looking at pParse->nErr
   97980 ** and/or pParse->db->mallocFailed.
   97981 */
   97982 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   97983   Walker w;
   97984   w.xSelectCallback = selectExpander;
   97985   w.xExprCallback = exprWalkNoop;
   97986   w.pParse = pParse;
   97987   sqlite3WalkSelect(&w, pSelect);
   97988 }
   97989 
   97990 
   97991 #ifndef SQLITE_OMIT_SUBQUERY
   97992 /*
   97993 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   97994 ** interface.
   97995 **
   97996 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   97997 ** information to the Table structure that represents the result set
   97998 ** of that subquery.
   97999 **
   98000 ** The Table structure that represents the result set was constructed
   98001 ** by selectExpander() but the type and collation information was omitted
   98002 ** at that point because identifiers had not yet been resolved.  This
   98003 ** routine is called after identifier resolution.
   98004 */
   98005 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   98006   Parse *pParse;
   98007   int i;
   98008   SrcList *pTabList;
   98009   struct SrcList_item *pFrom;
   98010 
   98011   assert( p->selFlags & SF_Resolved );
   98012   if( (p->selFlags & SF_HasTypeInfo)==0 ){
   98013     p->selFlags |= SF_HasTypeInfo;
   98014     pParse = pWalker->pParse;
   98015     pTabList = p->pSrc;
   98016     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   98017       Table *pTab = pFrom->pTab;
   98018       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   98019         /* A sub-query in the FROM clause of a SELECT */
   98020         Select *pSel = pFrom->pSelect;
   98021         assert( pSel );
   98022         while( pSel->pPrior ) pSel = pSel->pPrior;
   98023         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
   98024       }
   98025     }
   98026   }
   98027   return WRC_Continue;
   98028 }
   98029 #endif
   98030 
   98031 
   98032 /*
   98033 ** This routine adds datatype and collating sequence information to
   98034 ** the Table structures of all FROM-clause subqueries in a
   98035 ** SELECT statement.
   98036 **
   98037 ** Use this routine after name resolution.
   98038 */
   98039 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   98040 #ifndef SQLITE_OMIT_SUBQUERY
   98041   Walker w;
   98042   w.xSelectCallback = selectAddSubqueryTypeInfo;
   98043   w.xExprCallback = exprWalkNoop;
   98044   w.pParse = pParse;
   98045   sqlite3WalkSelect(&w, pSelect);
   98046 #endif
   98047 }
   98048 
   98049 
   98050 /*
   98051 ** This routine sets of a SELECT statement for processing.  The
   98052 ** following is accomplished:
   98053 **
   98054 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   98055 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   98056 **     *  ON and USING clauses are shifted into WHERE statements
   98057 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   98058 **     *  Identifiers in expression are matched to tables.
   98059 **
   98060 ** This routine acts recursively on all subqueries within the SELECT.
   98061 */
   98062 SQLITE_PRIVATE void sqlite3SelectPrep(
   98063   Parse *pParse,         /* The parser context */
   98064   Select *p,             /* The SELECT statement being coded. */
   98065   NameContext *pOuterNC  /* Name context for container */
   98066 ){
   98067   sqlite3 *db;
   98068   if( NEVER(p==0) ) return;
   98069   db = pParse->db;
   98070   if( p->selFlags & SF_HasTypeInfo ) return;
   98071   sqlite3SelectExpand(pParse, p);
   98072   if( pParse->nErr || db->mallocFailed ) return;
   98073   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   98074   if( pParse->nErr || db->mallocFailed ) return;
   98075   sqlite3SelectAddTypeInfo(pParse, p);
   98076 }
   98077 
   98078 /*
   98079 ** Reset the aggregate accumulator.
   98080 **
   98081 ** The aggregate accumulator is a set of memory cells that hold
   98082 ** intermediate results while calculating an aggregate.  This
   98083 ** routine simply stores NULLs in all of those memory cells.
   98084 */
   98085 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   98086   Vdbe *v = pParse->pVdbe;
   98087   int i;
   98088   struct AggInfo_func *pFunc;
   98089   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
   98090     return;
   98091   }
   98092   for(i=0; i<pAggInfo->nColumn; i++){
   98093     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
   98094   }
   98095   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   98096     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
   98097     if( pFunc->iDistinct>=0 ){
   98098       Expr *pE = pFunc->pExpr;
   98099       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   98100       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   98101         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   98102            "argument");
   98103         pFunc->iDistinct = -1;
   98104       }else{
   98105         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
   98106         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   98107                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98108       }
   98109     }
   98110   }
   98111 }
   98112 
   98113 /*
   98114 ** Invoke the OP_AggFinalize opcode for every aggregate function
   98115 ** in the AggInfo structure.
   98116 */
   98117 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   98118   Vdbe *v = pParse->pVdbe;
   98119   int i;
   98120   struct AggInfo_func *pF;
   98121   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   98122     ExprList *pList = pF->pExpr->x.pList;
   98123     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   98124     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   98125                       (void*)pF->pFunc, P4_FUNCDEF);
   98126   }
   98127 }
   98128 
   98129 /*
   98130 ** Update the accumulator memory cells for an aggregate based on
   98131 ** the current cursor position.
   98132 */
   98133 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   98134   Vdbe *v = pParse->pVdbe;
   98135   int i;
   98136   int regHit = 0;
   98137   int addrHitTest = 0;
   98138   struct AggInfo_func *pF;
   98139   struct AggInfo_col *pC;
   98140 
   98141   pAggInfo->directMode = 1;
   98142   sqlite3ExprCacheClear(pParse);
   98143   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   98144     int nArg;
   98145     int addrNext = 0;
   98146     int regAgg;
   98147     ExprList *pList = pF->pExpr->x.pList;
   98148     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   98149     if( pList ){
   98150       nArg = pList->nExpr;
   98151       regAgg = sqlite3GetTempRange(pParse, nArg);
   98152       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
   98153     }else{
   98154       nArg = 0;
   98155       regAgg = 0;
   98156     }
   98157     if( pF->iDistinct>=0 ){
   98158       addrNext = sqlite3VdbeMakeLabel(v);
   98159       assert( nArg==1 );
   98160       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   98161     }
   98162     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   98163       CollSeq *pColl = 0;
   98164       struct ExprList_item *pItem;
   98165       int j;
   98166       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   98167       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   98168         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   98169       }
   98170       if( !pColl ){
   98171         pColl = pParse->db->pDfltColl;
   98172       }
   98173       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
   98174       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
   98175     }
   98176     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   98177                       (void*)pF->pFunc, P4_FUNCDEF);
   98178     sqlite3VdbeChangeP5(v, (u8)nArg);
   98179     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   98180     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   98181     if( addrNext ){
   98182       sqlite3VdbeResolveLabel(v, addrNext);
   98183       sqlite3ExprCacheClear(pParse);
   98184     }
   98185   }
   98186 
   98187   /* Before populating the accumulator registers, clear the column cache.
   98188   ** Otherwise, if any of the required column values are already present
   98189   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   98190   ** to pC->iMem. But by the time the value is used, the original register
   98191   ** may have been used, invalidating the underlying buffer holding the
   98192   ** text or blob value. See ticket [883034dcb5].
   98193   **
   98194   ** Another solution would be to change the OP_SCopy used to copy cached
   98195   ** values to an OP_Copy.
   98196   */
   98197   if( regHit ){
   98198     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
   98199   }
   98200   sqlite3ExprCacheClear(pParse);
   98201   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   98202     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   98203   }
   98204   pAggInfo->directMode = 0;
   98205   sqlite3ExprCacheClear(pParse);
   98206   if( addrHitTest ){
   98207     sqlite3VdbeJumpHere(v, addrHitTest);
   98208   }
   98209 }
   98210 
   98211 /*
   98212 ** Add a single OP_Explain instruction to the VDBE to explain a simple
   98213 ** count(*) query ("SELECT count(*) FROM pTab").
   98214 */
   98215 #ifndef SQLITE_OMIT_EXPLAIN
   98216 static void explainSimpleCount(
   98217   Parse *pParse,                  /* Parse context */
   98218   Table *pTab,                    /* Table being queried */
   98219   Index *pIdx                     /* Index used to optimize scan, or NULL */
   98220 ){
   98221   if( pParse->explain==2 ){
   98222     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
   98223         pTab->zName,
   98224         pIdx ? "USING COVERING INDEX " : "",
   98225         pIdx ? pIdx->zName : "",
   98226         pTab->nRowEst
   98227     );
   98228     sqlite3VdbeAddOp4(
   98229         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
   98230     );
   98231   }
   98232 }
   98233 #else
   98234 # define explainSimpleCount(a,b,c)
   98235 #endif
   98236 
   98237 /*
   98238 ** Generate code for the SELECT statement given in the p argument.
   98239 **
   98240 ** The results are distributed in various ways depending on the
   98241 ** contents of the SelectDest structure pointed to by argument pDest
   98242 ** as follows:
   98243 **
   98244 **     pDest->eDest    Result
   98245 **     ------------    -------------------------------------------
   98246 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   98247 **                     opcode) for each row in the result set.
   98248 **
   98249 **     SRT_Mem         Only valid if the result is a single column.
   98250 **                     Store the first column of the first result row
   98251 **                     in register pDest->iParm then abandon the rest
   98252 **                     of the query.  This destination implies "LIMIT 1".
   98253 **
   98254 **     SRT_Set         The result must be a single column.  Store each
   98255 **                     row of result as the key in table pDest->iParm.
   98256 **                     Apply the affinity pDest->affinity before storing
   98257 **                     results.  Used to implement "IN (SELECT ...)".
   98258 **
   98259 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
   98260 **
   98261 **     SRT_Except      Remove results from the temporary table pDest->iParm.
   98262 **
   98263 **     SRT_Table       Store results in temporary table pDest->iParm.
   98264 **                     This is like SRT_EphemTab except that the table
   98265 **                     is assumed to already be open.
   98266 **
   98267 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
   98268 **                     the result there. The cursor is left open after
   98269 **                     returning.  This is like SRT_Table except that
   98270 **                     this destination uses OP_OpenEphemeral to create
   98271 **                     the table first.
   98272 **
   98273 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   98274 **                     results each time it is invoked.  The entry point
   98275 **                     of the co-routine is stored in register pDest->iParm.
   98276 **
   98277 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
   98278 **                     set is not empty.
   98279 **
   98280 **     SRT_Discard     Throw the results away.  This is used by SELECT
   98281 **                     statements within triggers whose only purpose is
   98282 **                     the side-effects of functions.
   98283 **
   98284 ** This routine returns the number of errors.  If any errors are
   98285 ** encountered, then an appropriate error message is left in
   98286 ** pParse->zErrMsg.
   98287 **
   98288 ** This routine does NOT free the Select structure passed in.  The
   98289 ** calling function needs to do that.
   98290 */
   98291 SQLITE_PRIVATE int sqlite3Select(
   98292   Parse *pParse,         /* The parser context */
   98293   Select *p,             /* The SELECT statement being coded. */
   98294   SelectDest *pDest      /* What to do with the query results */
   98295 ){
   98296   int i, j;              /* Loop counters */
   98297   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   98298   Vdbe *v;               /* The virtual machine under construction */
   98299   int isAgg;             /* True for select lists like "count(*)" */
   98300   ExprList *pEList;      /* List of columns to extract. */
   98301   SrcList *pTabList;     /* List of tables to select from */
   98302   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   98303   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
   98304   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   98305   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   98306   int isDistinct;        /* True if the DISTINCT keyword is present */
   98307   int distinct;          /* Table to use for the distinct set */
   98308   int rc = 1;            /* Value to return from this function */
   98309   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
   98310   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
   98311   AggInfo sAggInfo;      /* Information used by aggregate queries */
   98312   int iEnd;              /* Address of the end of the query */
   98313   sqlite3 *db;           /* The database connection */
   98314 
   98315 #ifndef SQLITE_OMIT_EXPLAIN
   98316   int iRestoreSelectId = pParse->iSelectId;
   98317   pParse->iSelectId = pParse->iNextSelectId++;
   98318 #endif
   98319 
   98320   db = pParse->db;
   98321   if( p==0 || db->mallocFailed || pParse->nErr ){
   98322     return 1;
   98323   }
   98324   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   98325   memset(&sAggInfo, 0, sizeof(sAggInfo));
   98326 
   98327   if( IgnorableOrderby(pDest) ){
   98328     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   98329            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
   98330     /* If ORDER BY makes no difference in the output then neither does
   98331     ** DISTINCT so it can be removed too. */
   98332     sqlite3ExprListDelete(db, p->pOrderBy);
   98333     p->pOrderBy = 0;
   98334     p->selFlags &= ~SF_Distinct;
   98335   }
   98336   sqlite3SelectPrep(pParse, p, 0);
   98337   pOrderBy = p->pOrderBy;
   98338   pTabList = p->pSrc;
   98339   pEList = p->pEList;
   98340   if( pParse->nErr || db->mallocFailed ){
   98341     goto select_end;
   98342   }
   98343   isAgg = (p->selFlags & SF_Aggregate)!=0;
   98344   assert( pEList!=0 );
   98345 
   98346   /* Begin generating code.
   98347   */
   98348   v = sqlite3GetVdbe(pParse);
   98349   if( v==0 ) goto select_end;
   98350 
   98351   /* If writing to memory or generating a set
   98352   ** only a single column may be output.
   98353   */
   98354 #ifndef SQLITE_OMIT_SUBQUERY
   98355   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   98356     goto select_end;
   98357   }
   98358 #endif
   98359 
   98360   /* Generate code for all sub-queries in the FROM clause
   98361   */
   98362 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   98363   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   98364     struct SrcList_item *pItem = &pTabList->a[i];
   98365     SelectDest dest;
   98366     Select *pSub = pItem->pSelect;
   98367     int isAggSub;
   98368 
   98369     if( pSub==0 ) continue;
   98370     if( pItem->addrFillSub ){
   98371       sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
   98372       continue;
   98373     }
   98374 
   98375     /* Increment Parse.nHeight by the height of the largest expression
   98376     ** tree refered to by this, the parent select. The child select
   98377     ** may contain expression trees of at most
   98378     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   98379     ** more conservative than necessary, but much easier than enforcing
   98380     ** an exact limit.
   98381     */
   98382     pParse->nHeight += sqlite3SelectExprHeight(p);
   98383 
   98384     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   98385     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   98386       /* This subquery can be absorbed into its parent. */
   98387       if( isAggSub ){
   98388         isAgg = 1;
   98389         p->selFlags |= SF_Aggregate;
   98390       }
   98391       i = -1;
   98392     }else{
   98393       /* Generate a subroutine that will fill an ephemeral table with
   98394       ** the content of this subquery.  pItem->addrFillSub will point
   98395       ** to the address of the generated subroutine.  pItem->regReturn
   98396       ** is a register allocated to hold the subroutine return address
   98397       */
   98398       int topAddr;
   98399       int onceAddr = 0;
   98400       int retAddr;
   98401       assert( pItem->addrFillSub==0 );
   98402       pItem->regReturn = ++pParse->nMem;
   98403       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
   98404       pItem->addrFillSub = topAddr+1;
   98405       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
   98406       if( pItem->isCorrelated==0 ){
   98407         /* If the subquery is no correlated and if we are not inside of
   98408         ** a trigger, then we only need to compute the value of the subquery
   98409         ** once. */
   98410         onceAddr = sqlite3CodeOnce(pParse);
   98411       }
   98412       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   98413       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   98414       sqlite3Select(pParse, pSub, &dest);
   98415       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
   98416       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
   98417       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
   98418       VdbeComment((v, "end %s", pItem->pTab->zName));
   98419       sqlite3VdbeChangeP1(v, topAddr, retAddr);
   98420       sqlite3ClearTempRegCache(pParse);
   98421     }
   98422     if( /*pParse->nErr ||*/ db->mallocFailed ){
   98423       goto select_end;
   98424     }
   98425     pParse->nHeight -= sqlite3SelectExprHeight(p);
   98426     pTabList = p->pSrc;
   98427     if( !IgnorableOrderby(pDest) ){
   98428       pOrderBy = p->pOrderBy;
   98429     }
   98430   }
   98431   pEList = p->pEList;
   98432 #endif
   98433   pWhere = p->pWhere;
   98434   pGroupBy = p->pGroupBy;
   98435   pHaving = p->pHaving;
   98436   isDistinct = (p->selFlags & SF_Distinct)!=0;
   98437 
   98438 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   98439   /* If there is are a sequence of queries, do the earlier ones first.
   98440   */
   98441   if( p->pPrior ){
   98442     if( p->pRightmost==0 ){
   98443       Select *pLoop, *pRight = 0;
   98444       int cnt = 0;
   98445       int mxSelect;
   98446       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
   98447         pLoop->pRightmost = p;
   98448         pLoop->pNext = pRight;
   98449         pRight = pLoop;
   98450       }
   98451       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   98452       if( mxSelect && cnt>mxSelect ){
   98453         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   98454         goto select_end;
   98455       }
   98456     }
   98457     rc = multiSelect(pParse, p, pDest);
   98458     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   98459     return rc;
   98460   }
   98461 #endif
   98462 
   98463   /* If there is both a GROUP BY and an ORDER BY clause and they are
   98464   ** identical, then disable the ORDER BY clause since the GROUP BY
   98465   ** will cause elements to come out in the correct order.  This is
   98466   ** an optimization - the correct answer should result regardless.
   98467   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
   98468   ** to disable this optimization for testing purposes.
   98469   */
   98470   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
   98471          && (db->flags & SQLITE_GroupByOrder)==0 ){
   98472     pOrderBy = 0;
   98473   }
   98474 
   98475   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   98476   ** if the select-list is the same as the ORDER BY list, then this query
   98477   ** can be rewritten as a GROUP BY. In other words, this:
   98478   **
   98479   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
   98480   **
   98481   ** is transformed to:
   98482   **
   98483   **     SELECT xyz FROM ... GROUP BY xyz
   98484   **
   98485   ** The second form is preferred as a single index (or temp-table) may be
   98486   ** used for both the ORDER BY and DISTINCT processing. As originally
   98487   ** written the query must use a temp-table for at least one of the ORDER
   98488   ** BY and DISTINCT, and an index or separate temp-table for the other.
   98489   */
   98490   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   98491    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
   98492   ){
   98493     p->selFlags &= ~SF_Distinct;
   98494     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   98495     pGroupBy = p->pGroupBy;
   98496     pOrderBy = 0;
   98497   }
   98498 
   98499   /* If there is an ORDER BY clause, then this sorting
   98500   ** index might end up being unused if the data can be
   98501   ** extracted in pre-sorted order.  If that is the case, then the
   98502   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   98503   ** we figure out that the sorting index is not needed.  The addrSortIndex
   98504   ** variable is used to facilitate that change.
   98505   */
   98506   if( pOrderBy ){
   98507     KeyInfo *pKeyInfo;
   98508     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
   98509     pOrderBy->iECursor = pParse->nTab++;
   98510     p->addrOpenEphm[2] = addrSortIndex =
   98511       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   98512                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
   98513                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98514   }else{
   98515     addrSortIndex = -1;
   98516   }
   98517 
   98518   /* If the output is destined for a temporary table, open that table.
   98519   */
   98520   if( pDest->eDest==SRT_EphemTab ){
   98521     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
   98522   }
   98523 
   98524   /* Set the limiter.
   98525   */
   98526   iEnd = sqlite3VdbeMakeLabel(v);
   98527   p->nSelectRow = (double)LARGEST_INT64;
   98528   computeLimitRegisters(pParse, p, iEnd);
   98529   if( p->iLimit==0 && addrSortIndex>=0 ){
   98530     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
   98531     p->selFlags |= SF_UseSorter;
   98532   }
   98533 
   98534   /* Open a virtual index to use for the distinct set.
   98535   */
   98536   if( p->selFlags & SF_Distinct ){
   98537     KeyInfo *pKeyInfo;
   98538     distinct = pParse->nTab++;
   98539     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
   98540     addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
   98541         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98542     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   98543   }else{
   98544     distinct = addrDistinctIndex = -1;
   98545   }
   98546 
   98547   /* Aggregate and non-aggregate queries are handled differently */
   98548   if( !isAgg && pGroupBy==0 ){
   98549     ExprList *pDist = (isDistinct ? p->pEList : 0);
   98550 
   98551     /* Begin the database scan. */
   98552     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
   98553     if( pWInfo==0 ) goto select_end;
   98554     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
   98555 
   98556     /* If sorting index that was created by a prior OP_OpenEphemeral
   98557     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   98558     ** into an OP_Noop.
   98559     */
   98560     if( addrSortIndex>=0 && pOrderBy==0 ){
   98561       sqlite3VdbeChangeToNoop(v, addrSortIndex);
   98562       p->addrOpenEphm[2] = -1;
   98563     }
   98564 
   98565     if( pWInfo->eDistinct ){
   98566       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
   98567 
   98568       assert( addrDistinctIndex>=0 );
   98569       pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
   98570 
   98571       assert( isDistinct );
   98572       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
   98573            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
   98574       );
   98575       distinct = -1;
   98576       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
   98577         int iJump;
   98578         int iExpr;
   98579         int iFlag = ++pParse->nMem;
   98580         int iBase = pParse->nMem+1;
   98581         int iBase2 = iBase + pEList->nExpr;
   98582         pParse->nMem += (pEList->nExpr*2);
   98583 
   98584         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
   98585         ** OP_Integer initializes the "first row" flag.  */
   98586         pOp->opcode = OP_Integer;
   98587         pOp->p1 = 1;
   98588         pOp->p2 = iFlag;
   98589 
   98590         sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
   98591         iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
   98592         sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
   98593         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
   98594           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
   98595           sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
   98596           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   98597           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   98598         }
   98599         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
   98600 
   98601         sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
   98602         assert( sqlite3VdbeCurrentAddr(v)==iJump );
   98603         sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
   98604       }else{
   98605         pOp->opcode = OP_Noop;
   98606       }
   98607     }
   98608 
   98609     /* Use the standard inner loop. */
   98610     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
   98611                     pWInfo->iContinue, pWInfo->iBreak);
   98612 
   98613     /* End the database scan loop.
   98614     */
   98615     sqlite3WhereEnd(pWInfo);
   98616   }else{
   98617     /* This is the processing for aggregate queries */
   98618     NameContext sNC;    /* Name context for processing aggregate information */
   98619     int iAMem;          /* First Mem address for storing current GROUP BY */
   98620     int iBMem;          /* First Mem address for previous GROUP BY */
   98621     int iUseFlag;       /* Mem address holding flag indicating that at least
   98622                         ** one row of the input to the aggregator has been
   98623                         ** processed */
   98624     int iAbortFlag;     /* Mem address which causes query abort if positive */
   98625     int groupBySort;    /* Rows come from source in GROUP BY order */
   98626     int addrEnd;        /* End of processing for this SELECT */
   98627     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
   98628     int sortOut = 0;    /* Output register from the sorter */
   98629 
   98630     /* Remove any and all aliases between the result set and the
   98631     ** GROUP BY clause.
   98632     */
   98633     if( pGroupBy ){
   98634       int k;                        /* Loop counter */
   98635       struct ExprList_item *pItem;  /* For looping over expression in a list */
   98636 
   98637       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   98638         pItem->iAlias = 0;
   98639       }
   98640       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   98641         pItem->iAlias = 0;
   98642       }
   98643       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
   98644     }else{
   98645       p->nSelectRow = (double)1;
   98646     }
   98647 
   98648 
   98649     /* Create a label to jump to when we want to abort the query */
   98650     addrEnd = sqlite3VdbeMakeLabel(v);
   98651 
   98652     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   98653     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   98654     ** SELECT statement.
   98655     */
   98656     memset(&sNC, 0, sizeof(sNC));
   98657     sNC.pParse = pParse;
   98658     sNC.pSrcList = pTabList;
   98659     sNC.pAggInfo = &sAggInfo;
   98660     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   98661     sAggInfo.pGroupBy = pGroupBy;
   98662     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   98663     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
   98664     if( pHaving ){
   98665       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   98666     }
   98667     sAggInfo.nAccumulator = sAggInfo.nColumn;
   98668     for(i=0; i<sAggInfo.nFunc; i++){
   98669       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   98670       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   98671     }
   98672     if( db->mallocFailed ) goto select_end;
   98673 
   98674     /* Processing for aggregates with GROUP BY is very different and
   98675     ** much more complex than aggregates without a GROUP BY.
   98676     */
   98677     if( pGroupBy ){
   98678       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   98679       int j1;             /* A-vs-B comparision jump */
   98680       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   98681       int regOutputRow;   /* Return address register for output subroutine */
   98682       int addrSetAbort;   /* Set the abort flag and return */
   98683       int addrTopOfLoop;  /* Top of the input loop */
   98684       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   98685       int addrReset;      /* Subroutine for resetting the accumulator */
   98686       int regReset;       /* Return address register for reset subroutine */
   98687 
   98688       /* If there is a GROUP BY clause we might need a sorting index to
   98689       ** implement it.  Allocate that sorting index now.  If it turns out
   98690       ** that we do not need it after all, the OP_SorterOpen instruction
   98691       ** will be converted into a Noop.
   98692       */
   98693       sAggInfo.sortingIdx = pParse->nTab++;
   98694       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
   98695       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
   98696           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   98697           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98698 
   98699       /* Initialize memory locations used by GROUP BY aggregate processing
   98700       */
   98701       iUseFlag = ++pParse->nMem;
   98702       iAbortFlag = ++pParse->nMem;
   98703       regOutputRow = ++pParse->nMem;
   98704       addrOutputRow = sqlite3VdbeMakeLabel(v);
   98705       regReset = ++pParse->nMem;
   98706       addrReset = sqlite3VdbeMakeLabel(v);
   98707       iAMem = pParse->nMem + 1;
   98708       pParse->nMem += pGroupBy->nExpr;
   98709       iBMem = pParse->nMem + 1;
   98710       pParse->nMem += pGroupBy->nExpr;
   98711       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   98712       VdbeComment((v, "clear abort flag"));
   98713       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   98714       VdbeComment((v, "indicate accumulator empty"));
   98715       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
   98716 
   98717       /* Begin a loop that will extract all source rows in GROUP BY order.
   98718       ** This might involve two separate loops with an OP_Sort in between, or
   98719       ** it might be a single loop that uses an index to extract information
   98720       ** in the right order to begin with.
   98721       */
   98722       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   98723       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
   98724       if( pWInfo==0 ) goto select_end;
   98725       if( pGroupBy==0 ){
   98726         /* The optimizer is able to deliver rows in group by order so
   98727         ** we do not have to sort.  The OP_OpenEphemeral table will be
   98728         ** cancelled later because we still need to use the pKeyInfo
   98729         */
   98730         pGroupBy = p->pGroupBy;
   98731         groupBySort = 0;
   98732       }else{
   98733         /* Rows are coming out in undetermined order.  We have to push
   98734         ** each row into a sorting index, terminate the first loop,
   98735         ** then loop over the sorting index in order to get the output
   98736         ** in sorted order
   98737         */
   98738         int regBase;
   98739         int regRecord;
   98740         int nCol;
   98741         int nGroupBy;
   98742 
   98743         explainTempTable(pParse,
   98744             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
   98745 
   98746         groupBySort = 1;
   98747         nGroupBy = pGroupBy->nExpr;
   98748         nCol = nGroupBy + 1;
   98749         j = nGroupBy+1;
   98750         for(i=0; i<sAggInfo.nColumn; i++){
   98751           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   98752             nCol++;
   98753             j++;
   98754           }
   98755         }
   98756         regBase = sqlite3GetTempRange(pParse, nCol);
   98757         sqlite3ExprCacheClear(pParse);
   98758         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   98759         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   98760         j = nGroupBy+1;
   98761         for(i=0; i<sAggInfo.nColumn; i++){
   98762           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   98763           if( pCol->iSorterColumn>=j ){
   98764             int r1 = j + regBase;
   98765             int r2;
   98766 
   98767             r2 = sqlite3ExprCodeGetColumn(pParse,
   98768                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
   98769             if( r1!=r2 ){
   98770               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   98771             }
   98772             j++;
   98773           }
   98774         }
   98775         regRecord = sqlite3GetTempReg(pParse);
   98776         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   98777         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
   98778         sqlite3ReleaseTempReg(pParse, regRecord);
   98779         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   98780         sqlite3WhereEnd(pWInfo);
   98781         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
   98782         sortOut = sqlite3GetTempReg(pParse);
   98783         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
   98784         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
   98785         VdbeComment((v, "GROUP BY sort"));
   98786         sAggInfo.useSortingIdx = 1;
   98787         sqlite3ExprCacheClear(pParse);
   98788       }
   98789 
   98790       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   98791       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   98792       ** Then compare the current GROUP BY terms against the GROUP BY terms
   98793       ** from the previous row currently stored in a0, a1, a2...
   98794       */
   98795       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   98796       sqlite3ExprCacheClear(pParse);
   98797       if( groupBySort ){
   98798         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
   98799       }
   98800       for(j=0; j<pGroupBy->nExpr; j++){
   98801         if( groupBySort ){
   98802           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
   98803           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   98804         }else{
   98805           sAggInfo.directMode = 1;
   98806           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   98807         }
   98808       }
   98809       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   98810                           (char*)pKeyInfo, P4_KEYINFO);
   98811       j1 = sqlite3VdbeCurrentAddr(v);
   98812       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
   98813 
   98814       /* Generate code that runs whenever the GROUP BY changes.
   98815       ** Changes in the GROUP BY are detected by the previous code
   98816       ** block.  If there were no changes, this block is skipped.
   98817       **
   98818       ** This code copies current group by terms in b0,b1,b2,...
   98819       ** over to a0,a1,a2.  It then calls the output subroutine
   98820       ** and resets the aggregate accumulator registers in preparation
   98821       ** for the next GROUP BY batch.
   98822       */
   98823       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   98824       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   98825       VdbeComment((v, "output one row"));
   98826       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
   98827       VdbeComment((v, "check abort flag"));
   98828       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   98829       VdbeComment((v, "reset accumulator"));
   98830 
   98831       /* Update the aggregate accumulators based on the content of
   98832       ** the current row
   98833       */
   98834       sqlite3VdbeJumpHere(v, j1);
   98835       updateAccumulator(pParse, &sAggInfo);
   98836       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   98837       VdbeComment((v, "indicate data in accumulator"));
   98838 
   98839       /* End of the loop
   98840       */
   98841       if( groupBySort ){
   98842         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
   98843       }else{
   98844         sqlite3WhereEnd(pWInfo);
   98845         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
   98846       }
   98847 
   98848       /* Output the final row of result
   98849       */
   98850       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   98851       VdbeComment((v, "output final row"));
   98852 
   98853       /* Jump over the subroutines
   98854       */
   98855       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   98856 
   98857       /* Generate a subroutine that outputs a single row of the result
   98858       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   98859       ** is less than or equal to zero, the subroutine is a no-op.  If
   98860       ** the processing calls for the query to abort, this subroutine
   98861       ** increments the iAbortFlag memory location before returning in
   98862       ** order to signal the caller to abort.
   98863       */
   98864       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   98865       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   98866       VdbeComment((v, "set abort flag"));
   98867       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98868       sqlite3VdbeResolveLabel(v, addrOutputRow);
   98869       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   98870       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
   98871       VdbeComment((v, "Groupby result generator entry point"));
   98872       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98873       finalizeAggFunctions(pParse, &sAggInfo);
   98874       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   98875       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
   98876                       distinct, pDest,
   98877                       addrOutputRow+1, addrSetAbort);
   98878       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98879       VdbeComment((v, "end groupby result generator"));
   98880 
   98881       /* Generate a subroutine that will reset the group-by accumulator
   98882       */
   98883       sqlite3VdbeResolveLabel(v, addrReset);
   98884       resetAccumulator(pParse, &sAggInfo);
   98885       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   98886 
   98887     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   98888     else {
   98889       ExprList *pDel = 0;
   98890 #ifndef SQLITE_OMIT_BTREECOUNT
   98891       Table *pTab;
   98892       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   98893         /* If isSimpleCount() returns a pointer to a Table structure, then
   98894         ** the SQL statement is of the form:
   98895         **
   98896         **   SELECT count(*) FROM <tbl>
   98897         **
   98898         ** where the Table structure returned represents table <tbl>.
   98899         **
   98900         ** This statement is so common that it is optimized specially. The
   98901         ** OP_Count instruction is executed either on the intkey table that
   98902         ** contains the data for table <tbl> or on one of its indexes. It
   98903         ** is better to execute the op on an index, as indexes are almost
   98904         ** always spread across less pages than their corresponding tables.
   98905         */
   98906         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   98907         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   98908         Index *pIdx;                         /* Iterator variable */
   98909         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   98910         Index *pBest = 0;                    /* Best index found so far */
   98911         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   98912 
   98913         sqlite3CodeVerifySchema(pParse, iDb);
   98914         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   98915 
   98916         /* Search for the index that has the least amount of columns. If
   98917         ** there is such an index, and it has less columns than the table
   98918         ** does, then we can assume that it consumes less space on disk and
   98919         ** will therefore be cheaper to scan to determine the query result.
   98920         ** In this case set iRoot to the root page number of the index b-tree
   98921         ** and pKeyInfo to the KeyInfo structure required to navigate the
   98922         ** index.
   98923         **
   98924         ** (2011-04-15) Do not do a full scan of an unordered index.
   98925         **
   98926         ** In practice the KeyInfo structure will not be used. It is only
   98927         ** passed to keep OP_OpenRead happy.
   98928         */
   98929         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   98930           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
   98931             pBest = pIdx;
   98932           }
   98933         }
   98934         if( pBest && pBest->nColumn<pTab->nCol ){
   98935           iRoot = pBest->tnum;
   98936           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
   98937         }
   98938 
   98939         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   98940         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
   98941         if( pKeyInfo ){
   98942           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
   98943         }
   98944         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   98945         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   98946         explainSimpleCount(pParse, pTab, pBest);
   98947       }else
   98948 #endif /* SQLITE_OMIT_BTREECOUNT */
   98949       {
   98950         /* Check if the query is of one of the following forms:
   98951         **
   98952         **   SELECT min(x) FROM ...
   98953         **   SELECT max(x) FROM ...
   98954         **
   98955         ** If it is, then ask the code in where.c to attempt to sort results
   98956         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   98957         ** If where.c is able to produce results sorted in this order, then
   98958         ** add vdbe code to break out of the processing loop after the
   98959         ** first iteration (since the first iteration of the loop is
   98960         ** guaranteed to operate on the row with the minimum or maximum
   98961         ** value of x, the only row required).
   98962         **
   98963         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   98964         ** modify behaviour as follows:
   98965         **
   98966         **   + If the query is a "SELECT min(x)", then the loop coded by
   98967         **     where.c should not iterate over any values with a NULL value
   98968         **     for x.
   98969         **
   98970         **   + The optimizer code in where.c (the thing that decides which
   98971         **     index or indices to use) should place a different priority on
   98972         **     satisfying the 'ORDER BY' clause than it does in other cases.
   98973         **     Refer to code and comments in where.c for details.
   98974         */
   98975         ExprList *pMinMax = 0;
   98976         u8 flag = minMaxQuery(p);
   98977         if( flag ){
   98978           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
   98979           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
   98980           pDel = pMinMax;
   98981           if( pMinMax && !db->mallocFailed ){
   98982             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   98983             pMinMax->a[0].pExpr->op = TK_COLUMN;
   98984           }
   98985         }
   98986 
   98987         /* This case runs if the aggregate has no GROUP BY clause.  The
   98988         ** processing is much simpler since there is only a single row
   98989         ** of output.
   98990         */
   98991         resetAccumulator(pParse, &sAggInfo);
   98992         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
   98993         if( pWInfo==0 ){
   98994           sqlite3ExprListDelete(db, pDel);
   98995           goto select_end;
   98996         }
   98997         updateAccumulator(pParse, &sAggInfo);
   98998         if( !pMinMax && flag ){
   98999           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
   99000           VdbeComment((v, "%s() by index",
   99001                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   99002         }
   99003         sqlite3WhereEnd(pWInfo);
   99004         finalizeAggFunctions(pParse, &sAggInfo);
   99005       }
   99006 
   99007       pOrderBy = 0;
   99008       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   99009       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
   99010                       pDest, addrEnd, addrEnd);
   99011       sqlite3ExprListDelete(db, pDel);
   99012     }
   99013     sqlite3VdbeResolveLabel(v, addrEnd);
   99014 
   99015   } /* endif aggregate query */
   99016 
   99017   if( distinct>=0 ){
   99018     explainTempTable(pParse, "DISTINCT");
   99019   }
   99020 
   99021   /* If there is an ORDER BY clause, then we need to sort the results
   99022   ** and send them to the callback one by one.
   99023   */
   99024   if( pOrderBy ){
   99025     explainTempTable(pParse, "ORDER BY");
   99026     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
   99027   }
   99028 
   99029   /* Jump here to skip this query
   99030   */
   99031   sqlite3VdbeResolveLabel(v, iEnd);
   99032 
   99033   /* The SELECT was successfully coded.   Set the return code to 0
   99034   ** to indicate no errors.
   99035   */
   99036   rc = 0;
   99037 
   99038   /* Control jumps to here if an error is encountered above, or upon
   99039   ** successful coding of the SELECT.
   99040   */
   99041 select_end:
   99042   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   99043 
   99044   /* Identify column names if results of the SELECT are to be output.
   99045   */
   99046   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   99047     generateColumnNames(pParse, pTabList, pEList);
   99048   }
   99049 
   99050   sqlite3DbFree(db, sAggInfo.aCol);
   99051   sqlite3DbFree(db, sAggInfo.aFunc);
   99052   return rc;
   99053 }
   99054 
   99055 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   99056 /*
   99057 ** Generate a human-readable description of a the Select object.
   99058 */
   99059 static void explainOneSelect(Vdbe *pVdbe, Select *p){
   99060   sqlite3ExplainPrintf(pVdbe, "SELECT ");
   99061   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   99062     if( p->selFlags & SF_Distinct ){
   99063       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
   99064     }
   99065     if( p->selFlags & SF_Aggregate ){
   99066       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
   99067     }
   99068     sqlite3ExplainNL(pVdbe);
   99069     sqlite3ExplainPrintf(pVdbe, "   ");
   99070   }
   99071   sqlite3ExplainExprList(pVdbe, p->pEList);
   99072   sqlite3ExplainNL(pVdbe);
   99073   if( p->pSrc && p->pSrc->nSrc ){
   99074     int i;
   99075     sqlite3ExplainPrintf(pVdbe, "FROM ");
   99076     sqlite3ExplainPush(pVdbe);
   99077     for(i=0; i<p->pSrc->nSrc; i++){
   99078       struct SrcList_item *pItem = &p->pSrc->a[i];
   99079       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
   99080       if( pItem->pSelect ){
   99081         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
   99082         if( pItem->pTab ){
   99083           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
   99084         }
   99085       }else if( pItem->zName ){
   99086         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
   99087       }
   99088       if( pItem->zAlias ){
   99089         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
   99090       }
   99091       if( pItem->jointype & JT_LEFT ){
   99092         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
   99093       }
   99094       sqlite3ExplainNL(pVdbe);
   99095     }
   99096     sqlite3ExplainPop(pVdbe);
   99097   }
   99098   if( p->pWhere ){
   99099     sqlite3ExplainPrintf(pVdbe, "WHERE ");
   99100     sqlite3ExplainExpr(pVdbe, p->pWhere);
   99101     sqlite3ExplainNL(pVdbe);
   99102   }
   99103   if( p->pGroupBy ){
   99104     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
   99105     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
   99106     sqlite3ExplainNL(pVdbe);
   99107   }
   99108   if( p->pHaving ){
   99109     sqlite3ExplainPrintf(pVdbe, "HAVING ");
   99110     sqlite3ExplainExpr(pVdbe, p->pHaving);
   99111     sqlite3ExplainNL(pVdbe);
   99112   }
   99113   if( p->pOrderBy ){
   99114     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
   99115     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
   99116     sqlite3ExplainNL(pVdbe);
   99117   }
   99118   if( p->pLimit ){
   99119     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
   99120     sqlite3ExplainExpr(pVdbe, p->pLimit);
   99121     sqlite3ExplainNL(pVdbe);
   99122   }
   99123   if( p->pOffset ){
   99124     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
   99125     sqlite3ExplainExpr(pVdbe, p->pOffset);
   99126     sqlite3ExplainNL(pVdbe);
   99127   }
   99128 }
   99129 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
   99130   if( p==0 ){
   99131     sqlite3ExplainPrintf(pVdbe, "(null-select)");
   99132     return;
   99133   }
   99134   while( p->pPrior ) p = p->pPrior;
   99135   sqlite3ExplainPush(pVdbe);
   99136   while( p ){
   99137     explainOneSelect(pVdbe, p);
   99138     p = p->pNext;
   99139     if( p==0 ) break;
   99140     sqlite3ExplainNL(pVdbe);
   99141     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
   99142   }
   99143   sqlite3ExplainPrintf(pVdbe, "END");
   99144   sqlite3ExplainPop(pVdbe);
   99145 }
   99146 
   99147 /* End of the structure debug printing code
   99148 *****************************************************************************/
   99149 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   99150 
   99151 /************** End of select.c **********************************************/
   99152 /************** Begin file table.c *******************************************/
   99153 /*
   99154 ** 2001 September 15
   99155 **
   99156 ** The author disclaims copyright to this source code.  In place of
   99157 ** a legal notice, here is a blessing:
   99158 **
   99159 **    May you do good and not evil.
   99160 **    May you find forgiveness for yourself and forgive others.
   99161 **    May you share freely, never taking more than you give.
   99162 **
   99163 *************************************************************************
   99164 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   99165 ** interface routines.  These are just wrappers around the main
   99166 ** interface routine of sqlite3_exec().
   99167 **
   99168 ** These routines are in a separate files so that they will not be linked
   99169 ** if they are not used.
   99170 */
   99171 /* #include <stdlib.h> */
   99172 /* #include <string.h> */
   99173 
   99174 #ifndef SQLITE_OMIT_GET_TABLE
   99175 
   99176 /*
   99177 ** This structure is used to pass data from sqlite3_get_table() through
   99178 ** to the callback function is uses to build the result.
   99179 */
   99180 typedef struct TabResult {
   99181   char **azResult;   /* Accumulated output */
   99182   char *zErrMsg;     /* Error message text, if an error occurs */
   99183   int nAlloc;        /* Slots allocated for azResult[] */
   99184   int nRow;          /* Number of rows in the result */
   99185   int nColumn;       /* Number of columns in the result */
   99186   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   99187   int rc;            /* Return code from sqlite3_exec() */
   99188 } TabResult;
   99189 
   99190 /*
   99191 ** This routine is called once for each row in the result table.  Its job
   99192 ** is to fill in the TabResult structure appropriately, allocating new
   99193 ** memory as necessary.
   99194 */
   99195 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   99196   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   99197   int need;                         /* Slots needed in p->azResult[] */
   99198   int i;                            /* Loop counter */
   99199   char *z;                          /* A single column of result */
   99200 
   99201   /* Make sure there is enough space in p->azResult to hold everything
   99202   ** we need to remember from this invocation of the callback.
   99203   */
   99204   if( p->nRow==0 && argv!=0 ){
   99205     need = nCol*2;
   99206   }else{
   99207     need = nCol;
   99208   }
   99209   if( p->nData + need > p->nAlloc ){
   99210     char **azNew;
   99211     p->nAlloc = p->nAlloc*2 + need;
   99212     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   99213     if( azNew==0 ) goto malloc_failed;
   99214     p->azResult = azNew;
   99215   }
   99216 
   99217   /* If this is the first row, then generate an extra row containing
   99218   ** the names of all columns.
   99219   */
   99220   if( p->nRow==0 ){
   99221     p->nColumn = nCol;
   99222     for(i=0; i<nCol; i++){
   99223       z = sqlite3_mprintf("%s", colv[i]);
   99224       if( z==0 ) goto malloc_failed;
   99225       p->azResult[p->nData++] = z;
   99226     }
   99227   }else if( p->nColumn!=nCol ){
   99228     sqlite3_free(p->zErrMsg);
   99229     p->zErrMsg = sqlite3_mprintf(
   99230        "sqlite3_get_table() called with two or more incompatible queries"
   99231     );
   99232     p->rc = SQLITE_ERROR;
   99233     return 1;
   99234   }
   99235 
   99236   /* Copy over the row data
   99237   */
   99238   if( argv!=0 ){
   99239     for(i=0; i<nCol; i++){
   99240       if( argv[i]==0 ){
   99241         z = 0;
   99242       }else{
   99243         int n = sqlite3Strlen30(argv[i])+1;
   99244         z = sqlite3_malloc( n );
   99245         if( z==0 ) goto malloc_failed;
   99246         memcpy(z, argv[i], n);
   99247       }
   99248       p->azResult[p->nData++] = z;
   99249     }
   99250     p->nRow++;
   99251   }
   99252   return 0;
   99253 
   99254 malloc_failed:
   99255   p->rc = SQLITE_NOMEM;
   99256   return 1;
   99257 }
   99258 
   99259 /*
   99260 ** Query the database.  But instead of invoking a callback for each row,
   99261 ** malloc() for space to hold the result and return the entire results
   99262 ** at the conclusion of the call.
   99263 **
   99264 ** The result that is written to ***pazResult is held in memory obtained
   99265 ** from malloc().  But the caller cannot free this memory directly.
   99266 ** Instead, the entire table should be passed to sqlite3_free_table() when
   99267 ** the calling procedure is finished using it.
   99268 */
   99269 SQLITE_API int sqlite3_get_table(
   99270   sqlite3 *db,                /* The database on which the SQL executes */
   99271   const char *zSql,           /* The SQL to be executed */
   99272   char ***pazResult,          /* Write the result table here */
   99273   int *pnRow,                 /* Write the number of rows in the result here */
   99274   int *pnColumn,              /* Write the number of columns of result here */
   99275   char **pzErrMsg             /* Write error messages here */
   99276 ){
   99277   int rc;
   99278   TabResult res;
   99279 
   99280   *pazResult = 0;
   99281   if( pnColumn ) *pnColumn = 0;
   99282   if( pnRow ) *pnRow = 0;
   99283   if( pzErrMsg ) *pzErrMsg = 0;
   99284   res.zErrMsg = 0;
   99285   res.nRow = 0;
   99286   res.nColumn = 0;
   99287   res.nData = 1;
   99288   res.nAlloc = 20;
   99289   res.rc = SQLITE_OK;
   99290   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   99291   if( res.azResult==0 ){
   99292      db->errCode = SQLITE_NOMEM;
   99293      return SQLITE_NOMEM;
   99294   }
   99295   res.azResult[0] = 0;
   99296   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   99297   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   99298   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   99299   if( (rc&0xff)==SQLITE_ABORT ){
   99300     sqlite3_free_table(&res.azResult[1]);
   99301     if( res.zErrMsg ){
   99302       if( pzErrMsg ){
   99303         sqlite3_free(*pzErrMsg);
   99304         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   99305       }
   99306       sqlite3_free(res.zErrMsg);
   99307     }
   99308     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   99309     return res.rc;
   99310   }
   99311   sqlite3_free(res.zErrMsg);
   99312   if( rc!=SQLITE_OK ){
   99313     sqlite3_free_table(&res.azResult[1]);
   99314     return rc;
   99315   }
   99316   if( res.nAlloc>res.nData ){
   99317     char **azNew;
   99318     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   99319     if( azNew==0 ){
   99320       sqlite3_free_table(&res.azResult[1]);
   99321       db->errCode = SQLITE_NOMEM;
   99322       return SQLITE_NOMEM;
   99323     }
   99324     res.azResult = azNew;
   99325   }
   99326   *pazResult = &res.azResult[1];
   99327   if( pnColumn ) *pnColumn = res.nColumn;
   99328   if( pnRow ) *pnRow = res.nRow;
   99329   return rc;
   99330 }
   99331 
   99332 /*
   99333 ** This routine frees the space the sqlite3_get_table() malloced.
   99334 */
   99335 SQLITE_API void sqlite3_free_table(
   99336   char **azResult            /* Result returned from from sqlite3_get_table() */
   99337 ){
   99338   if( azResult ){
   99339     int i, n;
   99340     azResult--;
   99341     assert( azResult!=0 );
   99342     n = SQLITE_PTR_TO_INT(azResult[0]);
   99343     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   99344     sqlite3_free(azResult);
   99345   }
   99346 }
   99347 
   99348 #endif /* SQLITE_OMIT_GET_TABLE */
   99349 
   99350 /************** End of table.c ***********************************************/
   99351 /************** Begin file trigger.c *****************************************/
   99352 /*
   99353 **
   99354 ** The author disclaims copyright to this source code.  In place of
   99355 ** a legal notice, here is a blessing:
   99356 **
   99357 **    May you do good and not evil.
   99358 **    May you find forgiveness for yourself and forgive others.
   99359 **    May you share freely, never taking more than you give.
   99360 **
   99361 *************************************************************************
   99362 ** This file contains the implementation for TRIGGERs
   99363 */
   99364 
   99365 #ifndef SQLITE_OMIT_TRIGGER
   99366 /*
   99367 ** Delete a linked list of TriggerStep structures.
   99368 */
   99369 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   99370   while( pTriggerStep ){
   99371     TriggerStep * pTmp = pTriggerStep;
   99372     pTriggerStep = pTriggerStep->pNext;
   99373 
   99374     sqlite3ExprDelete(db, pTmp->pWhere);
   99375     sqlite3ExprListDelete(db, pTmp->pExprList);
   99376     sqlite3SelectDelete(db, pTmp->pSelect);
   99377     sqlite3IdListDelete(db, pTmp->pIdList);
   99378 
   99379     sqlite3DbFree(db, pTmp);
   99380   }
   99381 }
   99382 
   99383 /*
   99384 ** Given table pTab, return a list of all the triggers attached to
   99385 ** the table. The list is connected by Trigger.pNext pointers.
   99386 **
   99387 ** All of the triggers on pTab that are in the same database as pTab
   99388 ** are already attached to pTab->pTrigger.  But there might be additional
   99389 ** triggers on pTab in the TEMP schema.  This routine prepends all
   99390 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   99391 ** and returns the combined list.
   99392 **
   99393 ** To state it another way:  This routine returns a list of all triggers
   99394 ** that fire off of pTab.  The list will include any TEMP triggers on
   99395 ** pTab as well as the triggers lised in pTab->pTrigger.
   99396 */
   99397 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   99398   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   99399   Trigger *pList = 0;                  /* List of triggers to return */
   99400 
   99401   if( pParse->disableTriggers ){
   99402     return 0;
   99403   }
   99404 
   99405   if( pTmpSchema!=pTab->pSchema ){
   99406     HashElem *p;
   99407     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
   99408     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   99409       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   99410       if( pTrig->pTabSchema==pTab->pSchema
   99411        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   99412       ){
   99413         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   99414         pList = pTrig;
   99415       }
   99416     }
   99417   }
   99418 
   99419   return (pList ? pList : pTab->pTrigger);
   99420 }
   99421 
   99422 /*
   99423 ** This is called by the parser when it sees a CREATE TRIGGER statement
   99424 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   99425 ** structure is generated based on the information available and stored
   99426 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   99427 ** sqlite3FinishTrigger() function is called to complete the trigger
   99428 ** construction process.
   99429 */
   99430 SQLITE_PRIVATE void sqlite3BeginTrigger(
   99431   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   99432   Token *pName1,      /* The name of the trigger */
   99433   Token *pName2,      /* The name of the trigger */
   99434   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   99435   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   99436   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   99437   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   99438   Expr *pWhen,        /* WHEN clause */
   99439   int isTemp,         /* True if the TEMPORARY keyword is present */
   99440   int noErr           /* Suppress errors if the trigger already exists */
   99441 ){
   99442   Trigger *pTrigger = 0;  /* The new trigger */
   99443   Table *pTab;            /* Table that the trigger fires off of */
   99444   char *zName = 0;        /* Name of the trigger */
   99445   sqlite3 *db = pParse->db;  /* The database connection */
   99446   int iDb;                /* The database to store the trigger in */
   99447   Token *pName;           /* The unqualified db name */
   99448   DbFixer sFix;           /* State vector for the DB fixer */
   99449   int iTabDb;             /* Index of the database holding pTab */
   99450 
   99451   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   99452   assert( pName2!=0 );
   99453   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   99454   assert( op>0 && op<0xff );
   99455   if( isTemp ){
   99456     /* If TEMP was specified, then the trigger name may not be qualified. */
   99457     if( pName2->n>0 ){
   99458       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   99459       goto trigger_cleanup;
   99460     }
   99461     iDb = 1;
   99462     pName = pName1;
   99463   }else{
   99464     /* Figure out the db that the the trigger will be created in */
   99465     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   99466     if( iDb<0 ){
   99467       goto trigger_cleanup;
   99468     }
   99469   }
   99470   if( !pTableName || db->mallocFailed ){
   99471     goto trigger_cleanup;
   99472   }
   99473 
   99474   /* A long-standing parser bug is that this syntax was allowed:
   99475   **
   99476   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
   99477   **                                                 ^^^^^^^^
   99478   **
   99479   ** To maintain backwards compatibility, ignore the database
   99480   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
   99481   */
   99482   if( db->init.busy && iDb!=1 ){
   99483     sqlite3DbFree(db, pTableName->a[0].zDatabase);
   99484     pTableName->a[0].zDatabase = 0;
   99485   }
   99486 
   99487   /* If the trigger name was unqualified, and the table is a temp table,
   99488   ** then set iDb to 1 to create the trigger in the temporary database.
   99489   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   99490   ** exist, the error is caught by the block below.
   99491   */
   99492   pTab = sqlite3SrcListLookup(pParse, pTableName);
   99493   if( db->init.busy==0 && pName2->n==0 && pTab
   99494         && pTab->pSchema==db->aDb[1].pSchema ){
   99495     iDb = 1;
   99496   }
   99497 
   99498   /* Ensure the table name matches database name and that the table exists */
   99499   if( db->mallocFailed ) goto trigger_cleanup;
   99500   assert( pTableName->nSrc==1 );
   99501   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
   99502       sqlite3FixSrcList(&sFix, pTableName) ){
   99503     goto trigger_cleanup;
   99504   }
   99505   pTab = sqlite3SrcListLookup(pParse, pTableName);
   99506   if( !pTab ){
   99507     /* The table does not exist. */
   99508     if( db->init.iDb==1 ){
   99509       /* Ticket #3810.
   99510       ** Normally, whenever a table is dropped, all associated triggers are
   99511       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   99512       ** and the table is dropped by a different database connection, the
   99513       ** trigger is not visible to the database connection that does the
   99514       ** drop so the trigger cannot be dropped.  This results in an
   99515       ** "orphaned trigger" - a trigger whose associated table is missing.
   99516       */
   99517       db->init.orphanTrigger = 1;
   99518     }
   99519     goto trigger_cleanup;
   99520   }
   99521   if( IsVirtual(pTab) ){
   99522     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   99523     goto trigger_cleanup;
   99524   }
   99525 
   99526   /* Check that the trigger name is not reserved and that no trigger of the
   99527   ** specified name exists */
   99528   zName = sqlite3NameFromToken(db, pName);
   99529   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   99530     goto trigger_cleanup;
   99531   }
   99532   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99533   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   99534                       zName, sqlite3Strlen30(zName)) ){
   99535     if( !noErr ){
   99536       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   99537     }else{
   99538       assert( !db->init.busy );
   99539       sqlite3CodeVerifySchema(pParse, iDb);
   99540     }
   99541     goto trigger_cleanup;
   99542   }
   99543 
   99544   /* Do not create a trigger on a system table */
   99545   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   99546     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   99547     pParse->nErr++;
   99548     goto trigger_cleanup;
   99549   }
   99550 
   99551   /* INSTEAD of triggers are only for views and views only support INSTEAD
   99552   ** of triggers.
   99553   */
   99554   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   99555     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   99556         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   99557     goto trigger_cleanup;
   99558   }
   99559   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   99560     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   99561         " trigger on table: %S", pTableName, 0);
   99562     goto trigger_cleanup;
   99563   }
   99564   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   99565 
   99566 #ifndef SQLITE_OMIT_AUTHORIZATION
   99567   {
   99568     int code = SQLITE_CREATE_TRIGGER;
   99569     const char *zDb = db->aDb[iTabDb].zName;
   99570     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   99571     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   99572     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   99573       goto trigger_cleanup;
   99574     }
   99575     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   99576       goto trigger_cleanup;
   99577     }
   99578   }
   99579 #endif
   99580 
   99581   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   99582   ** cannot appear on views.  So we might as well translate every
   99583   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   99584   ** elsewhere.
   99585   */
   99586   if (tr_tm == TK_INSTEAD){
   99587     tr_tm = TK_BEFORE;
   99588   }
   99589 
   99590   /* Build the Trigger object */
   99591   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   99592   if( pTrigger==0 ) goto trigger_cleanup;
   99593   pTrigger->zName = zName;
   99594   zName = 0;
   99595   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   99596   pTrigger->pSchema = db->aDb[iDb].pSchema;
   99597   pTrigger->pTabSchema = pTab->pSchema;
   99598   pTrigger->op = (u8)op;
   99599   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   99600   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   99601   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   99602   assert( pParse->pNewTrigger==0 );
   99603   pParse->pNewTrigger = pTrigger;
   99604 
   99605 trigger_cleanup:
   99606   sqlite3DbFree(db, zName);
   99607   sqlite3SrcListDelete(db, pTableName);
   99608   sqlite3IdListDelete(db, pColumns);
   99609   sqlite3ExprDelete(db, pWhen);
   99610   if( !pParse->pNewTrigger ){
   99611     sqlite3DeleteTrigger(db, pTrigger);
   99612   }else{
   99613     assert( pParse->pNewTrigger==pTrigger );
   99614   }
   99615 }
   99616 
   99617 /*
   99618 ** This routine is called after all of the trigger actions have been parsed
   99619 ** in order to complete the process of building the trigger.
   99620 */
   99621 SQLITE_PRIVATE void sqlite3FinishTrigger(
   99622   Parse *pParse,          /* Parser context */
   99623   TriggerStep *pStepList, /* The triggered program */
   99624   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   99625 ){
   99626   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   99627   char *zName;                            /* Name of trigger */
   99628   sqlite3 *db = pParse->db;               /* The database */
   99629   DbFixer sFix;                           /* Fixer object */
   99630   int iDb;                                /* Database containing the trigger */
   99631   Token nameToken;                        /* Trigger name for error reporting */
   99632 
   99633   pParse->pNewTrigger = 0;
   99634   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   99635   zName = pTrig->zName;
   99636   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   99637   pTrig->step_list = pStepList;
   99638   while( pStepList ){
   99639     pStepList->pTrig = pTrig;
   99640     pStepList = pStepList->pNext;
   99641   }
   99642   nameToken.z = pTrig->zName;
   99643   nameToken.n = sqlite3Strlen30(nameToken.z);
   99644   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
   99645           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
   99646     goto triggerfinish_cleanup;
   99647   }
   99648 
   99649   /* if we are not initializing,
   99650   ** build the sqlite_master entry
   99651   */
   99652   if( !db->init.busy ){
   99653     Vdbe *v;
   99654     char *z;
   99655 
   99656     /* Make an entry in the sqlite_master table */
   99657     v = sqlite3GetVdbe(pParse);
   99658     if( v==0 ) goto triggerfinish_cleanup;
   99659     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99660     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   99661     sqlite3NestedParse(pParse,
   99662        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   99663        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   99664        pTrig->table, z);
   99665     sqlite3DbFree(db, z);
   99666     sqlite3ChangeCookie(pParse, iDb);
   99667     sqlite3VdbeAddParseSchemaOp(v, iDb,
   99668         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   99669   }
   99670 
   99671   if( db->init.busy ){
   99672     Trigger *pLink = pTrig;
   99673     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   99674     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99675     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   99676     if( pTrig ){
   99677       db->mallocFailed = 1;
   99678     }else if( pLink->pSchema==pLink->pTabSchema ){
   99679       Table *pTab;
   99680       int n = sqlite3Strlen30(pLink->table);
   99681       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   99682       assert( pTab!=0 );
   99683       pLink->pNext = pTab->pTrigger;
   99684       pTab->pTrigger = pLink;
   99685     }
   99686   }
   99687 
   99688 triggerfinish_cleanup:
   99689   sqlite3DeleteTrigger(db, pTrig);
   99690   assert( !pParse->pNewTrigger );
   99691   sqlite3DeleteTriggerStep(db, pStepList);
   99692 }
   99693 
   99694 /*
   99695 ** Turn a SELECT statement (that the pSelect parameter points to) into
   99696 ** a trigger step.  Return a pointer to a TriggerStep structure.
   99697 **
   99698 ** The parser calls this routine when it finds a SELECT statement in
   99699 ** body of a TRIGGER.
   99700 */
   99701 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   99702   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   99703   if( pTriggerStep==0 ) {
   99704     sqlite3SelectDelete(db, pSelect);
   99705     return 0;
   99706   }
   99707   pTriggerStep->op = TK_SELECT;
   99708   pTriggerStep->pSelect = pSelect;
   99709   pTriggerStep->orconf = OE_Default;
   99710   return pTriggerStep;
   99711 }
   99712 
   99713 /*
   99714 ** Allocate space to hold a new trigger step.  The allocated space
   99715 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   99716 **
   99717 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   99718 */
   99719 static TriggerStep *triggerStepAllocate(
   99720   sqlite3 *db,                /* Database connection */
   99721   u8 op,                      /* Trigger opcode */
   99722   Token *pName                /* The target name */
   99723 ){
   99724   TriggerStep *pTriggerStep;
   99725 
   99726   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   99727   if( pTriggerStep ){
   99728     char *z = (char*)&pTriggerStep[1];
   99729     memcpy(z, pName->z, pName->n);
   99730     pTriggerStep->target.z = z;
   99731     pTriggerStep->target.n = pName->n;
   99732     pTriggerStep->op = op;
   99733   }
   99734   return pTriggerStep;
   99735 }
   99736 
   99737 /*
   99738 ** Build a trigger step out of an INSERT statement.  Return a pointer
   99739 ** to the new trigger step.
   99740 **
   99741 ** The parser calls this routine when it sees an INSERT inside the
   99742 ** body of a trigger.
   99743 */
   99744 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   99745   sqlite3 *db,        /* The database connection */
   99746   Token *pTableName,  /* Name of the table into which we insert */
   99747   IdList *pColumn,    /* List of columns in pTableName to insert into */
   99748   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
   99749   Select *pSelect,    /* A SELECT statement that supplies values */
   99750   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   99751 ){
   99752   TriggerStep *pTriggerStep;
   99753 
   99754   assert(pEList == 0 || pSelect == 0);
   99755   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
   99756 
   99757   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   99758   if( pTriggerStep ){
   99759     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   99760     pTriggerStep->pIdList = pColumn;
   99761     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   99762     pTriggerStep->orconf = orconf;
   99763   }else{
   99764     sqlite3IdListDelete(db, pColumn);
   99765   }
   99766   sqlite3ExprListDelete(db, pEList);
   99767   sqlite3SelectDelete(db, pSelect);
   99768 
   99769   return pTriggerStep;
   99770 }
   99771 
   99772 /*
   99773 ** Construct a trigger step that implements an UPDATE statement and return
   99774 ** a pointer to that trigger step.  The parser calls this routine when it
   99775 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   99776 */
   99777 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   99778   sqlite3 *db,         /* The database connection */
   99779   Token *pTableName,   /* Name of the table to be updated */
   99780   ExprList *pEList,    /* The SET clause: list of column and new values */
   99781   Expr *pWhere,        /* The WHERE clause */
   99782   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   99783 ){
   99784   TriggerStep *pTriggerStep;
   99785 
   99786   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   99787   if( pTriggerStep ){
   99788     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   99789     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   99790     pTriggerStep->orconf = orconf;
   99791   }
   99792   sqlite3ExprListDelete(db, pEList);
   99793   sqlite3ExprDelete(db, pWhere);
   99794   return pTriggerStep;
   99795 }
   99796 
   99797 /*
   99798 ** Construct a trigger step that implements a DELETE statement and return
   99799 ** a pointer to that trigger step.  The parser calls this routine when it
   99800 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   99801 */
   99802 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   99803   sqlite3 *db,            /* Database connection */
   99804   Token *pTableName,      /* The table from which rows are deleted */
   99805   Expr *pWhere            /* The WHERE clause */
   99806 ){
   99807   TriggerStep *pTriggerStep;
   99808 
   99809   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   99810   if( pTriggerStep ){
   99811     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   99812     pTriggerStep->orconf = OE_Default;
   99813   }
   99814   sqlite3ExprDelete(db, pWhere);
   99815   return pTriggerStep;
   99816 }
   99817 
   99818 /*
   99819 ** Recursively delete a Trigger structure
   99820 */
   99821 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   99822   if( pTrigger==0 ) return;
   99823   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   99824   sqlite3DbFree(db, pTrigger->zName);
   99825   sqlite3DbFree(db, pTrigger->table);
   99826   sqlite3ExprDelete(db, pTrigger->pWhen);
   99827   sqlite3IdListDelete(db, pTrigger->pColumns);
   99828   sqlite3DbFree(db, pTrigger);
   99829 }
   99830 
   99831 /*
   99832 ** This function is called to drop a trigger from the database schema.
   99833 **
   99834 ** This may be called directly from the parser and therefore identifies
   99835 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   99836 ** same job as this routine except it takes a pointer to the trigger
   99837 ** instead of the trigger name.
   99838 **/
   99839 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   99840   Trigger *pTrigger = 0;
   99841   int i;
   99842   const char *zDb;
   99843   const char *zName;
   99844   int nName;
   99845   sqlite3 *db = pParse->db;
   99846 
   99847   if( db->mallocFailed ) goto drop_trigger_cleanup;
   99848   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   99849     goto drop_trigger_cleanup;
   99850   }
   99851 
   99852   assert( pName->nSrc==1 );
   99853   zDb = pName->a[0].zDatabase;
   99854   zName = pName->a[0].zName;
   99855   nName = sqlite3Strlen30(zName);
   99856   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   99857   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   99858     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   99859     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   99860     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   99861     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   99862     if( pTrigger ) break;
   99863   }
   99864   if( !pTrigger ){
   99865     if( !noErr ){
   99866       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   99867     }else{
   99868       sqlite3CodeVerifyNamedSchema(pParse, zDb);
   99869     }
   99870     pParse->checkSchema = 1;
   99871     goto drop_trigger_cleanup;
   99872   }
   99873   sqlite3DropTriggerPtr(pParse, pTrigger);
   99874 
   99875 drop_trigger_cleanup:
   99876   sqlite3SrcListDelete(db, pName);
   99877 }
   99878 
   99879 /*
   99880 ** Return a pointer to the Table structure for the table that a trigger
   99881 ** is set on.
   99882 */
   99883 static Table *tableOfTrigger(Trigger *pTrigger){
   99884   int n = sqlite3Strlen30(pTrigger->table);
   99885   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   99886 }
   99887 
   99888 
   99889 /*
   99890 ** Drop a trigger given a pointer to that trigger.
   99891 */
   99892 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   99893   Table   *pTable;
   99894   Vdbe *v;
   99895   sqlite3 *db = pParse->db;
   99896   int iDb;
   99897 
   99898   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   99899   assert( iDb>=0 && iDb<db->nDb );
   99900   pTable = tableOfTrigger(pTrigger);
   99901   assert( pTable );
   99902   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   99903 #ifndef SQLITE_OMIT_AUTHORIZATION
   99904   {
   99905     int code = SQLITE_DROP_TRIGGER;
   99906     const char *zDb = db->aDb[iDb].zName;
   99907     const char *zTab = SCHEMA_TABLE(iDb);
   99908     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   99909     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   99910       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   99911       return;
   99912     }
   99913   }
   99914 #endif
   99915 
   99916   /* Generate code to destroy the database record of the trigger.
   99917   */
   99918   assert( pTable!=0 );
   99919   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   99920     int base;
   99921     static const VdbeOpList dropTrigger[] = {
   99922       { OP_Rewind,     0, ADDR(9),  0},
   99923       { OP_String8,    0, 1,        0}, /* 1 */
   99924       { OP_Column,     0, 1,        2},
   99925       { OP_Ne,         2, ADDR(8),  1},
   99926       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   99927       { OP_Column,     0, 0,        2},
   99928       { OP_Ne,         2, ADDR(8),  1},
   99929       { OP_Delete,     0, 0,        0},
   99930       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   99931     };
   99932 
   99933     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99934     sqlite3OpenMasterTable(pParse, iDb);
   99935     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
   99936     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
   99937     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   99938     sqlite3ChangeCookie(pParse, iDb);
   99939     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   99940     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   99941     if( pParse->nMem<3 ){
   99942       pParse->nMem = 3;
   99943     }
   99944   }
   99945 }
   99946 
   99947 /*
   99948 ** Remove a trigger from the hash tables of the sqlite* pointer.
   99949 */
   99950 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   99951   Trigger *pTrigger;
   99952   Hash *pHash;
   99953 
   99954   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99955   pHash = &(db->aDb[iDb].pSchema->trigHash);
   99956   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   99957   if( ALWAYS(pTrigger) ){
   99958     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   99959       Table *pTab = tableOfTrigger(pTrigger);
   99960       Trigger **pp;
   99961       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   99962       *pp = (*pp)->pNext;
   99963     }
   99964     sqlite3DeleteTrigger(db, pTrigger);
   99965     db->flags |= SQLITE_InternChanges;
   99966   }
   99967 }
   99968 
   99969 /*
   99970 ** pEList is the SET clause of an UPDATE statement.  Each entry
   99971 ** in pEList is of the format <id>=<expr>.  If any of the entries
   99972 ** in pEList have an <id> which matches an identifier in pIdList,
   99973 ** then return TRUE.  If pIdList==NULL, then it is considered a
   99974 ** wildcard that matches anything.  Likewise if pEList==NULL then
   99975 ** it matches anything so always return true.  Return false only
   99976 ** if there is no match.
   99977 */
   99978 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   99979   int e;
   99980   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   99981   for(e=0; e<pEList->nExpr; e++){
   99982     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   99983   }
   99984   return 0;
   99985 }
   99986 
   99987 /*
   99988 ** Return a list of all triggers on table pTab if there exists at least
   99989 ** one trigger that must be fired when an operation of type 'op' is
   99990 ** performed on the table, and, if that operation is an UPDATE, if at
   99991 ** least one of the columns in pChanges is being modified.
   99992 */
   99993 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   99994   Parse *pParse,          /* Parse context */
   99995   Table *pTab,            /* The table the contains the triggers */
   99996   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   99997   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   99998   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   99999 ){
   100000   int mask = 0;
   100001   Trigger *pList = 0;
   100002   Trigger *p;
   100003 
   100004   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
   100005     pList = sqlite3TriggerList(pParse, pTab);
   100006   }
   100007   assert( pList==0 || IsVirtual(pTab)==0 );
   100008   for(p=pList; p; p=p->pNext){
   100009     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   100010       mask |= p->tr_tm;
   100011     }
   100012   }
   100013   if( pMask ){
   100014     *pMask = mask;
   100015   }
   100016   return (mask ? pList : 0);
   100017 }
   100018 
   100019 /*
   100020 ** Convert the pStep->target token into a SrcList and return a pointer
   100021 ** to that SrcList.
   100022 **
   100023 ** This routine adds a specific database name, if needed, to the target when
   100024 ** forming the SrcList.  This prevents a trigger in one database from
   100025 ** referring to a target in another database.  An exception is when the
   100026 ** trigger is in TEMP in which case it can refer to any other database it
   100027 ** wants.
   100028 */
   100029 static SrcList *targetSrcList(
   100030   Parse *pParse,       /* The parsing context */
   100031   TriggerStep *pStep   /* The trigger containing the target token */
   100032 ){
   100033   int iDb;             /* Index of the database to use */
   100034   SrcList *pSrc;       /* SrcList to be returned */
   100035 
   100036   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   100037   if( pSrc ){
   100038     assert( pSrc->nSrc>0 );
   100039     assert( pSrc->a!=0 );
   100040     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   100041     if( iDb==0 || iDb>=2 ){
   100042       sqlite3 *db = pParse->db;
   100043       assert( iDb<pParse->db->nDb );
   100044       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   100045     }
   100046   }
   100047   return pSrc;
   100048 }
   100049 
   100050 /*
   100051 ** Generate VDBE code for the statements inside the body of a single
   100052 ** trigger.
   100053 */
   100054 static int codeTriggerProgram(
   100055   Parse *pParse,            /* The parser context */
   100056   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   100057   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   100058 ){
   100059   TriggerStep *pStep;
   100060   Vdbe *v = pParse->pVdbe;
   100061   sqlite3 *db = pParse->db;
   100062 
   100063   assert( pParse->pTriggerTab && pParse->pToplevel );
   100064   assert( pStepList );
   100065   assert( v!=0 );
   100066   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   100067     /* Figure out the ON CONFLICT policy that will be used for this step
   100068     ** of the trigger program. If the statement that caused this trigger
   100069     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   100070     ** the ON CONFLICT policy that was specified as part of the trigger
   100071     ** step statement. Example:
   100072     **
   100073     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   100074     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   100075     **   END;
   100076     **
   100077     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   100078     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   100079     */
   100080     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   100081 
   100082     switch( pStep->op ){
   100083       case TK_UPDATE: {
   100084         sqlite3Update(pParse,
   100085           targetSrcList(pParse, pStep),
   100086           sqlite3ExprListDup(db, pStep->pExprList, 0),
   100087           sqlite3ExprDup(db, pStep->pWhere, 0),
   100088           pParse->eOrconf
   100089         );
   100090         break;
   100091       }
   100092       case TK_INSERT: {
   100093         sqlite3Insert(pParse,
   100094           targetSrcList(pParse, pStep),
   100095           sqlite3ExprListDup(db, pStep->pExprList, 0),
   100096           sqlite3SelectDup(db, pStep->pSelect, 0),
   100097           sqlite3IdListDup(db, pStep->pIdList),
   100098           pParse->eOrconf
   100099         );
   100100         break;
   100101       }
   100102       case TK_DELETE: {
   100103         sqlite3DeleteFrom(pParse,
   100104           targetSrcList(pParse, pStep),
   100105           sqlite3ExprDup(db, pStep->pWhere, 0)
   100106         );
   100107         break;
   100108       }
   100109       default: assert( pStep->op==TK_SELECT ); {
   100110         SelectDest sDest;
   100111         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   100112         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   100113         sqlite3Select(pParse, pSelect, &sDest);
   100114         sqlite3SelectDelete(db, pSelect);
   100115         break;
   100116       }
   100117     }
   100118     if( pStep->op!=TK_SELECT ){
   100119       sqlite3VdbeAddOp0(v, OP_ResetCount);
   100120     }
   100121   }
   100122 
   100123   return 0;
   100124 }
   100125 
   100126 #ifdef SQLITE_DEBUG
   100127 /*
   100128 ** This function is used to add VdbeComment() annotations to a VDBE
   100129 ** program. It is not used in production code, only for debugging.
   100130 */
   100131 static const char *onErrorText(int onError){
   100132   switch( onError ){
   100133     case OE_Abort:    return "abort";
   100134     case OE_Rollback: return "rollback";
   100135     case OE_Fail:     return "fail";
   100136     case OE_Replace:  return "replace";
   100137     case OE_Ignore:   return "ignore";
   100138     case OE_Default:  return "default";
   100139   }
   100140   return "n/a";
   100141 }
   100142 #endif
   100143 
   100144 /*
   100145 ** Parse context structure pFrom has just been used to create a sub-vdbe
   100146 ** (trigger program). If an error has occurred, transfer error information
   100147 ** from pFrom to pTo.
   100148 */
   100149 static void transferParseError(Parse *pTo, Parse *pFrom){
   100150   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   100151   assert( pTo->zErrMsg==0 || pTo->nErr );
   100152   if( pTo->nErr==0 ){
   100153     pTo->zErrMsg = pFrom->zErrMsg;
   100154     pTo->nErr = pFrom->nErr;
   100155   }else{
   100156     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   100157   }
   100158 }
   100159 
   100160 /*
   100161 ** Create and populate a new TriggerPrg object with a sub-program
   100162 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   100163 */
   100164 static TriggerPrg *codeRowTrigger(
   100165   Parse *pParse,       /* Current parse context */
   100166   Trigger *pTrigger,   /* Trigger to code */
   100167   Table *pTab,         /* The table pTrigger is attached to */
   100168   int orconf           /* ON CONFLICT policy to code trigger program with */
   100169 ){
   100170   Parse *pTop = sqlite3ParseToplevel(pParse);
   100171   sqlite3 *db = pParse->db;   /* Database handle */
   100172   TriggerPrg *pPrg;           /* Value to return */
   100173   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   100174   Vdbe *v;                    /* Temporary VM */
   100175   NameContext sNC;            /* Name context for sub-vdbe */
   100176   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   100177   Parse *pSubParse;           /* Parse context for sub-vdbe */
   100178   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   100179 
   100180   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   100181   assert( pTop->pVdbe );
   100182 
   100183   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   100184   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   100185   ** list of the top-level Parse object sooner rather than later.  */
   100186   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   100187   if( !pPrg ) return 0;
   100188   pPrg->pNext = pTop->pTriggerPrg;
   100189   pTop->pTriggerPrg = pPrg;
   100190   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   100191   if( !pProgram ) return 0;
   100192   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   100193   pPrg->pTrigger = pTrigger;
   100194   pPrg->orconf = orconf;
   100195   pPrg->aColmask[0] = 0xffffffff;
   100196   pPrg->aColmask[1] = 0xffffffff;
   100197 
   100198   /* Allocate and populate a new Parse context to use for coding the
   100199   ** trigger sub-program.  */
   100200   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   100201   if( !pSubParse ) return 0;
   100202   memset(&sNC, 0, sizeof(sNC));
   100203   sNC.pParse = pSubParse;
   100204   pSubParse->db = db;
   100205   pSubParse->pTriggerTab = pTab;
   100206   pSubParse->pToplevel = pTop;
   100207   pSubParse->zAuthContext = pTrigger->zName;
   100208   pSubParse->eTriggerOp = pTrigger->op;
   100209   pSubParse->nQueryLoop = pParse->nQueryLoop;
   100210 
   100211   v = sqlite3GetVdbe(pSubParse);
   100212   if( v ){
   100213     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   100214       pTrigger->zName, onErrorText(orconf),
   100215       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   100216         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   100217         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   100218         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   100219       pTab->zName
   100220     ));
   100221 #ifndef SQLITE_OMIT_TRACE
   100222     sqlite3VdbeChangeP4(v, -1,
   100223       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   100224     );
   100225 #endif
   100226 
   100227     /* If one was specified, code the WHEN clause. If it evaluates to false
   100228     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   100229     ** OP_Halt inserted at the end of the program.  */
   100230     if( pTrigger->pWhen ){
   100231       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   100232       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   100233        && db->mallocFailed==0
   100234       ){
   100235         iEndTrigger = sqlite3VdbeMakeLabel(v);
   100236         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   100237       }
   100238       sqlite3ExprDelete(db, pWhen);
   100239     }
   100240 
   100241     /* Code the trigger program into the sub-vdbe. */
   100242     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   100243 
   100244     /* Insert an OP_Halt at the end of the sub-program. */
   100245     if( iEndTrigger ){
   100246       sqlite3VdbeResolveLabel(v, iEndTrigger);
   100247     }
   100248     sqlite3VdbeAddOp0(v, OP_Halt);
   100249     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   100250 
   100251     transferParseError(pParse, pSubParse);
   100252     if( db->mallocFailed==0 ){
   100253       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   100254     }
   100255     pProgram->nMem = pSubParse->nMem;
   100256     pProgram->nCsr = pSubParse->nTab;
   100257     pProgram->nOnce = pSubParse->nOnce;
   100258     pProgram->token = (void *)pTrigger;
   100259     pPrg->aColmask[0] = pSubParse->oldmask;
   100260     pPrg->aColmask[1] = pSubParse->newmask;
   100261     sqlite3VdbeDelete(v);
   100262   }
   100263 
   100264   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   100265   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   100266   sqlite3StackFree(db, pSubParse);
   100267 
   100268   return pPrg;
   100269 }
   100270 
   100271 /*
   100272 ** Return a pointer to a TriggerPrg object containing the sub-program for
   100273 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   100274 ** TriggerPrg object exists, a new object is allocated and populated before
   100275 ** being returned.
   100276 */
   100277 static TriggerPrg *getRowTrigger(
   100278   Parse *pParse,       /* Current parse context */
   100279   Trigger *pTrigger,   /* Trigger to code */
   100280   Table *pTab,         /* The table trigger pTrigger is attached to */
   100281   int orconf           /* ON CONFLICT algorithm. */
   100282 ){
   100283   Parse *pRoot = sqlite3ParseToplevel(pParse);
   100284   TriggerPrg *pPrg;
   100285 
   100286   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   100287 
   100288   /* It may be that this trigger has already been coded (or is in the
   100289   ** process of being coded). If this is the case, then an entry with
   100290   ** a matching TriggerPrg.pTrigger field will be present somewhere
   100291   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   100292   for(pPrg=pRoot->pTriggerPrg;
   100293       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   100294       pPrg=pPrg->pNext
   100295   );
   100296 
   100297   /* If an existing TriggerPrg could not be located, create a new one. */
   100298   if( !pPrg ){
   100299     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   100300   }
   100301 
   100302   return pPrg;
   100303 }
   100304 
   100305 /*
   100306 ** Generate code for the trigger program associated with trigger p on
   100307 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   100308 ** function are the same as those described in the header function for
   100309 ** sqlite3CodeRowTrigger()
   100310 */
   100311 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   100312   Parse *pParse,       /* Parse context */
   100313   Trigger *p,          /* Trigger to code */
   100314   Table *pTab,         /* The table to code triggers from */
   100315   int reg,             /* Reg array containing OLD.* and NEW.* values */
   100316   int orconf,          /* ON CONFLICT policy */
   100317   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   100318 ){
   100319   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   100320   TriggerPrg *pPrg;
   100321   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   100322   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   100323 
   100324   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   100325   ** is a pointer to the sub-vdbe containing the trigger program.  */
   100326   if( pPrg ){
   100327     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   100328 
   100329     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   100330     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   100331     VdbeComment(
   100332         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   100333 
   100334     /* Set the P5 operand of the OP_Program instruction to non-zero if
   100335     ** recursive invocation of this trigger program is disallowed. Recursive
   100336     ** invocation is disallowed if (a) the sub-program is really a trigger,
   100337     ** not a foreign key action, and (b) the flag to enable recursive triggers
   100338     ** is clear.  */
   100339     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   100340   }
   100341 }
   100342 
   100343 /*
   100344 ** This is called to code the required FOR EACH ROW triggers for an operation
   100345 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   100346 ** is given by the op paramater. The tr_tm parameter determines whether the
   100347 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   100348 ** parameter pChanges is passed the list of columns being modified.
   100349 **
   100350 ** If there are no triggers that fire at the specified time for the specified
   100351 ** operation on pTab, this function is a no-op.
   100352 **
   100353 ** The reg argument is the address of the first in an array of registers
   100354 ** that contain the values substituted for the new.* and old.* references
   100355 ** in the trigger program. If N is the number of columns in table pTab
   100356 ** (a copy of pTab->nCol), then registers are populated as follows:
   100357 **
   100358 **   Register       Contains
   100359 **   ------------------------------------------------------
   100360 **   reg+0          OLD.rowid
   100361 **   reg+1          OLD.* value of left-most column of pTab
   100362 **   ...            ...
   100363 **   reg+N          OLD.* value of right-most column of pTab
   100364 **   reg+N+1        NEW.rowid
   100365 **   reg+N+2        OLD.* value of left-most column of pTab
   100366 **   ...            ...
   100367 **   reg+N+N+1      NEW.* value of right-most column of pTab
   100368 **
   100369 ** For ON DELETE triggers, the registers containing the NEW.* values will
   100370 ** never be accessed by the trigger program, so they are not allocated or
   100371 ** populated by the caller (there is no data to populate them with anyway).
   100372 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   100373 ** are never accessed, and so are not allocated by the caller. So, for an
   100374 ** ON INSERT trigger, the value passed to this function as parameter reg
   100375 ** is not a readable register, although registers (reg+N) through
   100376 ** (reg+N+N+1) are.
   100377 **
   100378 ** Parameter orconf is the default conflict resolution algorithm for the
   100379 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   100380 ** is the instruction that control should jump to if a trigger program
   100381 ** raises an IGNORE exception.
   100382 */
   100383 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   100384   Parse *pParse,       /* Parse context */
   100385   Trigger *pTrigger,   /* List of triggers on table pTab */
   100386   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   100387   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   100388   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   100389   Table *pTab,         /* The table to code triggers from */
   100390   int reg,             /* The first in an array of registers (see above) */
   100391   int orconf,          /* ON CONFLICT policy */
   100392   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   100393 ){
   100394   Trigger *p;          /* Used to iterate through pTrigger list */
   100395 
   100396   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   100397   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   100398   assert( (op==TK_UPDATE)==(pChanges!=0) );
   100399 
   100400   for(p=pTrigger; p; p=p->pNext){
   100401 
   100402     /* Sanity checking:  The schema for the trigger and for the table are
   100403     ** always defined.  The trigger must be in the same schema as the table
   100404     ** or else it must be a TEMP trigger. */
   100405     assert( p->pSchema!=0 );
   100406     assert( p->pTabSchema!=0 );
   100407     assert( p->pSchema==p->pTabSchema
   100408          || p->pSchema==pParse->db->aDb[1].pSchema );
   100409 
   100410     /* Determine whether we should code this trigger */
   100411     if( p->op==op
   100412      && p->tr_tm==tr_tm
   100413      && checkColumnOverlap(p->pColumns, pChanges)
   100414     ){
   100415       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   100416     }
   100417   }
   100418 }
   100419 
   100420 /*
   100421 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   100422 ** This function returns a 32-bit bitmask indicating which columns of the
   100423 ** old.* or new.* tables actually are used by triggers. This information
   100424 ** may be used by the caller, for example, to avoid having to load the entire
   100425 ** old.* record into memory when executing an UPDATE or DELETE command.
   100426 **
   100427 ** Bit 0 of the returned mask is set if the left-most column of the
   100428 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   100429 ** the second leftmost column value is required, and so on. If there
   100430 ** are more than 32 columns in the table, and at least one of the columns
   100431 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   100432 **
   100433 ** It is not possible to determine if the old.rowid or new.rowid column is
   100434 ** accessed by triggers. The caller must always assume that it is.
   100435 **
   100436 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   100437 ** applies to the old.* table. If 1, the new.* table.
   100438 **
   100439 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   100440 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   100441 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   100442 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   100443 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   100444 */
   100445 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   100446   Parse *pParse,       /* Parse context */
   100447   Trigger *pTrigger,   /* List of triggers on table pTab */
   100448   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   100449   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   100450   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   100451   Table *pTab,         /* The table to code triggers from */
   100452   int orconf           /* Default ON CONFLICT policy for trigger steps */
   100453 ){
   100454   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   100455   u32 mask = 0;
   100456   Trigger *p;
   100457 
   100458   assert( isNew==1 || isNew==0 );
   100459   for(p=pTrigger; p; p=p->pNext){
   100460     if( p->op==op && (tr_tm&p->tr_tm)
   100461      && checkColumnOverlap(p->pColumns,pChanges)
   100462     ){
   100463       TriggerPrg *pPrg;
   100464       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   100465       if( pPrg ){
   100466         mask |= pPrg->aColmask[isNew];
   100467       }
   100468     }
   100469   }
   100470 
   100471   return mask;
   100472 }
   100473 
   100474 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   100475 
   100476 /************** End of trigger.c *********************************************/
   100477 /************** Begin file update.c ******************************************/
   100478 /*
   100479 ** 2001 September 15
   100480 **
   100481 ** The author disclaims copyright to this source code.  In place of
   100482 ** a legal notice, here is a blessing:
   100483 **
   100484 **    May you do good and not evil.
   100485 **    May you find forgiveness for yourself and forgive others.
   100486 **    May you share freely, never taking more than you give.
   100487 **
   100488 *************************************************************************
   100489 ** This file contains C code routines that are called by the parser
   100490 ** to handle UPDATE statements.
   100491 */
   100492 
   100493 #ifndef SQLITE_OMIT_VIRTUALTABLE
   100494 /* Forward declaration */
   100495 static void updateVirtualTable(
   100496   Parse *pParse,       /* The parsing context */
   100497   SrcList *pSrc,       /* The virtual table to be modified */
   100498   Table *pTab,         /* The virtual table */
   100499   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   100500   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   100501   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   100502   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   100503   int onError          /* ON CONFLICT strategy */
   100504 );
   100505 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   100506 
   100507 /*
   100508 ** The most recently coded instruction was an OP_Column to retrieve the
   100509 ** i-th column of table pTab. This routine sets the P4 parameter of the
   100510 ** OP_Column to the default value, if any.
   100511 **
   100512 ** The default value of a column is specified by a DEFAULT clause in the
   100513 ** column definition. This was either supplied by the user when the table
   100514 ** was created, or added later to the table definition by an ALTER TABLE
   100515 ** command. If the latter, then the row-records in the table btree on disk
   100516 ** may not contain a value for the column and the default value, taken
   100517 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   100518 ** If the former, then all row-records are guaranteed to include a value
   100519 ** for the column and the P4 value is not required.
   100520 **
   100521 ** Column definitions created by an ALTER TABLE command may only have
   100522 ** literal default values specified: a number, null or a string. (If a more
   100523 ** complicated default expression value was provided, it is evaluated
   100524 ** when the ALTER TABLE is executed and one of the literal values written
   100525 ** into the sqlite_master table.)
   100526 **
   100527 ** Therefore, the P4 parameter is only required if the default value for
   100528 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   100529 ** function is capable of transforming these types of expressions into
   100530 ** sqlite3_value objects.
   100531 **
   100532 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   100533 ** on register iReg. This is used when an equivalent integer value is
   100534 ** stored in place of an 8-byte floating point value in order to save
   100535 ** space.
   100536 */
   100537 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   100538   assert( pTab!=0 );
   100539   if( !pTab->pSelect ){
   100540     sqlite3_value *pValue;
   100541     u8 enc = ENC(sqlite3VdbeDb(v));
   100542     Column *pCol = &pTab->aCol[i];
   100543     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   100544     assert( i<pTab->nCol );
   100545     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   100546                          pCol->affinity, &pValue);
   100547     if( pValue ){
   100548       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   100549     }
   100550 #ifndef SQLITE_OMIT_FLOATING_POINT
   100551     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   100552       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   100553     }
   100554 #endif
   100555   }
   100556 }
   100557 
   100558 /*
   100559 ** Process an UPDATE statement.
   100560 **
   100561 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   100562 **          \_______/ \________/     \______/       \________________/
   100563 *            onError   pTabList      pChanges             pWhere
   100564 */
   100565 SQLITE_PRIVATE void sqlite3Update(
   100566   Parse *pParse,         /* The parser context */
   100567   SrcList *pTabList,     /* The table in which we should change things */
   100568   ExprList *pChanges,    /* Things to be changed */
   100569   Expr *pWhere,          /* The WHERE clause.  May be null */
   100570   int onError            /* How to handle constraint errors */
   100571 ){
   100572   int i, j;              /* Loop counters */
   100573   Table *pTab;           /* The table to be updated */
   100574   int addr = 0;          /* VDBE instruction address of the start of the loop */
   100575   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   100576   Vdbe *v;               /* The virtual database engine */
   100577   Index *pIdx;           /* For looping over indices */
   100578   int nIdx;              /* Number of indices that need updating */
   100579   int iCur;              /* VDBE Cursor number of pTab */
   100580   sqlite3 *db;           /* The database structure */
   100581   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   100582   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   100583                          ** an expression for the i-th column of the table.
   100584                          ** aXRef[i]==-1 if the i-th column is not changed. */
   100585   int chngRowid;         /* True if the record number is being changed */
   100586   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   100587   int openAll = 0;       /* True if all indices need to be opened */
   100588   AuthContext sContext;  /* The authorization context */
   100589   NameContext sNC;       /* The name-context to resolve expressions in */
   100590   int iDb;               /* Database containing the table being updated */
   100591   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   100592   int hasFK;             /* True if foreign key processing is required */
   100593 
   100594 #ifndef SQLITE_OMIT_TRIGGER
   100595   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   100596   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   100597   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   100598 #endif
   100599   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   100600 
   100601   /* Register Allocations */
   100602   int regRowCount = 0;   /* A count of rows changed */
   100603   int regOldRowid;       /* The old rowid */
   100604   int regNewRowid;       /* The new rowid */
   100605   int regNew;            /* Content of the NEW.* table in triggers */
   100606   int regOld = 0;        /* Content of OLD.* table in triggers */
   100607   int regRowSet = 0;     /* Rowset of rows to be updated */
   100608 
   100609   memset(&sContext, 0, sizeof(sContext));
   100610   db = pParse->db;
   100611   if( pParse->nErr || db->mallocFailed ){
   100612     goto update_cleanup;
   100613   }
   100614   assert( pTabList->nSrc==1 );
   100615 
   100616   /* Locate the table which we want to update.
   100617   */
   100618   pTab = sqlite3SrcListLookup(pParse, pTabList);
   100619   if( pTab==0 ) goto update_cleanup;
   100620   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   100621 
   100622   /* Figure out if we have any triggers and if the table being
   100623   ** updated is a view.
   100624   */
   100625 #ifndef SQLITE_OMIT_TRIGGER
   100626   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   100627   isView = pTab->pSelect!=0;
   100628   assert( pTrigger || tmask==0 );
   100629 #else
   100630 # define pTrigger 0
   100631 # define isView 0
   100632 # define tmask 0
   100633 #endif
   100634 #ifdef SQLITE_OMIT_VIEW
   100635 # undef isView
   100636 # define isView 0
   100637 #endif
   100638 
   100639   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   100640     goto update_cleanup;
   100641   }
   100642   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   100643     goto update_cleanup;
   100644   }
   100645   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
   100646   if( aXRef==0 ) goto update_cleanup;
   100647   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   100648 
   100649   /* Allocate a cursors for the main database table and for all indices.
   100650   ** The index cursors might not be used, but if they are used they
   100651   ** need to occur right after the database cursor.  So go ahead and
   100652   ** allocate enough space, just in case.
   100653   */
   100654   pTabList->a[0].iCursor = iCur = pParse->nTab++;
   100655   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100656     pParse->nTab++;
   100657   }
   100658 
   100659   /* Initialize the name-context */
   100660   memset(&sNC, 0, sizeof(sNC));
   100661   sNC.pParse = pParse;
   100662   sNC.pSrcList = pTabList;
   100663 
   100664   /* Resolve the column names in all the expressions of the
   100665   ** of the UPDATE statement.  Also find the column index
   100666   ** for each column to be updated in the pChanges array.  For each
   100667   ** column to be updated, make sure we have authorization to change
   100668   ** that column.
   100669   */
   100670   chngRowid = 0;
   100671   for(i=0; i<pChanges->nExpr; i++){
   100672     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   100673       goto update_cleanup;
   100674     }
   100675     for(j=0; j<pTab->nCol; j++){
   100676       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   100677         if( j==pTab->iPKey ){
   100678           chngRowid = 1;
   100679           pRowidExpr = pChanges->a[i].pExpr;
   100680         }
   100681         aXRef[j] = i;
   100682         break;
   100683       }
   100684     }
   100685     if( j>=pTab->nCol ){
   100686       if( sqlite3IsRowid(pChanges->a[i].zName) ){
   100687         chngRowid = 1;
   100688         pRowidExpr = pChanges->a[i].pExpr;
   100689       }else{
   100690         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   100691         pParse->checkSchema = 1;
   100692         goto update_cleanup;
   100693       }
   100694     }
   100695 #ifndef SQLITE_OMIT_AUTHORIZATION
   100696     {
   100697       int rc;
   100698       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   100699                            pTab->aCol[j].zName, db->aDb[iDb].zName);
   100700       if( rc==SQLITE_DENY ){
   100701         goto update_cleanup;
   100702       }else if( rc==SQLITE_IGNORE ){
   100703         aXRef[j] = -1;
   100704       }
   100705     }
   100706 #endif
   100707   }
   100708 
   100709   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
   100710 
   100711   /* Allocate memory for the array aRegIdx[].  There is one entry in the
   100712   ** array for each index associated with table being updated.  Fill in
   100713   ** the value with a register number for indices that are to be used
   100714   ** and with zero for unused indices.
   100715   */
   100716   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   100717   if( nIdx>0 ){
   100718     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   100719     if( aRegIdx==0 ) goto update_cleanup;
   100720   }
   100721   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100722     int reg;
   100723     if( hasFK || chngRowid ){
   100724       reg = ++pParse->nMem;
   100725     }else{
   100726       reg = 0;
   100727       for(i=0; i<pIdx->nColumn; i++){
   100728         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   100729           reg = ++pParse->nMem;
   100730           break;
   100731         }
   100732       }
   100733     }
   100734     aRegIdx[j] = reg;
   100735   }
   100736 
   100737   /* Begin generating code. */
   100738   v = sqlite3GetVdbe(pParse);
   100739   if( v==0 ) goto update_cleanup;
   100740   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   100741   sqlite3BeginWriteOperation(pParse, 1, iDb);
   100742 
   100743 #ifndef SQLITE_OMIT_VIRTUALTABLE
   100744   /* Virtual tables must be handled separately */
   100745   if( IsVirtual(pTab) ){
   100746     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   100747                        pWhere, onError);
   100748     pWhere = 0;
   100749     pTabList = 0;
   100750     goto update_cleanup;
   100751   }
   100752 #endif
   100753 
   100754   /* Allocate required registers. */
   100755   regRowSet = ++pParse->nMem;
   100756   regOldRowid = regNewRowid = ++pParse->nMem;
   100757   if( pTrigger || hasFK ){
   100758     regOld = pParse->nMem + 1;
   100759     pParse->nMem += pTab->nCol;
   100760   }
   100761   if( chngRowid || pTrigger || hasFK ){
   100762     regNewRowid = ++pParse->nMem;
   100763   }
   100764   regNew = pParse->nMem + 1;
   100765   pParse->nMem += pTab->nCol;
   100766 
   100767   /* Start the view context. */
   100768   if( isView ){
   100769     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   100770   }
   100771 
   100772   /* If we are trying to update a view, realize that view into
   100773   ** a ephemeral table.
   100774   */
   100775 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   100776   if( isView ){
   100777     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   100778   }
   100779 #endif
   100780 
   100781   /* Resolve the column names in all the expressions in the
   100782   ** WHERE clause.
   100783   */
   100784   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   100785     goto update_cleanup;
   100786   }
   100787 
   100788   /* Begin the database scan
   100789   */
   100790   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
   100791   pWInfo = sqlite3WhereBegin(
   100792       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
   100793   );
   100794   if( pWInfo==0 ) goto update_cleanup;
   100795   okOnePass = pWInfo->okOnePass;
   100796 
   100797   /* Remember the rowid of every item to be updated.
   100798   */
   100799   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
   100800   if( !okOnePass ){
   100801     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   100802   }
   100803 
   100804   /* End the database scan loop.
   100805   */
   100806   sqlite3WhereEnd(pWInfo);
   100807 
   100808   /* Initialize the count of updated rows
   100809   */
   100810   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   100811     regRowCount = ++pParse->nMem;
   100812     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   100813   }
   100814 
   100815   if( !isView ){
   100816     /*
   100817     ** Open every index that needs updating.  Note that if any
   100818     ** index could potentially invoke a REPLACE conflict resolution
   100819     ** action, then we need to open all indices because we might need
   100820     ** to be deleting some records.
   100821     */
   100822     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
   100823     if( onError==OE_Replace ){
   100824       openAll = 1;
   100825     }else{
   100826       openAll = 0;
   100827       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100828         if( pIdx->onError==OE_Replace ){
   100829           openAll = 1;
   100830           break;
   100831         }
   100832       }
   100833     }
   100834     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   100835       assert( aRegIdx );
   100836       if( openAll || aRegIdx[i]>0 ){
   100837         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   100838         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
   100839                        (char*)pKey, P4_KEYINFO_HANDOFF);
   100840         assert( pParse->nTab>iCur+i+1 );
   100841       }
   100842     }
   100843   }
   100844 
   100845   /* Top of the update loop */
   100846   if( okOnePass ){
   100847     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   100848     addr = sqlite3VdbeAddOp0(v, OP_Goto);
   100849     sqlite3VdbeJumpHere(v, a1);
   100850   }else{
   100851     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
   100852   }
   100853 
   100854   /* Make cursor iCur point to the record that is being updated. If
   100855   ** this record does not exist for some reason (deleted by a trigger,
   100856   ** for example, then jump to the next iteration of the RowSet loop.  */
   100857   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   100858 
   100859   /* If the record number will change, set register regNewRowid to
   100860   ** contain the new value. If the record number is not being modified,
   100861   ** then regNewRowid is the same register as regOldRowid, which is
   100862   ** already populated.  */
   100863   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
   100864   if( chngRowid ){
   100865     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   100866     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   100867   }
   100868 
   100869   /* If there are triggers on this table, populate an array of registers
   100870   ** with the required old.* column data.  */
   100871   if( hasFK || pTrigger ){
   100872     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   100873     oldmask |= sqlite3TriggerColmask(pParse,
   100874         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   100875     );
   100876     for(i=0; i<pTab->nCol; i++){
   100877       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
   100878         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
   100879       }else{
   100880         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   100881       }
   100882     }
   100883     if( chngRowid==0 ){
   100884       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   100885     }
   100886   }
   100887 
   100888   /* Populate the array of registers beginning at regNew with the new
   100889   ** row data. This array is used to check constaints, create the new
   100890   ** table and index records, and as the values for any new.* references
   100891   ** made by triggers.
   100892   **
   100893   ** If there are one or more BEFORE triggers, then do not populate the
   100894   ** registers associated with columns that are (a) not modified by
   100895   ** this UPDATE statement and (b) not accessed by new.* references. The
   100896   ** values for registers not modified by the UPDATE must be reloaded from
   100897   ** the database after the BEFORE triggers are fired anyway (as the trigger
   100898   ** may have modified them). So not loading those that are not going to
   100899   ** be used eliminates some redundant opcodes.
   100900   */
   100901   newmask = sqlite3TriggerColmask(
   100902       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   100903   );
   100904   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
   100905   for(i=0; i<pTab->nCol; i++){
   100906     if( i==pTab->iPKey ){
   100907       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
   100908     }else{
   100909       j = aXRef[i];
   100910       if( j>=0 ){
   100911         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   100912       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
   100913         /* This branch loads the value of a column that will not be changed
   100914         ** into a register. This is done if there are no BEFORE triggers, or
   100915         ** if there are one or more BEFORE triggers that use this value via
   100916         ** a new.* reference in a trigger program.
   100917         */
   100918         testcase( i==31 );
   100919         testcase( i==32 );
   100920         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   100921         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   100922       }
   100923     }
   100924   }
   100925 
   100926   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   100927   ** verified. One could argue that this is wrong.
   100928   */
   100929   if( tmask&TRIGGER_BEFORE ){
   100930     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
   100931     sqlite3TableAffinityStr(v, pTab);
   100932     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   100933         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
   100934 
   100935     /* The row-trigger may have deleted the row being updated. In this
   100936     ** case, jump to the next row. No updates or AFTER triggers are
   100937     ** required. This behaviour - what happens when the row being updated
   100938     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   100939     ** documentation.
   100940     */
   100941     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   100942 
   100943     /* If it did not delete it, the row-trigger may still have modified
   100944     ** some of the columns of the row being updated. Load the values for
   100945     ** all columns not modified by the update statement into their
   100946     ** registers in case this has happened.
   100947     */
   100948     for(i=0; i<pTab->nCol; i++){
   100949       if( aXRef[i]<0 && i!=pTab->iPKey ){
   100950         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   100951         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   100952       }
   100953     }
   100954   }
   100955 
   100956   if( !isView ){
   100957     int j1;                       /* Address of jump instruction */
   100958 
   100959     /* Do constraint checks. */
   100960     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
   100961         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
   100962 
   100963     /* Do FK constraint checks. */
   100964     if( hasFK ){
   100965       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
   100966     }
   100967 
   100968     /* Delete the index entries associated with the current record.  */
   100969     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   100970     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
   100971 
   100972     /* If changing the record number, delete the old record.  */
   100973     if( hasFK || chngRowid ){
   100974       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
   100975     }
   100976     sqlite3VdbeJumpHere(v, j1);
   100977 
   100978     if( hasFK ){
   100979       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
   100980     }
   100981 
   100982     /* Insert the new index entries and the new record. */
   100983     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
   100984 
   100985     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   100986     ** handle rows (possibly in other tables) that refer via a foreign key
   100987     ** to the row just updated. */
   100988     if( hasFK ){
   100989       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
   100990     }
   100991   }
   100992 
   100993   /* Increment the row counter
   100994   */
   100995   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   100996     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   100997   }
   100998 
   100999   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   101000       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
   101001 
   101002   /* Repeat the above with the next record to be updated, until
   101003   ** all record selected by the WHERE clause have been updated.
   101004   */
   101005   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   101006   sqlite3VdbeJumpHere(v, addr);
   101007 
   101008   /* Close all tables */
   101009   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   101010     assert( aRegIdx );
   101011     if( openAll || aRegIdx[i]>0 ){
   101012       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
   101013     }
   101014   }
   101015   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
   101016 
   101017   /* Update the sqlite_sequence table by storing the content of the
   101018   ** maximum rowid counter values recorded while inserting into
   101019   ** autoincrement tables.
   101020   */
   101021   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   101022     sqlite3AutoincrementEnd(pParse);
   101023   }
   101024 
   101025   /*
   101026   ** Return the number of rows that were changed. If this routine is
   101027   ** generating code because of a call to sqlite3NestedParse(), do not
   101028   ** invoke the callback function.
   101029   */
   101030   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   101031     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   101032     sqlite3VdbeSetNumCols(v, 1);
   101033     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   101034   }
   101035 
   101036 update_cleanup:
   101037   sqlite3AuthContextPop(&sContext);
   101038   sqlite3DbFree(db, aRegIdx);
   101039   sqlite3DbFree(db, aXRef);
   101040   sqlite3SrcListDelete(db, pTabList);
   101041   sqlite3ExprListDelete(db, pChanges);
   101042   sqlite3ExprDelete(db, pWhere);
   101043   return;
   101044 }
   101045 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   101046 ** thely may interfere with compilation of other functions in this file
   101047 ** (or in another file, if this file becomes part of the amalgamation).  */
   101048 #ifdef isView
   101049  #undef isView
   101050 #endif
   101051 #ifdef pTrigger
   101052  #undef pTrigger
   101053 #endif
   101054 
   101055 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101056 /*
   101057 ** Generate code for an UPDATE of a virtual table.
   101058 **
   101059 ** The strategy is that we create an ephemerial table that contains
   101060 ** for each row to be changed:
   101061 **
   101062 **   (A)  The original rowid of that row.
   101063 **   (B)  The revised rowid for the row. (note1)
   101064 **   (C)  The content of every column in the row.
   101065 **
   101066 ** Then we loop over this ephemeral table and for each row in
   101067 ** the ephermeral table call VUpdate.
   101068 **
   101069 ** When finished, drop the ephemeral table.
   101070 **
   101071 ** (note1) Actually, if we know in advance that (A) is always the same
   101072 ** as (B) we only store (A), then duplicate (A) when pulling
   101073 ** it out of the ephemeral table before calling VUpdate.
   101074 */
   101075 static void updateVirtualTable(
   101076   Parse *pParse,       /* The parsing context */
   101077   SrcList *pSrc,       /* The virtual table to be modified */
   101078   Table *pTab,         /* The virtual table */
   101079   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   101080   Expr *pRowid,        /* Expression used to recompute the rowid */
   101081   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   101082   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   101083   int onError          /* ON CONFLICT strategy */
   101084 ){
   101085   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   101086   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   101087   Select *pSelect = 0;      /* The SELECT statement */
   101088   Expr *pExpr;              /* Temporary expression */
   101089   int ephemTab;             /* Table holding the result of the SELECT */
   101090   int i;                    /* Loop counter */
   101091   int addr;                 /* Address of top of loop */
   101092   int iReg;                 /* First register in set passed to OP_VUpdate */
   101093   sqlite3 *db = pParse->db; /* Database connection */
   101094   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   101095   SelectDest dest;
   101096 
   101097   /* Construct the SELECT statement that will find the new values for
   101098   ** all updated rows.
   101099   */
   101100   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   101101   if( pRowid ){
   101102     pEList = sqlite3ExprListAppend(pParse, pEList,
   101103                                    sqlite3ExprDup(db, pRowid, 0));
   101104   }
   101105   assert( pTab->iPKey<0 );
   101106   for(i=0; i<pTab->nCol; i++){
   101107     if( aXRef[i]>=0 ){
   101108       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   101109     }else{
   101110       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   101111     }
   101112     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   101113   }
   101114   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   101115 
   101116   /* Create the ephemeral table into which the update results will
   101117   ** be stored.
   101118   */
   101119   assert( v );
   101120   ephemTab = pParse->nTab++;
   101121   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   101122   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   101123 
   101124   /* fill the ephemeral table
   101125   */
   101126   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   101127   sqlite3Select(pParse, pSelect, &dest);
   101128 
   101129   /* Generate code to scan the ephemeral table and call VUpdate. */
   101130   iReg = ++pParse->nMem;
   101131   pParse->nMem += pTab->nCol+1;
   101132   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
   101133   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   101134   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   101135   for(i=0; i<pTab->nCol; i++){
   101136     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   101137   }
   101138   sqlite3VtabMakeWritable(pParse, pTab);
   101139   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   101140   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   101141   sqlite3MayAbort(pParse);
   101142   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
   101143   sqlite3VdbeJumpHere(v, addr);
   101144   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   101145 
   101146   /* Cleanup */
   101147   sqlite3SelectDelete(db, pSelect);
   101148 }
   101149 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   101150 
   101151 /************** End of update.c **********************************************/
   101152 /************** Begin file vacuum.c ******************************************/
   101153 /*
   101154 ** 2003 April 6
   101155 **
   101156 ** The author disclaims copyright to this source code.  In place of
   101157 ** a legal notice, here is a blessing:
   101158 **
   101159 **    May you do good and not evil.
   101160 **    May you find forgiveness for yourself and forgive others.
   101161 **    May you share freely, never taking more than you give.
   101162 **
   101163 *************************************************************************
   101164 ** This file contains code used to implement the VACUUM command.
   101165 **
   101166 ** Most of the code in this file may be omitted by defining the
   101167 ** SQLITE_OMIT_VACUUM macro.
   101168 */
   101169 
   101170 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   101171 /*
   101172 ** Finalize a prepared statement.  If there was an error, store the
   101173 ** text of the error message in *pzErrMsg.  Return the result code.
   101174 */
   101175 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   101176   int rc;
   101177   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   101178   if( rc ){
   101179     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   101180   }
   101181   return rc;
   101182 }
   101183 
   101184 /*
   101185 ** Execute zSql on database db. Return an error code.
   101186 */
   101187 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   101188   sqlite3_stmt *pStmt;
   101189   VVA_ONLY( int rc; )
   101190   if( !zSql ){
   101191     return SQLITE_NOMEM;
   101192   }
   101193   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   101194     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   101195     return sqlite3_errcode(db);
   101196   }
   101197   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   101198   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
   101199   return vacuumFinalize(db, pStmt, pzErrMsg);
   101200 }
   101201 
   101202 /*
   101203 ** Execute zSql on database db. The statement returns exactly
   101204 ** one column. Execute this as SQL on the same database.
   101205 */
   101206 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   101207   sqlite3_stmt *pStmt;
   101208   int rc;
   101209 
   101210   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   101211   if( rc!=SQLITE_OK ) return rc;
   101212 
   101213   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   101214     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   101215     if( rc!=SQLITE_OK ){
   101216       vacuumFinalize(db, pStmt, pzErrMsg);
   101217       return rc;
   101218     }
   101219   }
   101220 
   101221   return vacuumFinalize(db, pStmt, pzErrMsg);
   101222 }
   101223 
   101224 /*
   101225 ** The non-standard VACUUM command is used to clean up the database,
   101226 ** collapse free space, etc.  It is modelled after the VACUUM command
   101227 ** in PostgreSQL.
   101228 **
   101229 ** In version 1.0.x of SQLite, the VACUUM command would call
   101230 ** gdbm_reorganize() on all the database tables.  But beginning
   101231 ** with 2.0.0, SQLite no longer uses GDBM so this command has
   101232 ** become a no-op.
   101233 */
   101234 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   101235   Vdbe *v = sqlite3GetVdbe(pParse);
   101236   if( v ){
   101237     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   101238   }
   101239   return;
   101240 }
   101241 
   101242 /*
   101243 ** This routine implements the OP_Vacuum opcode of the VDBE.
   101244 */
   101245 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   101246   int rc = SQLITE_OK;     /* Return code from service routines */
   101247   Btree *pMain;           /* The database being vacuumed */
   101248   Btree *pTemp;           /* The temporary database we vacuum into */
   101249   char *zSql = 0;         /* SQL statements */
   101250   int saved_flags;        /* Saved value of the db->flags */
   101251   int saved_nChange;      /* Saved value of db->nChange */
   101252   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   101253   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   101254   Db *pDb = 0;            /* Database to detach at end of vacuum */
   101255   int isMemDb;            /* True if vacuuming a :memory: database */
   101256   int nRes;               /* Bytes of reserved space at the end of each page */
   101257   int nDb;                /* Number of attached databases */
   101258 
   101259   if( !db->autoCommit ){
   101260     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   101261     return SQLITE_ERROR;
   101262   }
   101263   if( db->activeVdbeCnt>1 ){
   101264     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   101265     return SQLITE_ERROR;
   101266   }
   101267 
   101268   /* Save the current value of the database flags so that it can be
   101269   ** restored before returning. Then set the writable-schema flag, and
   101270   ** disable CHECK and foreign key constraints.  */
   101271   saved_flags = db->flags;
   101272   saved_nChange = db->nChange;
   101273   saved_nTotalChange = db->nTotalChange;
   101274   saved_xTrace = db->xTrace;
   101275   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   101276   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
   101277   db->xTrace = 0;
   101278 
   101279   pMain = db->aDb[0].pBt;
   101280   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   101281 
   101282   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   101283   ** can be set to 'off' for this file, as it is not recovered if a crash
   101284   ** occurs anyway. The integrity of the database is maintained by a
   101285   ** (possibly synchronous) transaction opened on the main database before
   101286   ** sqlite3BtreeCopyFile() is called.
   101287   **
   101288   ** An optimisation would be to use a non-journaled pager.
   101289   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   101290   ** that actually made the VACUUM run slower.  Very little journalling
   101291   ** actually occurs when doing a vacuum since the vacuum_db is initially
   101292   ** empty.  Only the journal header is written.  Apparently it takes more
   101293   ** time to parse and run the PRAGMA to turn journalling off than it does
   101294   ** to write the journal header file.
   101295   */
   101296   nDb = db->nDb;
   101297   if( sqlite3TempInMemory(db) ){
   101298     zSql = "ATTACH ':memory:' AS vacuum_db;";
   101299   }else{
   101300     zSql = "ATTACH '' AS vacuum_db;";
   101301   }
   101302   rc = execSql(db, pzErrMsg, zSql);
   101303   if( db->nDb>nDb ){
   101304     pDb = &db->aDb[db->nDb-1];
   101305     assert( strcmp(pDb->zName,"vacuum_db")==0 );
   101306   }
   101307   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101308   pTemp = db->aDb[db->nDb-1].pBt;
   101309 
   101310   /* The call to execSql() to attach the temp database has left the file
   101311   ** locked (as there was more than one active statement when the transaction
   101312   ** to read the schema was concluded. Unlock it here so that this doesn't
   101313   ** cause problems for the call to BtreeSetPageSize() below.  */
   101314   sqlite3BtreeCommit(pTemp);
   101315 
   101316   nRes = sqlite3BtreeGetReserve(pMain);
   101317 
   101318   /* A VACUUM cannot change the pagesize of an encrypted database. */
   101319 #ifdef SQLITE_HAS_CODEC
   101320   if( db->nextPagesize ){
   101321     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   101322     int nKey;
   101323     char *zKey;
   101324     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   101325     if( nKey ) db->nextPagesize = 0;
   101326   }
   101327 #endif
   101328 
   101329   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   101330   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101331 
   101332   /* Begin a transaction and take an exclusive lock on the main database
   101333   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   101334   ** to ensure that we do not try to change the page-size on a WAL database.
   101335   */
   101336   rc = execSql(db, pzErrMsg, "BEGIN;");
   101337   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101338   rc = sqlite3BtreeBeginTrans(pMain, 2);
   101339   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101340 
   101341   /* Do not attempt to change the page size for a WAL database */
   101342   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   101343                                                ==PAGER_JOURNALMODE_WAL ){
   101344     db->nextPagesize = 0;
   101345   }
   101346 
   101347   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   101348    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   101349    || NEVER(db->mallocFailed)
   101350   ){
   101351     rc = SQLITE_NOMEM;
   101352     goto end_of_vacuum;
   101353   }
   101354 
   101355 #ifndef SQLITE_OMIT_AUTOVACUUM
   101356   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   101357                                            sqlite3BtreeGetAutoVacuum(pMain));
   101358 #endif
   101359 
   101360   /* Query the schema of the main database. Create a mirror schema
   101361   ** in the temporary database.
   101362   */
   101363   rc = execExecSql(db, pzErrMsg,
   101364       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   101365       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   101366       "   AND rootpage>0"
   101367   );
   101368   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101369   rc = execExecSql(db, pzErrMsg,
   101370       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   101371       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   101372   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101373   rc = execExecSql(db, pzErrMsg,
   101374       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   101375       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   101376   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101377 
   101378   /* Loop through the tables in the main database. For each, do
   101379   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   101380   ** the contents to the temporary database.
   101381   */
   101382   rc = execExecSql(db, pzErrMsg,
   101383       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   101384       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   101385       "FROM main.sqlite_master "
   101386       "WHERE type = 'table' AND name!='sqlite_sequence' "
   101387       "  AND rootpage>0"
   101388   );
   101389   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101390 
   101391   /* Copy over the sequence table
   101392   */
   101393   rc = execExecSql(db, pzErrMsg,
   101394       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   101395       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   101396   );
   101397   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101398   rc = execExecSql(db, pzErrMsg,
   101399       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   101400       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   101401       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   101402   );
   101403   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101404 
   101405 
   101406   /* Copy the triggers, views, and virtual tables from the main database
   101407   ** over to the temporary database.  None of these objects has any
   101408   ** associated storage, so all we have to do is copy their entries
   101409   ** from the SQLITE_MASTER table.
   101410   */
   101411   rc = execSql(db, pzErrMsg,
   101412       "INSERT INTO vacuum_db.sqlite_master "
   101413       "  SELECT type, name, tbl_name, rootpage, sql"
   101414       "    FROM main.sqlite_master"
   101415       "   WHERE type='view' OR type='trigger'"
   101416       "      OR (type='table' AND rootpage=0)"
   101417   );
   101418   if( rc ) goto end_of_vacuum;
   101419 
   101420   /* At this point, there is a write transaction open on both the
   101421   ** vacuum database and the main database. Assuming no error occurs,
   101422   ** both transactions are closed by this block - the main database
   101423   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
   101424   ** call to sqlite3BtreeCommit().
   101425   */
   101426   {
   101427     u32 meta;
   101428     int i;
   101429 
   101430     /* This array determines which meta meta values are preserved in the
   101431     ** vacuum.  Even entries are the meta value number and odd entries
   101432     ** are an increment to apply to the meta value after the vacuum.
   101433     ** The increment is used to increase the schema cookie so that other
   101434     ** connections to the same database will know to reread the schema.
   101435     */
   101436     static const unsigned char aCopy[] = {
   101437        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   101438        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   101439        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   101440        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   101441     };
   101442 
   101443     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   101444     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   101445 
   101446     /* Copy Btree meta values */
   101447     for(i=0; i<ArraySize(aCopy); i+=2){
   101448       /* GetMeta() and UpdateMeta() cannot fail in this context because
   101449       ** we already have page 1 loaded into cache and marked dirty. */
   101450       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   101451       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   101452       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   101453     }
   101454 
   101455     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   101456     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101457     rc = sqlite3BtreeCommit(pTemp);
   101458     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101459 #ifndef SQLITE_OMIT_AUTOVACUUM
   101460     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   101461 #endif
   101462   }
   101463 
   101464   assert( rc==SQLITE_OK );
   101465   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   101466 
   101467 end_of_vacuum:
   101468   /* Restore the original value of db->flags */
   101469   db->flags = saved_flags;
   101470   db->nChange = saved_nChange;
   101471   db->nTotalChange = saved_nTotalChange;
   101472   db->xTrace = saved_xTrace;
   101473   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   101474 
   101475   /* Currently there is an SQL level transaction open on the vacuum
   101476   ** database. No locks are held on any other files (since the main file
   101477   ** was committed at the btree level). So it safe to end the transaction
   101478   ** by manually setting the autoCommit flag to true and detaching the
   101479   ** vacuum database. The vacuum_db journal file is deleted when the pager
   101480   ** is closed by the DETACH.
   101481   */
   101482   db->autoCommit = 1;
   101483 
   101484   if( pDb ){
   101485     sqlite3BtreeClose(pDb->pBt);
   101486     pDb->pBt = 0;
   101487     pDb->pSchema = 0;
   101488   }
   101489 
   101490   /* This both clears the schemas and reduces the size of the db->aDb[]
   101491   ** array. */
   101492   sqlite3ResetInternalSchema(db, -1);
   101493 
   101494   return rc;
   101495 }
   101496 
   101497 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   101498 
   101499 /************** End of vacuum.c **********************************************/
   101500 /************** Begin file vtab.c ********************************************/
   101501 /*
   101502 ** 2006 June 10
   101503 **
   101504 ** The author disclaims copyright to this source code.  In place of
   101505 ** a legal notice, here is a blessing:
   101506 **
   101507 **    May you do good and not evil.
   101508 **    May you find forgiveness for yourself and forgive others.
   101509 **    May you share freely, never taking more than you give.
   101510 **
   101511 *************************************************************************
   101512 ** This file contains code used to help implement virtual tables.
   101513 */
   101514 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101515 
   101516 /*
   101517 ** Before a virtual table xCreate() or xConnect() method is invoked, the
   101518 ** sqlite3.pVtabCtx member variable is set to point to an instance of
   101519 ** this struct allocated on the stack. It is used by the implementation of
   101520 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
   101521 ** are invoked only from within xCreate and xConnect methods.
   101522 */
   101523 struct VtabCtx {
   101524   Table *pTab;
   101525   VTable *pVTable;
   101526 };
   101527 
   101528 /*
   101529 ** The actual function that does the work of creating a new module.
   101530 ** This function implements the sqlite3_create_module() and
   101531 ** sqlite3_create_module_v2() interfaces.
   101532 */
   101533 static int createModule(
   101534   sqlite3 *db,                    /* Database in which module is registered */
   101535   const char *zName,              /* Name assigned to this module */
   101536   const sqlite3_module *pModule,  /* The definition of the module */
   101537   void *pAux,                     /* Context pointer for xCreate/xConnect */
   101538   void (*xDestroy)(void *)        /* Module destructor function */
   101539 ){
   101540   int rc, nName;
   101541   Module *pMod;
   101542 
   101543   sqlite3_mutex_enter(db->mutex);
   101544   nName = sqlite3Strlen30(zName);
   101545   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   101546   if( pMod ){
   101547     Module *pDel;
   101548     char *zCopy = (char *)(&pMod[1]);
   101549     memcpy(zCopy, zName, nName+1);
   101550     pMod->zName = zCopy;
   101551     pMod->pModule = pModule;
   101552     pMod->pAux = pAux;
   101553     pMod->xDestroy = xDestroy;
   101554     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
   101555     if( pDel && pDel->xDestroy ){
   101556       sqlite3ResetInternalSchema(db, -1);
   101557       pDel->xDestroy(pDel->pAux);
   101558     }
   101559     sqlite3DbFree(db, pDel);
   101560     if( pDel==pMod ){
   101561       db->mallocFailed = 1;
   101562     }
   101563   }else if( xDestroy ){
   101564     xDestroy(pAux);
   101565   }
   101566   rc = sqlite3ApiExit(db, SQLITE_OK);
   101567   sqlite3_mutex_leave(db->mutex);
   101568   return rc;
   101569 }
   101570 
   101571 
   101572 /*
   101573 ** External API function used to create a new virtual-table module.
   101574 */
   101575 SQLITE_API int sqlite3_create_module(
   101576   sqlite3 *db,                    /* Database in which module is registered */
   101577   const char *zName,              /* Name assigned to this module */
   101578   const sqlite3_module *pModule,  /* The definition of the module */
   101579   void *pAux                      /* Context pointer for xCreate/xConnect */
   101580 ){
   101581   return createModule(db, zName, pModule, pAux, 0);
   101582 }
   101583 
   101584 /*
   101585 ** External API function used to create a new virtual-table module.
   101586 */
   101587 SQLITE_API int sqlite3_create_module_v2(
   101588   sqlite3 *db,                    /* Database in which module is registered */
   101589   const char *zName,              /* Name assigned to this module */
   101590   const sqlite3_module *pModule,  /* The definition of the module */
   101591   void *pAux,                     /* Context pointer for xCreate/xConnect */
   101592   void (*xDestroy)(void *)        /* Module destructor function */
   101593 ){
   101594   return createModule(db, zName, pModule, pAux, xDestroy);
   101595 }
   101596 
   101597 /*
   101598 ** Lock the virtual table so that it cannot be disconnected.
   101599 ** Locks nest.  Every lock should have a corresponding unlock.
   101600 ** If an unlock is omitted, resources leaks will occur.
   101601 **
   101602 ** If a disconnect is attempted while a virtual table is locked,
   101603 ** the disconnect is deferred until all locks have been removed.
   101604 */
   101605 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   101606   pVTab->nRef++;
   101607 }
   101608 
   101609 
   101610 /*
   101611 ** pTab is a pointer to a Table structure representing a virtual-table.
   101612 ** Return a pointer to the VTable object used by connection db to access
   101613 ** this virtual-table, if one has been created, or NULL otherwise.
   101614 */
   101615 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   101616   VTable *pVtab;
   101617   assert( IsVirtual(pTab) );
   101618   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   101619   return pVtab;
   101620 }
   101621 
   101622 /*
   101623 ** Decrement the ref-count on a virtual table object. When the ref-count
   101624 ** reaches zero, call the xDisconnect() method to delete the object.
   101625 */
   101626 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   101627   sqlite3 *db = pVTab->db;
   101628 
   101629   assert( db );
   101630   assert( pVTab->nRef>0 );
   101631   assert( sqlite3SafetyCheckOk(db) );
   101632 
   101633   pVTab->nRef--;
   101634   if( pVTab->nRef==0 ){
   101635     sqlite3_vtab *p = pVTab->pVtab;
   101636     if( p ){
   101637       p->pModule->xDisconnect(p);
   101638     }
   101639     sqlite3DbFree(db, pVTab);
   101640   }
   101641 }
   101642 
   101643 /*
   101644 ** Table p is a virtual table. This function moves all elements in the
   101645 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   101646 ** database connections to be disconnected at the next opportunity.
   101647 ** Except, if argument db is not NULL, then the entry associated with
   101648 ** connection db is left in the p->pVTable list.
   101649 */
   101650 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   101651   VTable *pRet = 0;
   101652   VTable *pVTable = p->pVTable;
   101653   p->pVTable = 0;
   101654 
   101655   /* Assert that the mutex (if any) associated with the BtShared database
   101656   ** that contains table p is held by the caller. See header comments
   101657   ** above function sqlite3VtabUnlockList() for an explanation of why
   101658   ** this makes it safe to access the sqlite3.pDisconnect list of any
   101659   ** database connection that may have an entry in the p->pVTable list.
   101660   */
   101661   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   101662 
   101663   while( pVTable ){
   101664     sqlite3 *db2 = pVTable->db;
   101665     VTable *pNext = pVTable->pNext;
   101666     assert( db2 );
   101667     if( db2==db ){
   101668       pRet = pVTable;
   101669       p->pVTable = pRet;
   101670       pRet->pNext = 0;
   101671     }else{
   101672       pVTable->pNext = db2->pDisconnect;
   101673       db2->pDisconnect = pVTable;
   101674     }
   101675     pVTable = pNext;
   101676   }
   101677 
   101678   assert( !db || pRet );
   101679   return pRet;
   101680 }
   101681 
   101682 
   101683 /*
   101684 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   101685 **
   101686 ** This function may only be called when the mutexes associated with all
   101687 ** shared b-tree databases opened using connection db are held by the
   101688 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   101689 ** sqlite3.pDisconnect list is accessed only as follows:
   101690 **
   101691 **   1) By this function. In this case, all BtShared mutexes and the mutex
   101692 **      associated with the database handle itself must be held.
   101693 **
   101694 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   101695 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   101696 **      associated with the database the virtual table is stored in is held
   101697 **      or, if the virtual table is stored in a non-sharable database, then
   101698 **      the database handle mutex is held.
   101699 **
   101700 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   101701 ** by multiple threads. It is thread-safe.
   101702 */
   101703 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   101704   VTable *p = db->pDisconnect;
   101705   db->pDisconnect = 0;
   101706 
   101707   assert( sqlite3BtreeHoldsAllMutexes(db) );
   101708   assert( sqlite3_mutex_held(db->mutex) );
   101709 
   101710   if( p ){
   101711     sqlite3ExpirePreparedStatements(db);
   101712     do {
   101713       VTable *pNext = p->pNext;
   101714       sqlite3VtabUnlock(p);
   101715       p = pNext;
   101716     }while( p );
   101717   }
   101718 }
   101719 
   101720 /*
   101721 ** Clear any and all virtual-table information from the Table record.
   101722 ** This routine is called, for example, just before deleting the Table
   101723 ** record.
   101724 **
   101725 ** Since it is a virtual-table, the Table structure contains a pointer
   101726 ** to the head of a linked list of VTable structures. Each VTable
   101727 ** structure is associated with a single sqlite3* user of the schema.
   101728 ** The reference count of the VTable structure associated with database
   101729 ** connection db is decremented immediately (which may lead to the
   101730 ** structure being xDisconnected and free). Any other VTable structures
   101731 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   101732 ** database connection.
   101733 */
   101734 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   101735   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   101736   if( p->azModuleArg ){
   101737     int i;
   101738     for(i=0; i<p->nModuleArg; i++){
   101739       sqlite3DbFree(db, p->azModuleArg[i]);
   101740     }
   101741     sqlite3DbFree(db, p->azModuleArg);
   101742   }
   101743 }
   101744 
   101745 /*
   101746 ** Add a new module argument to pTable->azModuleArg[].
   101747 ** The string is not copied - the pointer is stored.  The
   101748 ** string will be freed automatically when the table is
   101749 ** deleted.
   101750 */
   101751 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   101752   int i = pTable->nModuleArg++;
   101753   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   101754   char **azModuleArg;
   101755   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   101756   if( azModuleArg==0 ){
   101757     int j;
   101758     for(j=0; j<i; j++){
   101759       sqlite3DbFree(db, pTable->azModuleArg[j]);
   101760     }
   101761     sqlite3DbFree(db, zArg);
   101762     sqlite3DbFree(db, pTable->azModuleArg);
   101763     pTable->nModuleArg = 0;
   101764   }else{
   101765     azModuleArg[i] = zArg;
   101766     azModuleArg[i+1] = 0;
   101767   }
   101768   pTable->azModuleArg = azModuleArg;
   101769 }
   101770 
   101771 /*
   101772 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   101773 ** statement.  The module name has been parsed, but the optional list
   101774 ** of parameters that follow the module name are still pending.
   101775 */
   101776 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   101777   Parse *pParse,        /* Parsing context */
   101778   Token *pName1,        /* Name of new table, or database name */
   101779   Token *pName2,        /* Name of new table or NULL */
   101780   Token *pModuleName,   /* Name of the module for the virtual table */
   101781   int ifNotExists       /* No error if the table already exists */
   101782 ){
   101783   int iDb;              /* The database the table is being created in */
   101784   Table *pTable;        /* The new virtual table */
   101785   sqlite3 *db;          /* Database connection */
   101786 
   101787   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
   101788   pTable = pParse->pNewTable;
   101789   if( pTable==0 ) return;
   101790   assert( 0==pTable->pIndex );
   101791 
   101792   db = pParse->db;
   101793   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   101794   assert( iDb>=0 );
   101795 
   101796   pTable->tabFlags |= TF_Virtual;
   101797   pTable->nModuleArg = 0;
   101798   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   101799   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
   101800   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   101801   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   101802 
   101803 #ifndef SQLITE_OMIT_AUTHORIZATION
   101804   /* Creating a virtual table invokes the authorization callback twice.
   101805   ** The first invocation, to obtain permission to INSERT a row into the
   101806   ** sqlite_master table, has already been made by sqlite3StartTable().
   101807   ** The second call, to obtain permission to create the table, is made now.
   101808   */
   101809   if( pTable->azModuleArg ){
   101810     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   101811             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   101812   }
   101813 #endif
   101814 }
   101815 
   101816 /*
   101817 ** This routine takes the module argument that has been accumulating
   101818 ** in pParse->zArg[] and appends it to the list of arguments on the
   101819 ** virtual table currently under construction in pParse->pTable.
   101820 */
   101821 static void addArgumentToVtab(Parse *pParse){
   101822   if( pParse->sArg.z && pParse->pNewTable ){
   101823     const char *z = (const char*)pParse->sArg.z;
   101824     int n = pParse->sArg.n;
   101825     sqlite3 *db = pParse->db;
   101826     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   101827   }
   101828 }
   101829 
   101830 /*
   101831 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   101832 ** has been completely parsed.
   101833 */
   101834 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   101835   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   101836   sqlite3 *db = pParse->db;         /* The database connection */
   101837 
   101838   if( pTab==0 ) return;
   101839   addArgumentToVtab(pParse);
   101840   pParse->sArg.z = 0;
   101841   if( pTab->nModuleArg<1 ) return;
   101842 
   101843   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   101844   ** first time (in other words if the virtual table is actually being
   101845   ** created now instead of just being read out of sqlite_master) then
   101846   ** do additional initialization work and store the statement text
   101847   ** in the sqlite_master table.
   101848   */
   101849   if( !db->init.busy ){
   101850     char *zStmt;
   101851     char *zWhere;
   101852     int iDb;
   101853     Vdbe *v;
   101854 
   101855     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   101856     if( pEnd ){
   101857       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   101858     }
   101859     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   101860 
   101861     /* A slot for the record has already been allocated in the
   101862     ** SQLITE_MASTER table.  We just need to update that slot with all
   101863     ** the information we've collected.
   101864     **
   101865     ** The VM register number pParse->regRowid holds the rowid of an
   101866     ** entry in the sqlite_master table tht was created for this vtab
   101867     ** by sqlite3StartTable().
   101868     */
   101869     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   101870     sqlite3NestedParse(pParse,
   101871       "UPDATE %Q.%s "
   101872          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   101873        "WHERE rowid=#%d",
   101874       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   101875       pTab->zName,
   101876       pTab->zName,
   101877       zStmt,
   101878       pParse->regRowid
   101879     );
   101880     sqlite3DbFree(db, zStmt);
   101881     v = sqlite3GetVdbe(pParse);
   101882     sqlite3ChangeCookie(pParse, iDb);
   101883 
   101884     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   101885     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   101886     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   101887     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   101888                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   101889   }
   101890 
   101891   /* If we are rereading the sqlite_master table create the in-memory
   101892   ** record of the table. The xConnect() method is not called until
   101893   ** the first time the virtual table is used in an SQL statement. This
   101894   ** allows a schema that contains virtual tables to be loaded before
   101895   ** the required virtual table implementations are registered.  */
   101896   else {
   101897     Table *pOld;
   101898     Schema *pSchema = pTab->pSchema;
   101899     const char *zName = pTab->zName;
   101900     int nName = sqlite3Strlen30(zName);
   101901     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   101902     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   101903     if( pOld ){
   101904       db->mallocFailed = 1;
   101905       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   101906       return;
   101907     }
   101908     pParse->pNewTable = 0;
   101909   }
   101910 }
   101911 
   101912 /*
   101913 ** The parser calls this routine when it sees the first token
   101914 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   101915 */
   101916 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   101917   addArgumentToVtab(pParse);
   101918   pParse->sArg.z = 0;
   101919   pParse->sArg.n = 0;
   101920 }
   101921 
   101922 /*
   101923 ** The parser calls this routine for each token after the first token
   101924 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   101925 */
   101926 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   101927   Token *pArg = &pParse->sArg;
   101928   if( pArg->z==0 ){
   101929     pArg->z = p->z;
   101930     pArg->n = p->n;
   101931   }else{
   101932     assert(pArg->z < p->z);
   101933     pArg->n = (int)(&p->z[p->n] - pArg->z);
   101934   }
   101935 }
   101936 
   101937 /*
   101938 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   101939 ** pointer to the function to invoke is passed as the fourth parameter
   101940 ** to this procedure.
   101941 */
   101942 static int vtabCallConstructor(
   101943   sqlite3 *db,
   101944   Table *pTab,
   101945   Module *pMod,
   101946   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   101947   char **pzErr
   101948 ){
   101949   VtabCtx sCtx;
   101950   VTable *pVTable;
   101951   int rc;
   101952   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   101953   int nArg = pTab->nModuleArg;
   101954   char *zErr = 0;
   101955   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   101956 
   101957   if( !zModuleName ){
   101958     return SQLITE_NOMEM;
   101959   }
   101960 
   101961   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   101962   if( !pVTable ){
   101963     sqlite3DbFree(db, zModuleName);
   101964     return SQLITE_NOMEM;
   101965   }
   101966   pVTable->db = db;
   101967   pVTable->pMod = pMod;
   101968 
   101969   /* Invoke the virtual table constructor */
   101970   assert( &db->pVtabCtx );
   101971   assert( xConstruct );
   101972   sCtx.pTab = pTab;
   101973   sCtx.pVTable = pVTable;
   101974   db->pVtabCtx = &sCtx;
   101975   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   101976   db->pVtabCtx = 0;
   101977   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   101978 
   101979   if( SQLITE_OK!=rc ){
   101980     if( zErr==0 ){
   101981       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   101982     }else {
   101983       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   101984       sqlite3_free(zErr);
   101985     }
   101986     sqlite3DbFree(db, pVTable);
   101987   }else if( ALWAYS(pVTable->pVtab) ){
   101988     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   101989     ** the sqlite3_vtab object if successful.  */
   101990     pVTable->pVtab->pModule = pMod->pModule;
   101991     pVTable->nRef = 1;
   101992     if( sCtx.pTab ){
   101993       const char *zFormat = "vtable constructor did not declare schema: %s";
   101994       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   101995       sqlite3VtabUnlock(pVTable);
   101996       rc = SQLITE_ERROR;
   101997     }else{
   101998       int iCol;
   101999       /* If everything went according to plan, link the new VTable structure
   102000       ** into the linked list headed by pTab->pVTable. Then loop through the
   102001       ** columns of the table to see if any of them contain the token "hidden".
   102002       ** If so, set the Column.isHidden flag and remove the token from
   102003       ** the type string.  */
   102004       pVTable->pNext = pTab->pVTable;
   102005       pTab->pVTable = pVTable;
   102006 
   102007       for(iCol=0; iCol<pTab->nCol; iCol++){
   102008         char *zType = pTab->aCol[iCol].zType;
   102009         int nType;
   102010         int i = 0;
   102011         if( !zType ) continue;
   102012         nType = sqlite3Strlen30(zType);
   102013         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   102014           for(i=0; i<nType; i++){
   102015             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   102016              && (zType[i+7]=='\0' || zType[i+7]==' ')
   102017             ){
   102018               i++;
   102019               break;
   102020             }
   102021           }
   102022         }
   102023         if( i<nType ){
   102024           int j;
   102025           int nDel = 6 + (zType[i+6] ? 1 : 0);
   102026           for(j=i; (j+nDel)<=nType; j++){
   102027             zType[j] = zType[j+nDel];
   102028           }
   102029           if( zType[i]=='\0' && i>0 ){
   102030             assert(zType[i-1]==' ');
   102031             zType[i-1] = '\0';
   102032           }
   102033           pTab->aCol[iCol].isHidden = 1;
   102034         }
   102035       }
   102036     }
   102037   }
   102038 
   102039   sqlite3DbFree(db, zModuleName);
   102040   return rc;
   102041 }
   102042 
   102043 /*
   102044 ** This function is invoked by the parser to call the xConnect() method
   102045 ** of the virtual table pTab. If an error occurs, an error code is returned
   102046 ** and an error left in pParse.
   102047 **
   102048 ** This call is a no-op if table pTab is not a virtual table.
   102049 */
   102050 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   102051   sqlite3 *db = pParse->db;
   102052   const char *zMod;
   102053   Module *pMod;
   102054   int rc;
   102055 
   102056   assert( pTab );
   102057   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   102058     return SQLITE_OK;
   102059   }
   102060 
   102061   /* Locate the required virtual table module */
   102062   zMod = pTab->azModuleArg[0];
   102063   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   102064 
   102065   if( !pMod ){
   102066     const char *zModule = pTab->azModuleArg[0];
   102067     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   102068     rc = SQLITE_ERROR;
   102069   }else{
   102070     char *zErr = 0;
   102071     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   102072     if( rc!=SQLITE_OK ){
   102073       sqlite3ErrorMsg(pParse, "%s", zErr);
   102074     }
   102075     sqlite3DbFree(db, zErr);
   102076   }
   102077 
   102078   return rc;
   102079 }
   102080 /*
   102081 ** Grow the db->aVTrans[] array so that there is room for at least one
   102082 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
   102083 */
   102084 static int growVTrans(sqlite3 *db){
   102085   const int ARRAY_INCR = 5;
   102086 
   102087   /* Grow the sqlite3.aVTrans array if required */
   102088   if( (db->nVTrans%ARRAY_INCR)==0 ){
   102089     VTable **aVTrans;
   102090     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   102091     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   102092     if( !aVTrans ){
   102093       return SQLITE_NOMEM;
   102094     }
   102095     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   102096     db->aVTrans = aVTrans;
   102097   }
   102098 
   102099   return SQLITE_OK;
   102100 }
   102101 
   102102 /*
   102103 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
   102104 ** have already been reserved using growVTrans().
   102105 */
   102106 static void addToVTrans(sqlite3 *db, VTable *pVTab){
   102107   /* Add pVtab to the end of sqlite3.aVTrans */
   102108   db->aVTrans[db->nVTrans++] = pVTab;
   102109   sqlite3VtabLock(pVTab);
   102110 }
   102111 
   102112 /*
   102113 ** This function is invoked by the vdbe to call the xCreate method
   102114 ** of the virtual table named zTab in database iDb.
   102115 **
   102116 ** If an error occurs, *pzErr is set to point an an English language
   102117 ** description of the error and an SQLITE_XXX error code is returned.
   102118 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   102119 */
   102120 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   102121   int rc = SQLITE_OK;
   102122   Table *pTab;
   102123   Module *pMod;
   102124   const char *zMod;
   102125 
   102126   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   102127   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   102128 
   102129   /* Locate the required virtual table module */
   102130   zMod = pTab->azModuleArg[0];
   102131   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   102132 
   102133   /* If the module has been registered and includes a Create method,
   102134   ** invoke it now. If the module has not been registered, return an
   102135   ** error. Otherwise, do nothing.
   102136   */
   102137   if( !pMod ){
   102138     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   102139     rc = SQLITE_ERROR;
   102140   }else{
   102141     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   102142   }
   102143 
   102144   /* Justification of ALWAYS():  The xConstructor method is required to
   102145   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   102146   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   102147     rc = growVTrans(db);
   102148     if( rc==SQLITE_OK ){
   102149       addToVTrans(db, sqlite3GetVTable(db, pTab));
   102150     }
   102151   }
   102152 
   102153   return rc;
   102154 }
   102155 
   102156 /*
   102157 ** This function is used to set the schema of a virtual table.  It is only
   102158 ** valid to call this function from within the xCreate() or xConnect() of a
   102159 ** virtual table module.
   102160 */
   102161 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   102162   Parse *pParse;
   102163 
   102164   int rc = SQLITE_OK;
   102165   Table *pTab;
   102166   char *zErr = 0;
   102167 
   102168   sqlite3_mutex_enter(db->mutex);
   102169   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
   102170     sqlite3Error(db, SQLITE_MISUSE, 0);
   102171     sqlite3_mutex_leave(db->mutex);
   102172     return SQLITE_MISUSE_BKPT;
   102173   }
   102174   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   102175 
   102176   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   102177   if( pParse==0 ){
   102178     rc = SQLITE_NOMEM;
   102179   }else{
   102180     pParse->declareVtab = 1;
   102181     pParse->db = db;
   102182     pParse->nQueryLoop = 1;
   102183 
   102184     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   102185      && pParse->pNewTable
   102186      && !db->mallocFailed
   102187      && !pParse->pNewTable->pSelect
   102188      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   102189     ){
   102190       if( !pTab->aCol ){
   102191         pTab->aCol = pParse->pNewTable->aCol;
   102192         pTab->nCol = pParse->pNewTable->nCol;
   102193         pParse->pNewTable->nCol = 0;
   102194         pParse->pNewTable->aCol = 0;
   102195       }
   102196       db->pVtabCtx->pTab = 0;
   102197     }else{
   102198       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   102199       sqlite3DbFree(db, zErr);
   102200       rc = SQLITE_ERROR;
   102201     }
   102202     pParse->declareVtab = 0;
   102203 
   102204     if( pParse->pVdbe ){
   102205       sqlite3VdbeFinalize(pParse->pVdbe);
   102206     }
   102207     sqlite3DeleteTable(db, pParse->pNewTable);
   102208     sqlite3StackFree(db, pParse);
   102209   }
   102210 
   102211   assert( (rc&0xff)==rc );
   102212   rc = sqlite3ApiExit(db, rc);
   102213   sqlite3_mutex_leave(db->mutex);
   102214   return rc;
   102215 }
   102216 
   102217 /*
   102218 ** This function is invoked by the vdbe to call the xDestroy method
   102219 ** of the virtual table named zTab in database iDb. This occurs
   102220 ** when a DROP TABLE is mentioned.
   102221 **
   102222 ** This call is a no-op if zTab is not a virtual table.
   102223 */
   102224 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   102225   int rc = SQLITE_OK;
   102226   Table *pTab;
   102227 
   102228   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   102229   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   102230     VTable *p = vtabDisconnectAll(db, pTab);
   102231 
   102232     assert( rc==SQLITE_OK );
   102233     rc = p->pMod->pModule->xDestroy(p->pVtab);
   102234 
   102235     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   102236     if( rc==SQLITE_OK ){
   102237       assert( pTab->pVTable==p && p->pNext==0 );
   102238       p->pVtab = 0;
   102239       pTab->pVTable = 0;
   102240       sqlite3VtabUnlock(p);
   102241     }
   102242   }
   102243 
   102244   return rc;
   102245 }
   102246 
   102247 /*
   102248 ** This function invokes either the xRollback or xCommit method
   102249 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   102250 ** called is identified by the second argument, "offset", which is
   102251 ** the offset of the method to call in the sqlite3_module structure.
   102252 **
   102253 ** The array is cleared after invoking the callbacks.
   102254 */
   102255 static void callFinaliser(sqlite3 *db, int offset){
   102256   int i;
   102257   if( db->aVTrans ){
   102258     for(i=0; i<db->nVTrans; i++){
   102259       VTable *pVTab = db->aVTrans[i];
   102260       sqlite3_vtab *p = pVTab->pVtab;
   102261       if( p ){
   102262         int (*x)(sqlite3_vtab *);
   102263         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   102264         if( x ) x(p);
   102265       }
   102266       pVTab->iSavepoint = 0;
   102267       sqlite3VtabUnlock(pVTab);
   102268     }
   102269     sqlite3DbFree(db, db->aVTrans);
   102270     db->nVTrans = 0;
   102271     db->aVTrans = 0;
   102272   }
   102273 }
   102274 
   102275 /*
   102276 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   102277 ** array. Return the error code for the first error that occurs, or
   102278 ** SQLITE_OK if all xSync operations are successful.
   102279 **
   102280 ** Set *pzErrmsg to point to a buffer that should be released using
   102281 ** sqlite3DbFree() containing an error message, if one is available.
   102282 */
   102283 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
   102284   int i;
   102285   int rc = SQLITE_OK;
   102286   VTable **aVTrans = db->aVTrans;
   102287 
   102288   db->aVTrans = 0;
   102289   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   102290     int (*x)(sqlite3_vtab *);
   102291     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   102292     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   102293       rc = x(pVtab);
   102294       sqlite3DbFree(db, *pzErrmsg);
   102295       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   102296       sqlite3_free(pVtab->zErrMsg);
   102297     }
   102298   }
   102299   db->aVTrans = aVTrans;
   102300   return rc;
   102301 }
   102302 
   102303 /*
   102304 ** Invoke the xRollback method of all virtual tables in the
   102305 ** sqlite3.aVTrans array. Then clear the array itself.
   102306 */
   102307 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   102308   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   102309   return SQLITE_OK;
   102310 }
   102311 
   102312 /*
   102313 ** Invoke the xCommit method of all virtual tables in the
   102314 ** sqlite3.aVTrans array. Then clear the array itself.
   102315 */
   102316 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   102317   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   102318   return SQLITE_OK;
   102319 }
   102320 
   102321 /*
   102322 ** If the virtual table pVtab supports the transaction interface
   102323 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   102324 ** not currently open, invoke the xBegin method now.
   102325 **
   102326 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   102327 ** in the sqlite3.aVTrans array.
   102328 */
   102329 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   102330   int rc = SQLITE_OK;
   102331   const sqlite3_module *pModule;
   102332 
   102333   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   102334   ** than zero, then this function is being called from within a
   102335   ** virtual module xSync() callback. It is illegal to write to
   102336   ** virtual module tables in this case, so return SQLITE_LOCKED.
   102337   */
   102338   if( sqlite3VtabInSync(db) ){
   102339     return SQLITE_LOCKED;
   102340   }
   102341   if( !pVTab ){
   102342     return SQLITE_OK;
   102343   }
   102344   pModule = pVTab->pVtab->pModule;
   102345 
   102346   if( pModule->xBegin ){
   102347     int i;
   102348 
   102349     /* If pVtab is already in the aVTrans array, return early */
   102350     for(i=0; i<db->nVTrans; i++){
   102351       if( db->aVTrans[i]==pVTab ){
   102352         return SQLITE_OK;
   102353       }
   102354     }
   102355 
   102356     /* Invoke the xBegin method. If successful, add the vtab to the
   102357     ** sqlite3.aVTrans[] array. */
   102358     rc = growVTrans(db);
   102359     if( rc==SQLITE_OK ){
   102360       rc = pModule->xBegin(pVTab->pVtab);
   102361       if( rc==SQLITE_OK ){
   102362         addToVTrans(db, pVTab);
   102363       }
   102364     }
   102365   }
   102366   return rc;
   102367 }
   102368 
   102369 /*
   102370 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
   102371 ** virtual tables that currently have an open transaction. Pass iSavepoint
   102372 ** as the second argument to the virtual table method invoked.
   102373 **
   102374 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
   102375 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
   102376 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
   102377 ** an open transaction is invoked.
   102378 **
   102379 ** If any virtual table method returns an error code other than SQLITE_OK,
   102380 ** processing is abandoned and the error returned to the caller of this
   102381 ** function immediately. If all calls to virtual table methods are successful,
   102382 ** SQLITE_OK is returned.
   102383 */
   102384 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
   102385   int rc = SQLITE_OK;
   102386 
   102387   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
   102388   assert( iSavepoint>=0 );
   102389   if( db->aVTrans ){
   102390     int i;
   102391     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   102392       VTable *pVTab = db->aVTrans[i];
   102393       const sqlite3_module *pMod = pVTab->pMod->pModule;
   102394       if( pVTab->pVtab && pMod->iVersion>=2 ){
   102395         int (*xMethod)(sqlite3_vtab *, int);
   102396         switch( op ){
   102397           case SAVEPOINT_BEGIN:
   102398             xMethod = pMod->xSavepoint;
   102399             pVTab->iSavepoint = iSavepoint+1;
   102400             break;
   102401           case SAVEPOINT_ROLLBACK:
   102402             xMethod = pMod->xRollbackTo;
   102403             break;
   102404           default:
   102405             xMethod = pMod->xRelease;
   102406             break;
   102407         }
   102408         if( xMethod && pVTab->iSavepoint>iSavepoint ){
   102409           rc = xMethod(pVTab->pVtab, iSavepoint);
   102410         }
   102411       }
   102412     }
   102413   }
   102414   return rc;
   102415 }
   102416 
   102417 /*
   102418 ** The first parameter (pDef) is a function implementation.  The
   102419 ** second parameter (pExpr) is the first argument to this function.
   102420 ** If pExpr is a column in a virtual table, then let the virtual
   102421 ** table implementation have an opportunity to overload the function.
   102422 **
   102423 ** This routine is used to allow virtual table implementations to
   102424 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   102425 **
   102426 ** Return either the pDef argument (indicating no change) or a
   102427 ** new FuncDef structure that is marked as ephemeral using the
   102428 ** SQLITE_FUNC_EPHEM flag.
   102429 */
   102430 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   102431   sqlite3 *db,    /* Database connection for reporting malloc problems */
   102432   FuncDef *pDef,  /* Function to possibly overload */
   102433   int nArg,       /* Number of arguments to the function */
   102434   Expr *pExpr     /* First argument to the function */
   102435 ){
   102436   Table *pTab;
   102437   sqlite3_vtab *pVtab;
   102438   sqlite3_module *pMod;
   102439   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   102440   void *pArg = 0;
   102441   FuncDef *pNew;
   102442   int rc = 0;
   102443   char *zLowerName;
   102444   unsigned char *z;
   102445 
   102446 
   102447   /* Check to see the left operand is a column in a virtual table */
   102448   if( NEVER(pExpr==0) ) return pDef;
   102449   if( pExpr->op!=TK_COLUMN ) return pDef;
   102450   pTab = pExpr->pTab;
   102451   if( NEVER(pTab==0) ) return pDef;
   102452   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   102453   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   102454   assert( pVtab!=0 );
   102455   assert( pVtab->pModule!=0 );
   102456   pMod = (sqlite3_module *)pVtab->pModule;
   102457   if( pMod->xFindFunction==0 ) return pDef;
   102458 
   102459   /* Call the xFindFunction method on the virtual table implementation
   102460   ** to see if the implementation wants to overload this function
   102461   */
   102462   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   102463   if( zLowerName ){
   102464     for(z=(unsigned char*)zLowerName; *z; z++){
   102465       *z = sqlite3UpperToLower[*z];
   102466     }
   102467     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   102468     sqlite3DbFree(db, zLowerName);
   102469   }
   102470   if( rc==0 ){
   102471     return pDef;
   102472   }
   102473 
   102474   /* Create a new ephemeral function definition for the overloaded
   102475   ** function */
   102476   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   102477                              + sqlite3Strlen30(pDef->zName) + 1);
   102478   if( pNew==0 ){
   102479     return pDef;
   102480   }
   102481   *pNew = *pDef;
   102482   pNew->zName = (char *)&pNew[1];
   102483   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   102484   pNew->xFunc = xFunc;
   102485   pNew->pUserData = pArg;
   102486   pNew->flags |= SQLITE_FUNC_EPHEM;
   102487   return pNew;
   102488 }
   102489 
   102490 /*
   102491 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   102492 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   102493 ** array if it is missing.  If pTab is already in the array, this routine
   102494 ** is a no-op.
   102495 */
   102496 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   102497   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   102498   int i, n;
   102499   Table **apVtabLock;
   102500 
   102501   assert( IsVirtual(pTab) );
   102502   for(i=0; i<pToplevel->nVtabLock; i++){
   102503     if( pTab==pToplevel->apVtabLock[i] ) return;
   102504   }
   102505   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   102506   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   102507   if( apVtabLock ){
   102508     pToplevel->apVtabLock = apVtabLock;
   102509     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   102510   }else{
   102511     pToplevel->db->mallocFailed = 1;
   102512   }
   102513 }
   102514 
   102515 /*
   102516 ** Return the ON CONFLICT resolution mode in effect for the virtual
   102517 ** table update operation currently in progress.
   102518 **
   102519 ** The results of this routine are undefined unless it is called from
   102520 ** within an xUpdate method.
   102521 */
   102522 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
   102523   static const unsigned char aMap[] = {
   102524     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   102525   };
   102526   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
   102527   assert( OE_Ignore==4 && OE_Replace==5 );
   102528   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
   102529   return (int)aMap[db->vtabOnConflict-1];
   102530 }
   102531 
   102532 /*
   102533 ** Call from within the xCreate() or xConnect() methods to provide
   102534 ** the SQLite core with additional information about the behavior
   102535 ** of the virtual table being implemented.
   102536 */
   102537 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   102538   va_list ap;
   102539   int rc = SQLITE_OK;
   102540 
   102541   sqlite3_mutex_enter(db->mutex);
   102542 
   102543   va_start(ap, op);
   102544   switch( op ){
   102545     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
   102546       VtabCtx *p = db->pVtabCtx;
   102547       if( !p ){
   102548         rc = SQLITE_MISUSE_BKPT;
   102549       }else{
   102550         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
   102551         p->pVTable->bConstraint = (u8)va_arg(ap, int);
   102552       }
   102553       break;
   102554     }
   102555     default:
   102556       rc = SQLITE_MISUSE_BKPT;
   102557       break;
   102558   }
   102559   va_end(ap);
   102560 
   102561   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
   102562   sqlite3_mutex_leave(db->mutex);
   102563   return rc;
   102564 }
   102565 
   102566 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   102567 
   102568 /************** End of vtab.c ************************************************/
   102569 /************** Begin file where.c *******************************************/
   102570 /*
   102571 ** 2001 September 15
   102572 **
   102573 ** The author disclaims copyright to this source code.  In place of
   102574 ** a legal notice, here is a blessing:
   102575 **
   102576 **    May you do good and not evil.
   102577 **    May you find forgiveness for yourself and forgive others.
   102578 **    May you share freely, never taking more than you give.
   102579 **
   102580 *************************************************************************
   102581 ** This module contains C code that generates VDBE code used to process
   102582 ** the WHERE clause of SQL statements.  This module is responsible for
   102583 ** generating the code that loops through a table looking for applicable
   102584 ** rows.  Indices are selected and used to speed the search when doing
   102585 ** so is applicable.  Because this module is responsible for selecting
   102586 ** indices, you might also think of this module as the "query optimizer".
   102587 */
   102588 
   102589 
   102590 /*
   102591 ** Trace output macros
   102592 */
   102593 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   102594 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
   102595 #endif
   102596 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   102597 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
   102598 #else
   102599 # define WHERETRACE(X)
   102600 #endif
   102601 
   102602 /* Forward reference
   102603 */
   102604 typedef struct WhereClause WhereClause;
   102605 typedef struct WhereMaskSet WhereMaskSet;
   102606 typedef struct WhereOrInfo WhereOrInfo;
   102607 typedef struct WhereAndInfo WhereAndInfo;
   102608 typedef struct WhereCost WhereCost;
   102609 
   102610 /*
   102611 ** The query generator uses an array of instances of this structure to
   102612 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   102613 ** clause subexpression is separated from the others by AND operators,
   102614 ** usually, or sometimes subexpressions separated by OR.
   102615 **
   102616 ** All WhereTerms are collected into a single WhereClause structure.
   102617 ** The following identity holds:
   102618 **
   102619 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   102620 **
   102621 ** When a term is of the form:
   102622 **
   102623 **              X <op> <expr>
   102624 **
   102625 ** where X is a column name and <op> is one of certain operators,
   102626 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   102627 ** cursor number and column number for X.  WhereTerm.eOperator records
   102628 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   102629 ** use of a bitmask encoding for the operator allows us to search
   102630 ** quickly for terms that match any of several different operators.
   102631 **
   102632 ** A WhereTerm might also be two or more subterms connected by OR:
   102633 **
   102634 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   102635 **
   102636 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
   102637 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   102638 ** is collected about the
   102639 **
   102640 ** If a term in the WHERE clause does not match either of the two previous
   102641 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   102642 ** to the original subexpression content and wtFlags is set up appropriately
   102643 ** but no other fields in the WhereTerm object are meaningful.
   102644 **
   102645 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   102646 ** but they do so indirectly.  A single WhereMaskSet structure translates
   102647 ** cursor number into bits and the translated bit is stored in the prereq
   102648 ** fields.  The translation is used in order to maximize the number of
   102649 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   102650 ** spread out over the non-negative integers.  For example, the cursor
   102651 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   102652 ** translates these sparse cursor numbers into consecutive integers
   102653 ** beginning with 0 in order to make the best possible use of the available
   102654 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   102655 ** would be mapped into integers 0 through 7.
   102656 **
   102657 ** The number of terms in a join is limited by the number of bits
   102658 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   102659 ** is only able to process joins with 64 or fewer tables.
   102660 */
   102661 typedef struct WhereTerm WhereTerm;
   102662 struct WhereTerm {
   102663   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   102664   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   102665   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   102666   union {
   102667     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   102668     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
   102669     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
   102670   } u;
   102671   u16 eOperator;          /* A WO_xx value describing <op> */
   102672   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   102673   u8 nChild;              /* Number of children that must disable us */
   102674   WhereClause *pWC;       /* The clause this term is part of */
   102675   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   102676   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   102677 };
   102678 
   102679 /*
   102680 ** Allowed values of WhereTerm.wtFlags
   102681 */
   102682 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   102683 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   102684 #define TERM_CODED      0x04   /* This term is already coded */
   102685 #define TERM_COPIED     0x08   /* Has a child */
   102686 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   102687 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   102688 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   102689 #ifdef SQLITE_ENABLE_STAT3
   102690 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
   102691 #else
   102692 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
   102693 #endif
   102694 
   102695 /*
   102696 ** An instance of the following structure holds all information about a
   102697 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   102698 **
   102699 ** Explanation of pOuter:  For a WHERE clause of the form
   102700 **
   102701 **           a AND ((b AND c) OR (d AND e)) AND f
   102702 **
   102703 ** There are separate WhereClause objects for the whole clause and for
   102704 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
   102705 ** subclauses points to the WhereClause object for the whole clause.
   102706 */
   102707 struct WhereClause {
   102708   Parse *pParse;           /* The parser context */
   102709   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
   102710   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
   102711   WhereClause *pOuter;     /* Outer conjunction */
   102712   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   102713   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
   102714   int nTerm;               /* Number of terms */
   102715   int nSlot;               /* Number of entries in a[] */
   102716   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   102717 #if defined(SQLITE_SMALL_STACK)
   102718   WhereTerm aStatic[1];    /* Initial static space for a[] */
   102719 #else
   102720   WhereTerm aStatic[8];    /* Initial static space for a[] */
   102721 #endif
   102722 };
   102723 
   102724 /*
   102725 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   102726 ** a dynamically allocated instance of the following structure.
   102727 */
   102728 struct WhereOrInfo {
   102729   WhereClause wc;          /* Decomposition into subterms */
   102730   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   102731 };
   102732 
   102733 /*
   102734 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   102735 ** a dynamically allocated instance of the following structure.
   102736 */
   102737 struct WhereAndInfo {
   102738   WhereClause wc;          /* The subexpression broken out */
   102739 };
   102740 
   102741 /*
   102742 ** An instance of the following structure keeps track of a mapping
   102743 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   102744 **
   102745 ** The VDBE cursor numbers are small integers contained in
   102746 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   102747 ** clause, the cursor numbers might not begin with 0 and they might
   102748 ** contain gaps in the numbering sequence.  But we want to make maximum
   102749 ** use of the bits in our bitmasks.  This structure provides a mapping
   102750 ** from the sparse cursor numbers into consecutive integers beginning
   102751 ** with 0.
   102752 **
   102753 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   102754 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   102755 **
   102756 ** For example, if the WHERE clause expression used these VDBE
   102757 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   102758 ** would map those cursor numbers into bits 0 through 5.
   102759 **
   102760 ** Note that the mapping is not necessarily ordered.  In the example
   102761 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   102762 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   102763 ** does not really matter.  What is important is that sparse cursor
   102764 ** numbers all get mapped into bit numbers that begin with 0 and contain
   102765 ** no gaps.
   102766 */
   102767 struct WhereMaskSet {
   102768   int n;                        /* Number of assigned cursor values */
   102769   int ix[BMS];                  /* Cursor assigned to each bit */
   102770 };
   102771 
   102772 /*
   102773 ** A WhereCost object records a lookup strategy and the estimated
   102774 ** cost of pursuing that strategy.
   102775 */
   102776 struct WhereCost {
   102777   WherePlan plan;    /* The lookup strategy */
   102778   double rCost;      /* Overall cost of pursuing this search strategy */
   102779   Bitmask used;      /* Bitmask of cursors used by this plan */
   102780 };
   102781 
   102782 /*
   102783 ** Bitmasks for the operators that indices are able to exploit.  An
   102784 ** OR-ed combination of these values can be used when searching for
   102785 ** terms in the where clause.
   102786 */
   102787 #define WO_IN     0x001
   102788 #define WO_EQ     0x002
   102789 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   102790 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   102791 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   102792 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   102793 #define WO_MATCH  0x040
   102794 #define WO_ISNULL 0x080
   102795 #define WO_OR     0x100       /* Two or more OR-connected terms */
   102796 #define WO_AND    0x200       /* Two or more AND-connected terms */
   102797 #define WO_NOOP   0x800       /* This term does not restrict search space */
   102798 
   102799 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   102800 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   102801 
   102802 /*
   102803 ** Value for wsFlags returned by bestIndex() and stored in
   102804 ** WhereLevel.wsFlags.  These flags determine which search
   102805 ** strategies are appropriate.
   102806 **
   102807 ** The least significant 12 bits is reserved as a mask for WO_ values above.
   102808 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
   102809 ** But if the table is the right table of a left join, WhereLevel.wsFlags
   102810 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
   102811 ** the "op" parameter to findTerm when we are resolving equality constraints.
   102812 ** ISNULL constraints will then not be used on the right table of a left
   102813 ** join.  Tickets #2177 and #2189.
   102814 */
   102815 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
   102816 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
   102817 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
   102818 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
   102819 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
   102820 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
   102821 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
   102822 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
   102823 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
   102824 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
   102825 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
   102826 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
   102827 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
   102828 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
   102829 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
   102830 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
   102831 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
   102832 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
   102833 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
   102834 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
   102835 
   102836 /*
   102837 ** Initialize a preallocated WhereClause structure.
   102838 */
   102839 static void whereClauseInit(
   102840   WhereClause *pWC,        /* The WhereClause to be initialized */
   102841   Parse *pParse,           /* The parsing context */
   102842   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
   102843   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
   102844 ){
   102845   pWC->pParse = pParse;
   102846   pWC->pMaskSet = pMaskSet;
   102847   pWC->pOuter = 0;
   102848   pWC->nTerm = 0;
   102849   pWC->nSlot = ArraySize(pWC->aStatic);
   102850   pWC->a = pWC->aStatic;
   102851   pWC->vmask = 0;
   102852   pWC->wctrlFlags = wctrlFlags;
   102853 }
   102854 
   102855 /* Forward reference */
   102856 static void whereClauseClear(WhereClause*);
   102857 
   102858 /*
   102859 ** Deallocate all memory associated with a WhereOrInfo object.
   102860 */
   102861 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   102862   whereClauseClear(&p->wc);
   102863   sqlite3DbFree(db, p);
   102864 }
   102865 
   102866 /*
   102867 ** Deallocate all memory associated with a WhereAndInfo object.
   102868 */
   102869 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   102870   whereClauseClear(&p->wc);
   102871   sqlite3DbFree(db, p);
   102872 }
   102873 
   102874 /*
   102875 ** Deallocate a WhereClause structure.  The WhereClause structure
   102876 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   102877 */
   102878 static void whereClauseClear(WhereClause *pWC){
   102879   int i;
   102880   WhereTerm *a;
   102881   sqlite3 *db = pWC->pParse->db;
   102882   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   102883     if( a->wtFlags & TERM_DYNAMIC ){
   102884       sqlite3ExprDelete(db, a->pExpr);
   102885     }
   102886     if( a->wtFlags & TERM_ORINFO ){
   102887       whereOrInfoDelete(db, a->u.pOrInfo);
   102888     }else if( a->wtFlags & TERM_ANDINFO ){
   102889       whereAndInfoDelete(db, a->u.pAndInfo);
   102890     }
   102891   }
   102892   if( pWC->a!=pWC->aStatic ){
   102893     sqlite3DbFree(db, pWC->a);
   102894   }
   102895 }
   102896 
   102897 /*
   102898 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   102899 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   102900 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   102901 ** 0 is returned if the new WhereTerm could not be added due to a memory
   102902 ** allocation error.  The memory allocation failure will be recorded in
   102903 ** the db->mallocFailed flag so that higher-level functions can detect it.
   102904 **
   102905 ** This routine will increase the size of the pWC->a[] array as necessary.
   102906 **
   102907 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   102908 ** for freeing the expression p is assumed by the WhereClause object pWC.
   102909 ** This is true even if this routine fails to allocate a new WhereTerm.
   102910 **
   102911 ** WARNING:  This routine might reallocate the space used to store
   102912 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   102913 ** calling this routine.  Such pointers may be reinitialized by referencing
   102914 ** the pWC->a[] array.
   102915 */
   102916 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   102917   WhereTerm *pTerm;
   102918   int idx;
   102919   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
   102920   if( pWC->nTerm>=pWC->nSlot ){
   102921     WhereTerm *pOld = pWC->a;
   102922     sqlite3 *db = pWC->pParse->db;
   102923     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   102924     if( pWC->a==0 ){
   102925       if( wtFlags & TERM_DYNAMIC ){
   102926         sqlite3ExprDelete(db, p);
   102927       }
   102928       pWC->a = pOld;
   102929       return 0;
   102930     }
   102931     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   102932     if( pOld!=pWC->aStatic ){
   102933       sqlite3DbFree(db, pOld);
   102934     }
   102935     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   102936   }
   102937   pTerm = &pWC->a[idx = pWC->nTerm++];
   102938   pTerm->pExpr = p;
   102939   pTerm->wtFlags = wtFlags;
   102940   pTerm->pWC = pWC;
   102941   pTerm->iParent = -1;
   102942   return idx;
   102943 }
   102944 
   102945 /*
   102946 ** This routine identifies subexpressions in the WHERE clause where
   102947 ** each subexpression is separated by the AND operator or some other
   102948 ** operator specified in the op parameter.  The WhereClause structure
   102949 ** is filled with pointers to subexpressions.  For example:
   102950 **
   102951 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   102952 **           \________/     \_______________/     \________________/
   102953 **            slot[0]            slot[1]               slot[2]
   102954 **
   102955 ** The original WHERE clause in pExpr is unaltered.  All this routine
   102956 ** does is make slot[] entries point to substructure within pExpr.
   102957 **
   102958 ** In the previous sentence and in the diagram, "slot[]" refers to
   102959 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   102960 ** all terms of the WHERE clause.
   102961 */
   102962 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
   102963   pWC->op = (u8)op;
   102964   if( pExpr==0 ) return;
   102965   if( pExpr->op!=op ){
   102966     whereClauseInsert(pWC, pExpr, 0);
   102967   }else{
   102968     whereSplit(pWC, pExpr->pLeft, op);
   102969     whereSplit(pWC, pExpr->pRight, op);
   102970   }
   102971 }
   102972 
   102973 /*
   102974 ** Initialize an expression mask set (a WhereMaskSet object)
   102975 */
   102976 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
   102977 
   102978 /*
   102979 ** Return the bitmask for the given cursor number.  Return 0 if
   102980 ** iCursor is not in the set.
   102981 */
   102982 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   102983   int i;
   102984   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
   102985   for(i=0; i<pMaskSet->n; i++){
   102986     if( pMaskSet->ix[i]==iCursor ){
   102987       return ((Bitmask)1)<<i;
   102988     }
   102989   }
   102990   return 0;
   102991 }
   102992 
   102993 /*
   102994 ** Create a new mask for cursor iCursor.
   102995 **
   102996 ** There is one cursor per table in the FROM clause.  The number of
   102997 ** tables in the FROM clause is limited by a test early in the
   102998 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   102999 ** array will never overflow.
   103000 */
   103001 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   103002   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   103003   pMaskSet->ix[pMaskSet->n++] = iCursor;
   103004 }
   103005 
   103006 /*
   103007 ** This routine walks (recursively) an expression tree and generates
   103008 ** a bitmask indicating which tables are used in that expression
   103009 ** tree.
   103010 **
   103011 ** In order for this routine to work, the calling function must have
   103012 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
   103013 ** the header comment on that routine for additional information.
   103014 ** The sqlite3ResolveExprNames() routines looks for column names and
   103015 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
   103016 ** the VDBE cursor number of the table.  This routine just has to
   103017 ** translate the cursor numbers into bitmask values and OR all
   103018 ** the bitmasks together.
   103019 */
   103020 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   103021 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   103022 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   103023   Bitmask mask = 0;
   103024   if( p==0 ) return 0;
   103025   if( p->op==TK_COLUMN ){
   103026     mask = getMask(pMaskSet, p->iTable);
   103027     return mask;
   103028   }
   103029   mask = exprTableUsage(pMaskSet, p->pRight);
   103030   mask |= exprTableUsage(pMaskSet, p->pLeft);
   103031   if( ExprHasProperty(p, EP_xIsSelect) ){
   103032     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   103033   }else{
   103034     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   103035   }
   103036   return mask;
   103037 }
   103038 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   103039   int i;
   103040   Bitmask mask = 0;
   103041   if( pList ){
   103042     for(i=0; i<pList->nExpr; i++){
   103043       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   103044     }
   103045   }
   103046   return mask;
   103047 }
   103048 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   103049   Bitmask mask = 0;
   103050   while( pS ){
   103051     SrcList *pSrc = pS->pSrc;
   103052     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   103053     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   103054     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   103055     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   103056     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   103057     if( ALWAYS(pSrc!=0) ){
   103058       int i;
   103059       for(i=0; i<pSrc->nSrc; i++){
   103060         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
   103061         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
   103062       }
   103063     }
   103064     pS = pS->pPrior;
   103065   }
   103066   return mask;
   103067 }
   103068 
   103069 /*
   103070 ** Return TRUE if the given operator is one of the operators that is
   103071 ** allowed for an indexable WHERE clause term.  The allowed operators are
   103072 ** "=", "<", ">", "<=", ">=", and "IN".
   103073 **
   103074 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
   103075 ** of one of the following forms: column = expression column > expression
   103076 ** column >= expression column < expression column <= expression
   103077 ** expression = column expression > column expression >= column
   103078 ** expression < column expression <= column column IN
   103079 ** (expression-list) column IN (subquery) column IS NULL
   103080 */
   103081 static int allowedOp(int op){
   103082   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   103083   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   103084   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   103085   assert( TK_GE==TK_EQ+4 );
   103086   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   103087 }
   103088 
   103089 /*
   103090 ** Swap two objects of type TYPE.
   103091 */
   103092 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   103093 
   103094 /*
   103095 ** Commute a comparison operator.  Expressions of the form "X op Y"
   103096 ** are converted into "Y op X".
   103097 **
   103098 ** If a collation sequence is associated with either the left or right
   103099 ** side of the comparison, it remains associated with the same side after
   103100 ** the commutation. So "Y collate NOCASE op X" becomes
   103101 ** "X collate NOCASE op Y". This is because any collation sequence on
   103102 ** the left hand side of a comparison overrides any collation sequence
   103103 ** attached to the right. For the same reason the EP_ExpCollate flag
   103104 ** is not commuted.
   103105 */
   103106 static void exprCommute(Parse *pParse, Expr *pExpr){
   103107   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
   103108   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
   103109   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   103110   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
   103111   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   103112   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
   103113   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
   103114   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
   103115   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   103116   if( pExpr->op>=TK_GT ){
   103117     assert( TK_LT==TK_GT+2 );
   103118     assert( TK_GE==TK_LE+2 );
   103119     assert( TK_GT>TK_EQ );
   103120     assert( TK_GT<TK_LE );
   103121     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   103122     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   103123   }
   103124 }
   103125 
   103126 /*
   103127 ** Translate from TK_xx operator to WO_xx bitmask.
   103128 */
   103129 static u16 operatorMask(int op){
   103130   u16 c;
   103131   assert( allowedOp(op) );
   103132   if( op==TK_IN ){
   103133     c = WO_IN;
   103134   }else if( op==TK_ISNULL ){
   103135     c = WO_ISNULL;
   103136   }else{
   103137     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   103138     c = (u16)(WO_EQ<<(op-TK_EQ));
   103139   }
   103140   assert( op!=TK_ISNULL || c==WO_ISNULL );
   103141   assert( op!=TK_IN || c==WO_IN );
   103142   assert( op!=TK_EQ || c==WO_EQ );
   103143   assert( op!=TK_LT || c==WO_LT );
   103144   assert( op!=TK_LE || c==WO_LE );
   103145   assert( op!=TK_GT || c==WO_GT );
   103146   assert( op!=TK_GE || c==WO_GE );
   103147   return c;
   103148 }
   103149 
   103150 /*
   103151 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   103152 ** where X is a reference to the iColumn of table iCur and <op> is one of
   103153 ** the WO_xx operator codes specified by the op parameter.
   103154 ** Return a pointer to the term.  Return 0 if not found.
   103155 */
   103156 static WhereTerm *findTerm(
   103157   WhereClause *pWC,     /* The WHERE clause to be searched */
   103158   int iCur,             /* Cursor number of LHS */
   103159   int iColumn,          /* Column number of LHS */
   103160   Bitmask notReady,     /* RHS must not overlap with this mask */
   103161   u32 op,               /* Mask of WO_xx values describing operator */
   103162   Index *pIdx           /* Must be compatible with this index, if not NULL */
   103163 ){
   103164   WhereTerm *pTerm;
   103165   int k;
   103166   assert( iCur>=0 );
   103167   op &= WO_ALL;
   103168   for(; pWC; pWC=pWC->pOuter){
   103169     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
   103170       if( pTerm->leftCursor==iCur
   103171          && (pTerm->prereqRight & notReady)==0
   103172          && pTerm->u.leftColumn==iColumn
   103173          && (pTerm->eOperator & op)!=0
   103174       ){
   103175         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
   103176           Expr *pX = pTerm->pExpr;
   103177           CollSeq *pColl;
   103178           char idxaff;
   103179           int j;
   103180           Parse *pParse = pWC->pParse;
   103181 
   103182           idxaff = pIdx->pTable->aCol[iColumn].affinity;
   103183           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
   103184 
   103185           /* Figure out the collation sequence required from an index for
   103186           ** it to be useful for optimising expression pX. Store this
   103187           ** value in variable pColl.
   103188           */
   103189           assert(pX->pLeft);
   103190           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   103191           assert(pColl || pParse->nErr);
   103192 
   103193           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   103194             if( NEVER(j>=pIdx->nColumn) ) return 0;
   103195           }
   103196           if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
   103197         }
   103198         return pTerm;
   103199       }
   103200     }
   103201   }
   103202   return 0;
   103203 }
   103204 
   103205 /* Forward reference */
   103206 static void exprAnalyze(SrcList*, WhereClause*, int);
   103207 
   103208 /*
   103209 ** Call exprAnalyze on all terms in a WHERE clause.
   103210 **
   103211 **
   103212 */
   103213 static void exprAnalyzeAll(
   103214   SrcList *pTabList,       /* the FROM clause */
   103215   WhereClause *pWC         /* the WHERE clause to be analyzed */
   103216 ){
   103217   int i;
   103218   for(i=pWC->nTerm-1; i>=0; i--){
   103219     exprAnalyze(pTabList, pWC, i);
   103220   }
   103221 }
   103222 
   103223 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   103224 /*
   103225 ** Check to see if the given expression is a LIKE or GLOB operator that
   103226 ** can be optimized using inequality constraints.  Return TRUE if it is
   103227 ** so and false if not.
   103228 **
   103229 ** In order for the operator to be optimizible, the RHS must be a string
   103230 ** literal that does not begin with a wildcard.
   103231 */
   103232 static int isLikeOrGlob(
   103233   Parse *pParse,    /* Parsing and code generating context */
   103234   Expr *pExpr,      /* Test this expression */
   103235   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   103236   int *pisComplete, /* True if the only wildcard is % in the last character */
   103237   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   103238 ){
   103239   const char *z = 0;         /* String on RHS of LIKE operator */
   103240   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   103241   ExprList *pList;           /* List of operands to the LIKE operator */
   103242   int c;                     /* One character in z[] */
   103243   int cnt;                   /* Number of non-wildcard prefix characters */
   103244   char wc[3];                /* Wildcard characters */
   103245   sqlite3 *db = pParse->db;  /* Database connection */
   103246   sqlite3_value *pVal = 0;
   103247   int op;                    /* Opcode of pRight */
   103248 
   103249   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   103250     return 0;
   103251   }
   103252 #ifdef SQLITE_EBCDIC
   103253   if( *pnoCase ) return 0;
   103254 #endif
   103255   pList = pExpr->x.pList;
   103256   pLeft = pList->a[1].pExpr;
   103257   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
   103258     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   103259     ** be the name of an indexed column with TEXT affinity. */
   103260     return 0;
   103261   }
   103262   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   103263 
   103264   pRight = pList->a[0].pExpr;
   103265   op = pRight->op;
   103266   if( op==TK_REGISTER ){
   103267     op = pRight->op2;
   103268   }
   103269   if( op==TK_VARIABLE ){
   103270     Vdbe *pReprepare = pParse->pReprepare;
   103271     int iCol = pRight->iColumn;
   103272     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
   103273     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   103274       z = (char *)sqlite3_value_text(pVal);
   103275     }
   103276     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
   103277     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   103278   }else if( op==TK_STRING ){
   103279     z = pRight->u.zToken;
   103280   }
   103281   if( z ){
   103282     cnt = 0;
   103283     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   103284       cnt++;
   103285     }
   103286     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   103287       Expr *pPrefix;
   103288       *pisComplete = c==wc[0] && z[cnt+1]==0;
   103289       pPrefix = sqlite3Expr(db, TK_STRING, z);
   103290       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   103291       *ppPrefix = pPrefix;
   103292       if( op==TK_VARIABLE ){
   103293         Vdbe *v = pParse->pVdbe;
   103294         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   103295         if( *pisComplete && pRight->u.zToken[1] ){
   103296           /* If the rhs of the LIKE expression is a variable, and the current
   103297           ** value of the variable means there is no need to invoke the LIKE
   103298           ** function, then no OP_Variable will be added to the program.
   103299           ** This causes problems for the sqlite3_bind_parameter_name()
   103300           ** API. To workaround them, add a dummy OP_Variable here.
   103301           */
   103302           int r1 = sqlite3GetTempReg(pParse);
   103303           sqlite3ExprCodeTarget(pParse, pRight, r1);
   103304           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   103305           sqlite3ReleaseTempReg(pParse, r1);
   103306         }
   103307       }
   103308     }else{
   103309       z = 0;
   103310     }
   103311   }
   103312 
   103313   sqlite3ValueFree(pVal);
   103314   return (z!=0);
   103315 }
   103316 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   103317 
   103318 
   103319 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103320 /*
   103321 ** Check to see if the given expression is of the form
   103322 **
   103323 **         column MATCH expr
   103324 **
   103325 ** If it is then return TRUE.  If not, return FALSE.
   103326 */
   103327 static int isMatchOfColumn(
   103328   Expr *pExpr      /* Test this expression */
   103329 ){
   103330   ExprList *pList;
   103331 
   103332   if( pExpr->op!=TK_FUNCTION ){
   103333     return 0;
   103334   }
   103335   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   103336     return 0;
   103337   }
   103338   pList = pExpr->x.pList;
   103339   if( pList->nExpr!=2 ){
   103340     return 0;
   103341   }
   103342   if( pList->a[1].pExpr->op != TK_COLUMN ){
   103343     return 0;
   103344   }
   103345   return 1;
   103346 }
   103347 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   103348 
   103349 /*
   103350 ** If the pBase expression originated in the ON or USING clause of
   103351 ** a join, then transfer the appropriate markings over to derived.
   103352 */
   103353 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   103354   pDerived->flags |= pBase->flags & EP_FromJoin;
   103355   pDerived->iRightJoinTable = pBase->iRightJoinTable;
   103356 }
   103357 
   103358 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   103359 /*
   103360 ** Analyze a term that consists of two or more OR-connected
   103361 ** subterms.  So in:
   103362 **
   103363 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   103364 **                          ^^^^^^^^^^^^^^^^^^^^
   103365 **
   103366 ** This routine analyzes terms such as the middle term in the above example.
   103367 ** A WhereOrTerm object is computed and attached to the term under
   103368 ** analysis, regardless of the outcome of the analysis.  Hence:
   103369 **
   103370 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   103371 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   103372 **
   103373 ** The term being analyzed must have two or more of OR-connected subterms.
   103374 ** A single subterm might be a set of AND-connected sub-subterms.
   103375 ** Examples of terms under analysis:
   103376 **
   103377 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   103378 **     (B)     x=expr1 OR expr2=x OR x=expr3
   103379 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   103380 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   103381 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   103382 **
   103383 ** CASE 1:
   103384 **
   103385 ** If all subterms are of the form T.C=expr for some single column of C
   103386 ** a single table T (as shown in example B above) then create a new virtual
   103387 ** term that is an equivalent IN expression.  In other words, if the term
   103388 ** being analyzed is:
   103389 **
   103390 **      x = expr1  OR  expr2 = x  OR  x = expr3
   103391 **
   103392 ** then create a new virtual term like this:
   103393 **
   103394 **      x IN (expr1,expr2,expr3)
   103395 **
   103396 ** CASE 2:
   103397 **
   103398 ** If all subterms are indexable by a single table T, then set
   103399 **
   103400 **     WhereTerm.eOperator              =  WO_OR
   103401 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   103402 **
   103403 ** A subterm is "indexable" if it is of the form
   103404 ** "T.C <op> <expr>" where C is any column of table T and
   103405 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   103406 ** A subterm is also indexable if it is an AND of two or more
   103407 ** subsubterms at least one of which is indexable.  Indexable AND
   103408 ** subterms have their eOperator set to WO_AND and they have
   103409 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   103410 **
   103411 ** From another point of view, "indexable" means that the subterm could
   103412 ** potentially be used with an index if an appropriate index exists.
   103413 ** This analysis does not consider whether or not the index exists; that
   103414 ** is something the bestIndex() routine will determine.  This analysis
   103415 ** only looks at whether subterms appropriate for indexing exist.
   103416 **
   103417 ** All examples A through E above all satisfy case 2.  But if a term
   103418 ** also statisfies case 1 (such as B) we know that the optimizer will
   103419 ** always prefer case 1, so in that case we pretend that case 2 is not
   103420 ** satisfied.
   103421 **
   103422 ** It might be the case that multiple tables are indexable.  For example,
   103423 ** (E) above is indexable on tables P, Q, and R.
   103424 **
   103425 ** Terms that satisfy case 2 are candidates for lookup by using
   103426 ** separate indices to find rowids for each subterm and composing
   103427 ** the union of all rowids using a RowSet object.  This is similar
   103428 ** to "bitmap indices" in other database engines.
   103429 **
   103430 ** OTHERWISE:
   103431 **
   103432 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   103433 ** zero.  This term is not useful for search.
   103434 */
   103435 static void exprAnalyzeOrTerm(
   103436   SrcList *pSrc,            /* the FROM clause */
   103437   WhereClause *pWC,         /* the complete WHERE clause */
   103438   int idxTerm               /* Index of the OR-term to be analyzed */
   103439 ){
   103440   Parse *pParse = pWC->pParse;            /* Parser context */
   103441   sqlite3 *db = pParse->db;               /* Database connection */
   103442   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   103443   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   103444   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
   103445   int i;                                  /* Loop counters */
   103446   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   103447   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   103448   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   103449   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   103450   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   103451 
   103452   /*
   103453   ** Break the OR clause into its separate subterms.  The subterms are
   103454   ** stored in a WhereClause structure containing within the WhereOrInfo
   103455   ** object that is attached to the original OR clause term.
   103456   */
   103457   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   103458   assert( pExpr->op==TK_OR );
   103459   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   103460   if( pOrInfo==0 ) return;
   103461   pTerm->wtFlags |= TERM_ORINFO;
   103462   pOrWc = &pOrInfo->wc;
   103463   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
   103464   whereSplit(pOrWc, pExpr, TK_OR);
   103465   exprAnalyzeAll(pSrc, pOrWc);
   103466   if( db->mallocFailed ) return;
   103467   assert( pOrWc->nTerm>=2 );
   103468 
   103469   /*
   103470   ** Compute the set of tables that might satisfy cases 1 or 2.
   103471   */
   103472   indexable = ~(Bitmask)0;
   103473   chngToIN = ~(pWC->vmask);
   103474   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   103475     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   103476       WhereAndInfo *pAndInfo;
   103477       assert( pOrTerm->eOperator==0 );
   103478       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   103479       chngToIN = 0;
   103480       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   103481       if( pAndInfo ){
   103482         WhereClause *pAndWC;
   103483         WhereTerm *pAndTerm;
   103484         int j;
   103485         Bitmask b = 0;
   103486         pOrTerm->u.pAndInfo = pAndInfo;
   103487         pOrTerm->wtFlags |= TERM_ANDINFO;
   103488         pOrTerm->eOperator = WO_AND;
   103489         pAndWC = &pAndInfo->wc;
   103490         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
   103491         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   103492         exprAnalyzeAll(pSrc, pAndWC);
   103493         pAndWC->pOuter = pWC;
   103494         testcase( db->mallocFailed );
   103495         if( !db->mallocFailed ){
   103496           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   103497             assert( pAndTerm->pExpr );
   103498             if( allowedOp(pAndTerm->pExpr->op) ){
   103499               b |= getMask(pMaskSet, pAndTerm->leftCursor);
   103500             }
   103501           }
   103502         }
   103503         indexable &= b;
   103504       }
   103505     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   103506       /* Skip this term for now.  We revisit it when we process the
   103507       ** corresponding TERM_VIRTUAL term */
   103508     }else{
   103509       Bitmask b;
   103510       b = getMask(pMaskSet, pOrTerm->leftCursor);
   103511       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   103512         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   103513         b |= getMask(pMaskSet, pOther->leftCursor);
   103514       }
   103515       indexable &= b;
   103516       if( pOrTerm->eOperator!=WO_EQ ){
   103517         chngToIN = 0;
   103518       }else{
   103519         chngToIN &= b;
   103520       }
   103521     }
   103522   }
   103523 
   103524   /*
   103525   ** Record the set of tables that satisfy case 2.  The set might be
   103526   ** empty.
   103527   */
   103528   pOrInfo->indexable = indexable;
   103529   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   103530 
   103531   /*
   103532   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   103533   ** we have to do some additional checking to see if case 1 really
   103534   ** is satisfied.
   103535   **
   103536   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   103537   ** that there is no possibility of transforming the OR clause into an
   103538   ** IN operator because one or more terms in the OR clause contain
   103539   ** something other than == on a column in the single table.  The 1-bit
   103540   ** case means that every term of the OR clause is of the form
   103541   ** "table.column=expr" for some single table.  The one bit that is set
   103542   ** will correspond to the common table.  We still need to check to make
   103543   ** sure the same column is used on all terms.  The 2-bit case is when
   103544   ** the all terms are of the form "table1.column=table2.column".  It
   103545   ** might be possible to form an IN operator with either table1.column
   103546   ** or table2.column as the LHS if either is common to every term of
   103547   ** the OR clause.
   103548   **
   103549   ** Note that terms of the form "table.column1=table.column2" (the
   103550   ** same table on both sizes of the ==) cannot be optimized.
   103551   */
   103552   if( chngToIN ){
   103553     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   103554     int iColumn = -1;         /* Column index on lhs of IN operator */
   103555     int iCursor = -1;         /* Table cursor common to all terms */
   103556     int j = 0;                /* Loop counter */
   103557 
   103558     /* Search for a table and column that appears on one side or the
   103559     ** other of the == operator in every subterm.  That table and column
   103560     ** will be recorded in iCursor and iColumn.  There might not be any
   103561     ** such table and column.  Set okToChngToIN if an appropriate table
   103562     ** and column is found but leave okToChngToIN false if not found.
   103563     */
   103564     for(j=0; j<2 && !okToChngToIN; j++){
   103565       pOrTerm = pOrWc->a;
   103566       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   103567         assert( pOrTerm->eOperator==WO_EQ );
   103568         pOrTerm->wtFlags &= ~TERM_OR_OK;
   103569         if( pOrTerm->leftCursor==iCursor ){
   103570           /* This is the 2-bit case and we are on the second iteration and
   103571           ** current term is from the first iteration.  So skip this term. */
   103572           assert( j==1 );
   103573           continue;
   103574         }
   103575         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
   103576           /* This term must be of the form t1.a==t2.b where t2 is in the
   103577           ** chngToIN set but t1 is not.  This term will be either preceeded
   103578           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   103579           ** and use its inversion. */
   103580           testcase( pOrTerm->wtFlags & TERM_COPIED );
   103581           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   103582           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   103583           continue;
   103584         }
   103585         iColumn = pOrTerm->u.leftColumn;
   103586         iCursor = pOrTerm->leftCursor;
   103587         break;
   103588       }
   103589       if( i<0 ){
   103590         /* No candidate table+column was found.  This can only occur
   103591         ** on the second iteration */
   103592         assert( j==1 );
   103593         assert( (chngToIN&(chngToIN-1))==0 );
   103594         assert( chngToIN==getMask(pMaskSet, iCursor) );
   103595         break;
   103596       }
   103597       testcase( j==1 );
   103598 
   103599       /* We have found a candidate table and column.  Check to see if that
   103600       ** table and column is common to every term in the OR clause */
   103601       okToChngToIN = 1;
   103602       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   103603         assert( pOrTerm->eOperator==WO_EQ );
   103604         if( pOrTerm->leftCursor!=iCursor ){
   103605           pOrTerm->wtFlags &= ~TERM_OR_OK;
   103606         }else if( pOrTerm->u.leftColumn!=iColumn ){
   103607           okToChngToIN = 0;
   103608         }else{
   103609           int affLeft, affRight;
   103610           /* If the right-hand side is also a column, then the affinities
   103611           ** of both right and left sides must be such that no type
   103612           ** conversions are required on the right.  (Ticket #2249)
   103613           */
   103614           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   103615           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   103616           if( affRight!=0 && affRight!=affLeft ){
   103617             okToChngToIN = 0;
   103618           }else{
   103619             pOrTerm->wtFlags |= TERM_OR_OK;
   103620           }
   103621         }
   103622       }
   103623     }
   103624 
   103625     /* At this point, okToChngToIN is true if original pTerm satisfies
   103626     ** case 1.  In that case, construct a new virtual term that is
   103627     ** pTerm converted into an IN operator.
   103628     **
   103629     ** EV: R-00211-15100
   103630     */
   103631     if( okToChngToIN ){
   103632       Expr *pDup;            /* A transient duplicate expression */
   103633       ExprList *pList = 0;   /* The RHS of the IN operator */
   103634       Expr *pLeft = 0;       /* The LHS of the IN operator */
   103635       Expr *pNew;            /* The complete IN operator */
   103636 
   103637       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   103638         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   103639         assert( pOrTerm->eOperator==WO_EQ );
   103640         assert( pOrTerm->leftCursor==iCursor );
   103641         assert( pOrTerm->u.leftColumn==iColumn );
   103642         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   103643         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
   103644         pLeft = pOrTerm->pExpr->pLeft;
   103645       }
   103646       assert( pLeft!=0 );
   103647       pDup = sqlite3ExprDup(db, pLeft, 0);
   103648       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   103649       if( pNew ){
   103650         int idxNew;
   103651         transferJoinMarkings(pNew, pExpr);
   103652         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   103653         pNew->x.pList = pList;
   103654         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   103655         testcase( idxNew==0 );
   103656         exprAnalyze(pSrc, pWC, idxNew);
   103657         pTerm = &pWC->a[idxTerm];
   103658         pWC->a[idxNew].iParent = idxTerm;
   103659         pTerm->nChild = 1;
   103660       }else{
   103661         sqlite3ExprListDelete(db, pList);
   103662       }
   103663       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
   103664     }
   103665   }
   103666 }
   103667 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   103668 
   103669 
   103670 /*
   103671 ** The input to this routine is an WhereTerm structure with only the
   103672 ** "pExpr" field filled in.  The job of this routine is to analyze the
   103673 ** subexpression and populate all the other fields of the WhereTerm
   103674 ** structure.
   103675 **
   103676 ** If the expression is of the form "<expr> <op> X" it gets commuted
   103677 ** to the standard form of "X <op> <expr>".
   103678 **
   103679 ** If the expression is of the form "X <op> Y" where both X and Y are
   103680 ** columns, then the original expression is unchanged and a new virtual
   103681 ** term of the form "Y <op> X" is added to the WHERE clause and
   103682 ** analyzed separately.  The original term is marked with TERM_COPIED
   103683 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   103684 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   103685 ** is a commuted copy of a prior term.)  The original term has nChild=1
   103686 ** and the copy has idxParent set to the index of the original term.
   103687 */
   103688 static void exprAnalyze(
   103689   SrcList *pSrc,            /* the FROM clause */
   103690   WhereClause *pWC,         /* the WHERE clause */
   103691   int idxTerm               /* Index of the term to be analyzed */
   103692 ){
   103693   WhereTerm *pTerm;                /* The term to be analyzed */
   103694   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   103695   Expr *pExpr;                     /* The expression to be analyzed */
   103696   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   103697   Bitmask prereqAll;               /* Prerequesites of pExpr */
   103698   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   103699   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   103700   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   103701   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   103702   int op;                          /* Top-level operator.  pExpr->op */
   103703   Parse *pParse = pWC->pParse;     /* Parsing context */
   103704   sqlite3 *db = pParse->db;        /* Database connection */
   103705 
   103706   if( db->mallocFailed ){
   103707     return;
   103708   }
   103709   pTerm = &pWC->a[idxTerm];
   103710   pMaskSet = pWC->pMaskSet;
   103711   pExpr = pTerm->pExpr;
   103712   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   103713   op = pExpr->op;
   103714   if( op==TK_IN ){
   103715     assert( pExpr->pRight==0 );
   103716     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   103717       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   103718     }else{
   103719       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   103720     }
   103721   }else if( op==TK_ISNULL ){
   103722     pTerm->prereqRight = 0;
   103723   }else{
   103724     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   103725   }
   103726   prereqAll = exprTableUsage(pMaskSet, pExpr);
   103727   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   103728     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   103729     prereqAll |= x;
   103730     extraRight = x-1;  /* ON clause terms may not be used with an index
   103731                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   103732   }
   103733   pTerm->prereqAll = prereqAll;
   103734   pTerm->leftCursor = -1;
   103735   pTerm->iParent = -1;
   103736   pTerm->eOperator = 0;
   103737   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
   103738     Expr *pLeft = pExpr->pLeft;
   103739     Expr *pRight = pExpr->pRight;
   103740     if( pLeft->op==TK_COLUMN ){
   103741       pTerm->leftCursor = pLeft->iTable;
   103742       pTerm->u.leftColumn = pLeft->iColumn;
   103743       pTerm->eOperator = operatorMask(op);
   103744     }
   103745     if( pRight && pRight->op==TK_COLUMN ){
   103746       WhereTerm *pNew;
   103747       Expr *pDup;
   103748       if( pTerm->leftCursor>=0 ){
   103749         int idxNew;
   103750         pDup = sqlite3ExprDup(db, pExpr, 0);
   103751         if( db->mallocFailed ){
   103752           sqlite3ExprDelete(db, pDup);
   103753           return;
   103754         }
   103755         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   103756         if( idxNew==0 ) return;
   103757         pNew = &pWC->a[idxNew];
   103758         pNew->iParent = idxTerm;
   103759         pTerm = &pWC->a[idxTerm];
   103760         pTerm->nChild = 1;
   103761         pTerm->wtFlags |= TERM_COPIED;
   103762       }else{
   103763         pDup = pExpr;
   103764         pNew = pTerm;
   103765       }
   103766       exprCommute(pParse, pDup);
   103767       pLeft = pDup->pLeft;
   103768       pNew->leftCursor = pLeft->iTable;
   103769       pNew->u.leftColumn = pLeft->iColumn;
   103770       testcase( (prereqLeft | extraRight) != prereqLeft );
   103771       pNew->prereqRight = prereqLeft | extraRight;
   103772       pNew->prereqAll = prereqAll;
   103773       pNew->eOperator = operatorMask(pDup->op);
   103774     }
   103775   }
   103776 
   103777 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   103778   /* If a term is the BETWEEN operator, create two new virtual terms
   103779   ** that define the range that the BETWEEN implements.  For example:
   103780   **
   103781   **      a BETWEEN b AND c
   103782   **
   103783   ** is converted into:
   103784   **
   103785   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   103786   **
   103787   ** The two new terms are added onto the end of the WhereClause object.
   103788   ** The new terms are "dynamic" and are children of the original BETWEEN
   103789   ** term.  That means that if the BETWEEN term is coded, the children are
   103790   ** skipped.  Or, if the children are satisfied by an index, the original
   103791   ** BETWEEN term is skipped.
   103792   */
   103793   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   103794     ExprList *pList = pExpr->x.pList;
   103795     int i;
   103796     static const u8 ops[] = {TK_GE, TK_LE};
   103797     assert( pList!=0 );
   103798     assert( pList->nExpr==2 );
   103799     for(i=0; i<2; i++){
   103800       Expr *pNewExpr;
   103801       int idxNew;
   103802       pNewExpr = sqlite3PExpr(pParse, ops[i],
   103803                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   103804                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   103805       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   103806       testcase( idxNew==0 );
   103807       exprAnalyze(pSrc, pWC, idxNew);
   103808       pTerm = &pWC->a[idxTerm];
   103809       pWC->a[idxNew].iParent = idxTerm;
   103810     }
   103811     pTerm->nChild = 2;
   103812   }
   103813 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   103814 
   103815 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   103816   /* Analyze a term that is composed of two or more subterms connected by
   103817   ** an OR operator.
   103818   */
   103819   else if( pExpr->op==TK_OR ){
   103820     assert( pWC->op==TK_AND );
   103821     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   103822     pTerm = &pWC->a[idxTerm];
   103823   }
   103824 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   103825 
   103826 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   103827   /* Add constraints to reduce the search space on a LIKE or GLOB
   103828   ** operator.
   103829   **
   103830   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   103831   **
   103832   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   103833   **
   103834   ** The last character of the prefix "abc" is incremented to form the
   103835   ** termination condition "abd".
   103836   */
   103837   if( pWC->op==TK_AND
   103838    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   103839   ){
   103840     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   103841     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   103842     Expr *pNewExpr1;
   103843     Expr *pNewExpr2;
   103844     int idxNew1;
   103845     int idxNew2;
   103846     CollSeq *pColl;    /* Collating sequence to use */
   103847 
   103848     pLeft = pExpr->x.pList->a[1].pExpr;
   103849     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   103850     if( !db->mallocFailed ){
   103851       u8 c, *pC;       /* Last character before the first wildcard */
   103852       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   103853       c = *pC;
   103854       if( noCase ){
   103855         /* The point is to increment the last character before the first
   103856         ** wildcard.  But if we increment '@', that will push it into the
   103857         ** alphabetic range where case conversions will mess up the
   103858         ** inequality.  To avoid this, make sure to also run the full
   103859         ** LIKE on all candidate expressions by clearing the isComplete flag
   103860         */
   103861         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
   103862 
   103863 
   103864         c = sqlite3UpperToLower[c];
   103865       }
   103866       *pC = c + 1;
   103867     }
   103868     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
   103869     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   103870                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   103871                      pStr1, 0);
   103872     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   103873     testcase( idxNew1==0 );
   103874     exprAnalyze(pSrc, pWC, idxNew1);
   103875     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   103876                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   103877                      pStr2, 0);
   103878     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   103879     testcase( idxNew2==0 );
   103880     exprAnalyze(pSrc, pWC, idxNew2);
   103881     pTerm = &pWC->a[idxTerm];
   103882     if( isComplete ){
   103883       pWC->a[idxNew1].iParent = idxTerm;
   103884       pWC->a[idxNew2].iParent = idxTerm;
   103885       pTerm->nChild = 2;
   103886     }
   103887   }
   103888 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   103889 
   103890 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103891   /* Add a WO_MATCH auxiliary term to the constraint set if the
   103892   ** current expression is of the form:  column MATCH expr.
   103893   ** This information is used by the xBestIndex methods of
   103894   ** virtual tables.  The native query optimizer does not attempt
   103895   ** to do anything with MATCH functions.
   103896   */
   103897   if( isMatchOfColumn(pExpr) ){
   103898     int idxNew;
   103899     Expr *pRight, *pLeft;
   103900     WhereTerm *pNewTerm;
   103901     Bitmask prereqColumn, prereqExpr;
   103902 
   103903     pRight = pExpr->x.pList->a[0].pExpr;
   103904     pLeft = pExpr->x.pList->a[1].pExpr;
   103905     prereqExpr = exprTableUsage(pMaskSet, pRight);
   103906     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   103907     if( (prereqExpr & prereqColumn)==0 ){
   103908       Expr *pNewExpr;
   103909       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   103910                               0, sqlite3ExprDup(db, pRight, 0), 0);
   103911       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   103912       testcase( idxNew==0 );
   103913       pNewTerm = &pWC->a[idxNew];
   103914       pNewTerm->prereqRight = prereqExpr;
   103915       pNewTerm->leftCursor = pLeft->iTable;
   103916       pNewTerm->u.leftColumn = pLeft->iColumn;
   103917       pNewTerm->eOperator = WO_MATCH;
   103918       pNewTerm->iParent = idxTerm;
   103919       pTerm = &pWC->a[idxTerm];
   103920       pTerm->nChild = 1;
   103921       pTerm->wtFlags |= TERM_COPIED;
   103922       pNewTerm->prereqAll = pTerm->prereqAll;
   103923     }
   103924   }
   103925 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   103926 
   103927 #ifdef SQLITE_ENABLE_STAT3
   103928   /* When sqlite_stat3 histogram data is available an operator of the
   103929   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
   103930   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
   103931   ** virtual term of that form.
   103932   **
   103933   ** Note that the virtual term must be tagged with TERM_VNULL.  This
   103934   ** TERM_VNULL tag will suppress the not-null check at the beginning
   103935   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
   103936   ** the start of the loop will prevent any results from being returned.
   103937   */
   103938   if( pExpr->op==TK_NOTNULL
   103939    && pExpr->pLeft->op==TK_COLUMN
   103940    && pExpr->pLeft->iColumn>=0
   103941   ){
   103942     Expr *pNewExpr;
   103943     Expr *pLeft = pExpr->pLeft;
   103944     int idxNew;
   103945     WhereTerm *pNewTerm;
   103946 
   103947     pNewExpr = sqlite3PExpr(pParse, TK_GT,
   103948                             sqlite3ExprDup(db, pLeft, 0),
   103949                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
   103950 
   103951     idxNew = whereClauseInsert(pWC, pNewExpr,
   103952                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
   103953     if( idxNew ){
   103954       pNewTerm = &pWC->a[idxNew];
   103955       pNewTerm->prereqRight = 0;
   103956       pNewTerm->leftCursor = pLeft->iTable;
   103957       pNewTerm->u.leftColumn = pLeft->iColumn;
   103958       pNewTerm->eOperator = WO_GT;
   103959       pNewTerm->iParent = idxTerm;
   103960       pTerm = &pWC->a[idxTerm];
   103961       pTerm->nChild = 1;
   103962       pTerm->wtFlags |= TERM_COPIED;
   103963       pNewTerm->prereqAll = pTerm->prereqAll;
   103964     }
   103965   }
   103966 #endif /* SQLITE_ENABLE_STAT */
   103967 
   103968   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   103969   ** an index for tables to the left of the join.
   103970   */
   103971   pTerm->prereqRight |= extraRight;
   103972 }
   103973 
   103974 /*
   103975 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
   103976 ** a reference to any table other than the iBase table.
   103977 */
   103978 static int referencesOtherTables(
   103979   ExprList *pList,          /* Search expressions in ths list */
   103980   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
   103981   int iFirst,               /* Be searching with the iFirst-th expression */
   103982   int iBase                 /* Ignore references to this table */
   103983 ){
   103984   Bitmask allowed = ~getMask(pMaskSet, iBase);
   103985   while( iFirst<pList->nExpr ){
   103986     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
   103987       return 1;
   103988     }
   103989   }
   103990   return 0;
   103991 }
   103992 
   103993 /*
   103994 ** This function searches the expression list passed as the second argument
   103995 ** for an expression of type TK_COLUMN that refers to the same column and
   103996 ** uses the same collation sequence as the iCol'th column of index pIdx.
   103997 ** Argument iBase is the cursor number used for the table that pIdx refers
   103998 ** to.
   103999 **
   104000 ** If such an expression is found, its index in pList->a[] is returned. If
   104001 ** no expression is found, -1 is returned.
   104002 */
   104003 static int findIndexCol(
   104004   Parse *pParse,                  /* Parse context */
   104005   ExprList *pList,                /* Expression list to search */
   104006   int iBase,                      /* Cursor for table associated with pIdx */
   104007   Index *pIdx,                    /* Index to match column of */
   104008   int iCol                        /* Column of index to match */
   104009 ){
   104010   int i;
   104011   const char *zColl = pIdx->azColl[iCol];
   104012 
   104013   for(i=0; i<pList->nExpr; i++){
   104014     Expr *p = pList->a[i].pExpr;
   104015     if( p->op==TK_COLUMN
   104016      && p->iColumn==pIdx->aiColumn[iCol]
   104017      && p->iTable==iBase
   104018     ){
   104019       CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
   104020       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
   104021         return i;
   104022       }
   104023     }
   104024   }
   104025 
   104026   return -1;
   104027 }
   104028 
   104029 /*
   104030 ** This routine determines if pIdx can be used to assist in processing a
   104031 ** DISTINCT qualifier. In other words, it tests whether or not using this
   104032 ** index for the outer loop guarantees that rows with equal values for
   104033 ** all expressions in the pDistinct list are delivered grouped together.
   104034 **
   104035 ** For example, the query
   104036 **
   104037 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
   104038 **
   104039 ** can benefit from any index on columns "b" and "c".
   104040 */
   104041 static int isDistinctIndex(
   104042   Parse *pParse,                  /* Parsing context */
   104043   WhereClause *pWC,               /* The WHERE clause */
   104044   Index *pIdx,                    /* The index being considered */
   104045   int base,                       /* Cursor number for the table pIdx is on */
   104046   ExprList *pDistinct,            /* The DISTINCT expressions */
   104047   int nEqCol                      /* Number of index columns with == */
   104048 ){
   104049   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
   104050   int i;                          /* Iterator variable */
   104051 
   104052   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
   104053   testcase( pDistinct->nExpr==BMS-1 );
   104054 
   104055   /* Loop through all the expressions in the distinct list. If any of them
   104056   ** are not simple column references, return early. Otherwise, test if the
   104057   ** WHERE clause contains a "col=X" clause. If it does, the expression
   104058   ** can be ignored. If it does not, and the column does not belong to the
   104059   ** same table as index pIdx, return early. Finally, if there is no
   104060   ** matching "col=X" expression and the column is on the same table as pIdx,
   104061   ** set the corresponding bit in variable mask.
   104062   */
   104063   for(i=0; i<pDistinct->nExpr; i++){
   104064     WhereTerm *pTerm;
   104065     Expr *p = pDistinct->a[i].pExpr;
   104066     if( p->op!=TK_COLUMN ) return 0;
   104067     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
   104068     if( pTerm ){
   104069       Expr *pX = pTerm->pExpr;
   104070       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   104071       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
   104072       if( p1==p2 ) continue;
   104073     }
   104074     if( p->iTable!=base ) return 0;
   104075     mask |= (((Bitmask)1) << i);
   104076   }
   104077 
   104078   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
   104079     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
   104080     if( iExpr<0 ) break;
   104081     mask &= ~(((Bitmask)1) << iExpr);
   104082   }
   104083 
   104084   return (mask==0);
   104085 }
   104086 
   104087 
   104088 /*
   104089 ** Return true if the DISTINCT expression-list passed as the third argument
   104090 ** is redundant. A DISTINCT list is redundant if the database contains a
   104091 ** UNIQUE index that guarantees that the result of the query will be distinct
   104092 ** anyway.
   104093 */
   104094 static int isDistinctRedundant(
   104095   Parse *pParse,
   104096   SrcList *pTabList,
   104097   WhereClause *pWC,
   104098   ExprList *pDistinct
   104099 ){
   104100   Table *pTab;
   104101   Index *pIdx;
   104102   int i;
   104103   int iBase;
   104104 
   104105   /* If there is more than one table or sub-select in the FROM clause of
   104106   ** this query, then it will not be possible to show that the DISTINCT
   104107   ** clause is redundant. */
   104108   if( pTabList->nSrc!=1 ) return 0;
   104109   iBase = pTabList->a[0].iCursor;
   104110   pTab = pTabList->a[0].pTab;
   104111 
   104112   /* If any of the expressions is an IPK column on table iBase, then return
   104113   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   104114   ** current SELECT is a correlated sub-query.
   104115   */
   104116   for(i=0; i<pDistinct->nExpr; i++){
   104117     Expr *p = pDistinct->a[i].pExpr;
   104118     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   104119   }
   104120 
   104121   /* Loop through all indices on the table, checking each to see if it makes
   104122   ** the DISTINCT qualifier redundant. It does so if:
   104123   **
   104124   **   1. The index is itself UNIQUE, and
   104125   **
   104126   **   2. All of the columns in the index are either part of the pDistinct
   104127   **      list, or else the WHERE clause contains a term of the form "col=X",
   104128   **      where X is a constant value. The collation sequences of the
   104129   **      comparison and select-list expressions must match those of the index.
   104130   */
   104131   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   104132     if( pIdx->onError==OE_None ) continue;
   104133     for(i=0; i<pIdx->nColumn; i++){
   104134       int iCol = pIdx->aiColumn[i];
   104135       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
   104136        && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
   104137       ){
   104138         break;
   104139       }
   104140     }
   104141     if( i==pIdx->nColumn ){
   104142       /* This index implies that the DISTINCT qualifier is redundant. */
   104143       return 1;
   104144     }
   104145   }
   104146 
   104147   return 0;
   104148 }
   104149 
   104150 /*
   104151 ** This routine decides if pIdx can be used to satisfy the ORDER BY
   104152 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
   104153 ** ORDER BY clause, this routine returns 0.
   104154 **
   104155 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
   104156 ** left-most table in the FROM clause of that same SELECT statement and
   104157 ** the table has a cursor number of "base".  pIdx is an index on pTab.
   104158 **
   104159 ** nEqCol is the number of columns of pIdx that are used as equality
   104160 ** constraints.  Any of these columns may be missing from the ORDER BY
   104161 ** clause and the match can still be a success.
   104162 **
   104163 ** All terms of the ORDER BY that match against the index must be either
   104164 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
   104165 ** index do not need to satisfy this constraint.)  The *pbRev value is
   104166 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
   104167 ** the ORDER BY clause is all ASC.
   104168 */
   104169 static int isSortingIndex(
   104170   Parse *pParse,          /* Parsing context */
   104171   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
   104172   Index *pIdx,            /* The index we are testing */
   104173   int base,               /* Cursor number for the table to be sorted */
   104174   ExprList *pOrderBy,     /* The ORDER BY clause */
   104175   int nEqCol,             /* Number of index columns with == constraints */
   104176   int wsFlags,            /* Index usages flags */
   104177   int *pbRev              /* Set to 1 if ORDER BY is DESC */
   104178 ){
   104179   int i, j;                       /* Loop counters */
   104180   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
   104181   int nTerm;                      /* Number of ORDER BY terms */
   104182   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
   104183   sqlite3 *db = pParse->db;
   104184 
   104185   if( !pOrderBy ) return 0;
   104186   if( wsFlags & WHERE_COLUMN_IN ) return 0;
   104187   if( pIdx->bUnordered ) return 0;
   104188 
   104189   nTerm = pOrderBy->nExpr;
   104190   assert( nTerm>0 );
   104191 
   104192   /* Argument pIdx must either point to a 'real' named index structure,
   104193   ** or an index structure allocated on the stack by bestBtreeIndex() to
   104194   ** represent the rowid index that is part of every table.  */
   104195   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
   104196 
   104197   /* Match terms of the ORDER BY clause against columns of
   104198   ** the index.
   104199   **
   104200   ** Note that indices have pIdx->nColumn regular columns plus
   104201   ** one additional column containing the rowid.  The rowid column
   104202   ** of the index is also allowed to match against the ORDER BY
   104203   ** clause.
   104204   */
   104205   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
   104206     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
   104207     CollSeq *pColl;    /* The collating sequence of pExpr */
   104208     int termSortOrder; /* Sort order for this term */
   104209     int iColumn;       /* The i-th column of the index.  -1 for rowid */
   104210     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
   104211     const char *zColl; /* Name of the collating sequence for i-th index term */
   104212 
   104213     pExpr = pTerm->pExpr;
   104214     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
   104215       /* Can not use an index sort on anything that is not a column in the
   104216       ** left-most table of the FROM clause */
   104217       break;
   104218     }
   104219     pColl = sqlite3ExprCollSeq(pParse, pExpr);
   104220     if( !pColl ){
   104221       pColl = db->pDfltColl;
   104222     }
   104223     if( pIdx->zName && i<pIdx->nColumn ){
   104224       iColumn = pIdx->aiColumn[i];
   104225       if( iColumn==pIdx->pTable->iPKey ){
   104226         iColumn = -1;
   104227       }
   104228       iSortOrder = pIdx->aSortOrder[i];
   104229       zColl = pIdx->azColl[i];
   104230     }else{
   104231       iColumn = -1;
   104232       iSortOrder = 0;
   104233       zColl = pColl->zName;
   104234     }
   104235     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
   104236       /* Term j of the ORDER BY clause does not match column i of the index */
   104237       if( i<nEqCol ){
   104238         /* If an index column that is constrained by == fails to match an
   104239         ** ORDER BY term, that is OK.  Just ignore that column of the index
   104240         */
   104241         continue;
   104242       }else if( i==pIdx->nColumn ){
   104243         /* Index column i is the rowid.  All other terms match. */
   104244         break;
   104245       }else{
   104246         /* If an index column fails to match and is not constrained by ==
   104247         ** then the index cannot satisfy the ORDER BY constraint.
   104248         */
   104249         return 0;
   104250       }
   104251     }
   104252     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
   104253     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
   104254     assert( iSortOrder==0 || iSortOrder==1 );
   104255     termSortOrder = iSortOrder ^ pTerm->sortOrder;
   104256     if( i>nEqCol ){
   104257       if( termSortOrder!=sortOrder ){
   104258         /* Indices can only be used if all ORDER BY terms past the
   104259         ** equality constraints are all either DESC or ASC. */
   104260         return 0;
   104261       }
   104262     }else{
   104263       sortOrder = termSortOrder;
   104264     }
   104265     j++;
   104266     pTerm++;
   104267     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   104268       /* If the indexed column is the primary key and everything matches
   104269       ** so far and none of the ORDER BY terms to the right reference other
   104270       ** tables in the join, then we are assured that the index can be used
   104271       ** to sort because the primary key is unique and so none of the other
   104272       ** columns will make any difference
   104273       */
   104274       j = nTerm;
   104275     }
   104276   }
   104277 
   104278   *pbRev = sortOrder!=0;
   104279   if( j>=nTerm ){
   104280     /* All terms of the ORDER BY clause are covered by this index so
   104281     ** this index can be used for sorting. */
   104282     return 1;
   104283   }
   104284   if( pIdx->onError!=OE_None && i==pIdx->nColumn
   104285       && (wsFlags & WHERE_COLUMN_NULL)==0
   104286       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   104287     /* All terms of this index match some prefix of the ORDER BY clause
   104288     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
   104289     ** clause reference other tables in a join.  If this is all true then
   104290     ** the order by clause is superfluous.  Not that if the matching
   104291     ** condition is IS NULL then the result is not necessarily unique
   104292     ** even on a UNIQUE index, so disallow those cases. */
   104293     return 1;
   104294   }
   104295   return 0;
   104296 }
   104297 
   104298 /*
   104299 ** Prepare a crude estimate of the logarithm of the input value.
   104300 ** The results need not be exact.  This is only used for estimating
   104301 ** the total cost of performing operations with O(logN) or O(NlogN)
   104302 ** complexity.  Because N is just a guess, it is no great tragedy if
   104303 ** logN is a little off.
   104304 */
   104305 static double estLog(double N){
   104306   double logN = 1;
   104307   double x = 10;
   104308   while( N>x ){
   104309     logN += 1;
   104310     x *= 10;
   104311   }
   104312   return logN;
   104313 }
   104314 
   104315 /*
   104316 ** Two routines for printing the content of an sqlite3_index_info
   104317 ** structure.  Used for testing and debugging only.  If neither
   104318 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   104319 ** are no-ops.
   104320 */
   104321 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
   104322 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   104323   int i;
   104324   if( !sqlite3WhereTrace ) return;
   104325   for(i=0; i<p->nConstraint; i++){
   104326     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   104327        i,
   104328        p->aConstraint[i].iColumn,
   104329        p->aConstraint[i].iTermOffset,
   104330        p->aConstraint[i].op,
   104331        p->aConstraint[i].usable);
   104332   }
   104333   for(i=0; i<p->nOrderBy; i++){
   104334     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   104335        i,
   104336        p->aOrderBy[i].iColumn,
   104337        p->aOrderBy[i].desc);
   104338   }
   104339 }
   104340 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   104341   int i;
   104342   if( !sqlite3WhereTrace ) return;
   104343   for(i=0; i<p->nConstraint; i++){
   104344     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   104345        i,
   104346        p->aConstraintUsage[i].argvIndex,
   104347        p->aConstraintUsage[i].omit);
   104348   }
   104349   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   104350   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   104351   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   104352   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   104353 }
   104354 #else
   104355 #define TRACE_IDX_INPUTS(A)
   104356 #define TRACE_IDX_OUTPUTS(A)
   104357 #endif
   104358 
   104359 /*
   104360 ** Required because bestIndex() is called by bestOrClauseIndex()
   104361 */
   104362 static void bestIndex(
   104363     Parse*, WhereClause*, struct SrcList_item*,
   104364     Bitmask, Bitmask, ExprList*, WhereCost*);
   104365 
   104366 /*
   104367 ** This routine attempts to find an scanning strategy that can be used
   104368 ** to optimize an 'OR' expression that is part of a WHERE clause.
   104369 **
   104370 ** The table associated with FROM clause term pSrc may be either a
   104371 ** regular B-Tree table or a virtual table.
   104372 */
   104373 static void bestOrClauseIndex(
   104374   Parse *pParse,              /* The parsing context */
   104375   WhereClause *pWC,           /* The WHERE clause */
   104376   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   104377   Bitmask notReady,           /* Mask of cursors not available for indexing */
   104378   Bitmask notValid,           /* Cursors not available for any purpose */
   104379   ExprList *pOrderBy,         /* The ORDER BY clause */
   104380   WhereCost *pCost            /* Lowest cost query plan */
   104381 ){
   104382 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   104383   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   104384   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
   104385   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
   104386   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
   104387 
   104388   /* The OR-clause optimization is disallowed if the INDEXED BY or
   104389   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
   104390   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
   104391     return;
   104392   }
   104393   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
   104394     return;
   104395   }
   104396 
   104397   /* Search the WHERE clause terms for a usable WO_OR term. */
   104398   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104399     if( pTerm->eOperator==WO_OR
   104400      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
   104401      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
   104402     ){
   104403       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   104404       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   104405       WhereTerm *pOrTerm;
   104406       int flags = WHERE_MULTI_OR;
   104407       double rTotal = 0;
   104408       double nRow = 0;
   104409       Bitmask used = 0;
   104410 
   104411       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   104412         WhereCost sTermCost;
   104413         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
   104414           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
   104415         ));
   104416         if( pOrTerm->eOperator==WO_AND ){
   104417           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
   104418           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
   104419         }else if( pOrTerm->leftCursor==iCur ){
   104420           WhereClause tempWC;
   104421           tempWC.pParse = pWC->pParse;
   104422           tempWC.pMaskSet = pWC->pMaskSet;
   104423           tempWC.pOuter = pWC;
   104424           tempWC.op = TK_AND;
   104425           tempWC.a = pOrTerm;
   104426           tempWC.wctrlFlags = 0;
   104427           tempWC.nTerm = 1;
   104428           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
   104429         }else{
   104430           continue;
   104431         }
   104432         rTotal += sTermCost.rCost;
   104433         nRow += sTermCost.plan.nRow;
   104434         used |= sTermCost.used;
   104435         if( rTotal>=pCost->rCost ) break;
   104436       }
   104437 
   104438       /* If there is an ORDER BY clause, increase the scan cost to account
   104439       ** for the cost of the sort. */
   104440       if( pOrderBy!=0 ){
   104441         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
   104442                     rTotal, rTotal+nRow*estLog(nRow)));
   104443         rTotal += nRow*estLog(nRow);
   104444       }
   104445 
   104446       /* If the cost of scanning using this OR term for optimization is
   104447       ** less than the current cost stored in pCost, replace the contents
   104448       ** of pCost. */
   104449       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
   104450       if( rTotal<pCost->rCost ){
   104451         pCost->rCost = rTotal;
   104452         pCost->used = used;
   104453         pCost->plan.nRow = nRow;
   104454         pCost->plan.wsFlags = flags;
   104455         pCost->plan.u.pTerm = pTerm;
   104456       }
   104457     }
   104458   }
   104459 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   104460 }
   104461 
   104462 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104463 /*
   104464 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   104465 ** could be used with an index to access pSrc, assuming an appropriate
   104466 ** index existed.
   104467 */
   104468 static int termCanDriveIndex(
   104469   WhereTerm *pTerm,              /* WHERE clause term to check */
   104470   struct SrcList_item *pSrc,     /* Table we are trying to access */
   104471   Bitmask notReady               /* Tables in outer loops of the join */
   104472 ){
   104473   char aff;
   104474   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   104475   if( pTerm->eOperator!=WO_EQ ) return 0;
   104476   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   104477   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   104478   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   104479   return 1;
   104480 }
   104481 #endif
   104482 
   104483 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104484 /*
   104485 ** If the query plan for pSrc specified in pCost is a full table scan
   104486 ** and indexing is allows (if there is no NOT INDEXED clause) and it
   104487 ** possible to construct a transient index that would perform better
   104488 ** than a full table scan even when the cost of constructing the index
   104489 ** is taken into account, then alter the query plan to use the
   104490 ** transient index.
   104491 */
   104492 static void bestAutomaticIndex(
   104493   Parse *pParse,              /* The parsing context */
   104494   WhereClause *pWC,           /* The WHERE clause */
   104495   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   104496   Bitmask notReady,           /* Mask of cursors that are not available */
   104497   WhereCost *pCost            /* Lowest cost query plan */
   104498 ){
   104499   double nTableRow;           /* Rows in the input table */
   104500   double logN;                /* log(nTableRow) */
   104501   double costTempIdx;         /* per-query cost of the transient index */
   104502   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   104503   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   104504   Table *pTable;              /* Table tht might be indexed */
   104505 
   104506   if( pParse->nQueryLoop<=(double)1 ){
   104507     /* There is no point in building an automatic index for a single scan */
   104508     return;
   104509   }
   104510   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
   104511     /* Automatic indices are disabled at run-time */
   104512     return;
   104513   }
   104514   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
   104515     /* We already have some kind of index in use for this query. */
   104516     return;
   104517   }
   104518   if( pSrc->notIndexed ){
   104519     /* The NOT INDEXED clause appears in the SQL. */
   104520     return;
   104521   }
   104522   if( pSrc->isCorrelated ){
   104523     /* The source is a correlated sub-query. No point in indexing it. */
   104524     return;
   104525   }
   104526 
   104527   assert( pParse->nQueryLoop >= (double)1 );
   104528   pTable = pSrc->pTab;
   104529   nTableRow = pTable->nRowEst;
   104530   logN = estLog(nTableRow);
   104531   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
   104532   if( costTempIdx>=pCost->rCost ){
   104533     /* The cost of creating the transient table would be greater than
   104534     ** doing the full table scan */
   104535     return;
   104536   }
   104537 
   104538   /* Search for any equality comparison term */
   104539   pWCEnd = &pWC->a[pWC->nTerm];
   104540   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104541     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104542       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
   104543                     pCost->rCost, costTempIdx));
   104544       pCost->rCost = costTempIdx;
   104545       pCost->plan.nRow = logN + 1;
   104546       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
   104547       pCost->used = pTerm->prereqRight;
   104548       break;
   104549     }
   104550   }
   104551 }
   104552 #else
   104553 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
   104554 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   104555 
   104556 
   104557 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104558 /*
   104559 ** Generate code to construct the Index object for an automatic index
   104560 ** and to set up the WhereLevel object pLevel so that the code generator
   104561 ** makes use of the automatic index.
   104562 */
   104563 static void constructAutomaticIndex(
   104564   Parse *pParse,              /* The parsing context */
   104565   WhereClause *pWC,           /* The WHERE clause */
   104566   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   104567   Bitmask notReady,           /* Mask of cursors that are not available */
   104568   WhereLevel *pLevel          /* Write new index here */
   104569 ){
   104570   int nColumn;                /* Number of columns in the constructed index */
   104571   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   104572   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   104573   int nByte;                  /* Byte of memory needed for pIdx */
   104574   Index *pIdx;                /* Object describing the transient index */
   104575   Vdbe *v;                    /* Prepared statement under construction */
   104576   int addrInit;               /* Address of the initialization bypass jump */
   104577   Table *pTable;              /* The table being indexed */
   104578   KeyInfo *pKeyinfo;          /* Key information for the index */
   104579   int addrTop;                /* Top of the index fill loop */
   104580   int regRecord;              /* Register holding an index record */
   104581   int n;                      /* Column counter */
   104582   int i;                      /* Loop counter */
   104583   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   104584   CollSeq *pColl;             /* Collating sequence to on a column */
   104585   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   104586   Bitmask extraCols;          /* Bitmap of additional columns */
   104587 
   104588   /* Generate code to skip over the creation and initialization of the
   104589   ** transient index on 2nd and subsequent iterations of the loop. */
   104590   v = pParse->pVdbe;
   104591   assert( v!=0 );
   104592   addrInit = sqlite3CodeOnce(pParse);
   104593 
   104594   /* Count the number of columns that will be added to the index
   104595   ** and used to match WHERE clause constraints */
   104596   nColumn = 0;
   104597   pTable = pSrc->pTab;
   104598   pWCEnd = &pWC->a[pWC->nTerm];
   104599   idxCols = 0;
   104600   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104601     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104602       int iCol = pTerm->u.leftColumn;
   104603       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   104604       testcase( iCol==BMS );
   104605       testcase( iCol==BMS-1 );
   104606       if( (idxCols & cMask)==0 ){
   104607         nColumn++;
   104608         idxCols |= cMask;
   104609       }
   104610     }
   104611   }
   104612   assert( nColumn>0 );
   104613   pLevel->plan.nEq = nColumn;
   104614 
   104615   /* Count the number of additional columns needed to create a
   104616   ** covering index.  A "covering index" is an index that contains all
   104617   ** columns that are needed by the query.  With a covering index, the
   104618   ** original table never needs to be accessed.  Automatic indices must
   104619   ** be a covering index because the index will not be updated if the
   104620   ** original table changes and the index and table cannot both be used
   104621   ** if they go out of sync.
   104622   */
   104623   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
   104624   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
   104625   testcase( pTable->nCol==BMS-1 );
   104626   testcase( pTable->nCol==BMS-2 );
   104627   for(i=0; i<mxBitCol; i++){
   104628     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
   104629   }
   104630   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   104631     nColumn += pTable->nCol - BMS + 1;
   104632   }
   104633   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
   104634 
   104635   /* Construct the Index object to describe this index */
   104636   nByte = sizeof(Index);
   104637   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
   104638   nByte += nColumn*sizeof(char*);   /* Index.azColl */
   104639   nByte += nColumn;                 /* Index.aSortOrder */
   104640   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
   104641   if( pIdx==0 ) return;
   104642   pLevel->plan.u.pIdx = pIdx;
   104643   pIdx->azColl = (char**)&pIdx[1];
   104644   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
   104645   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
   104646   pIdx->zName = "auto-index";
   104647   pIdx->nColumn = nColumn;
   104648   pIdx->pTable = pTable;
   104649   n = 0;
   104650   idxCols = 0;
   104651   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104652     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104653       int iCol = pTerm->u.leftColumn;
   104654       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   104655       if( (idxCols & cMask)==0 ){
   104656         Expr *pX = pTerm->pExpr;
   104657         idxCols |= cMask;
   104658         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   104659         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   104660         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
   104661         n++;
   104662       }
   104663     }
   104664   }
   104665   assert( (u32)n==pLevel->plan.nEq );
   104666 
   104667   /* Add additional columns needed to make the automatic index into
   104668   ** a covering index */
   104669   for(i=0; i<mxBitCol; i++){
   104670     if( extraCols & (((Bitmask)1)<<i) ){
   104671       pIdx->aiColumn[n] = i;
   104672       pIdx->azColl[n] = "BINARY";
   104673       n++;
   104674     }
   104675   }
   104676   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   104677     for(i=BMS-1; i<pTable->nCol; i++){
   104678       pIdx->aiColumn[n] = i;
   104679       pIdx->azColl[n] = "BINARY";
   104680       n++;
   104681     }
   104682   }
   104683   assert( n==nColumn );
   104684 
   104685   /* Create the automatic index */
   104686   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
   104687   assert( pLevel->iIdxCur>=0 );
   104688   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
   104689                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
   104690   VdbeComment((v, "for %s", pTable->zName));
   104691 
   104692   /* Fill the automatic index with content */
   104693   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
   104694   regRecord = sqlite3GetTempReg(pParse);
   104695   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
   104696   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   104697   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   104698   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
   104699   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   104700   sqlite3VdbeJumpHere(v, addrTop);
   104701   sqlite3ReleaseTempReg(pParse, regRecord);
   104702 
   104703   /* Jump here when skipping the initialization */
   104704   sqlite3VdbeJumpHere(v, addrInit);
   104705 }
   104706 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   104707 
   104708 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104709 /*
   104710 ** Allocate and populate an sqlite3_index_info structure. It is the
   104711 ** responsibility of the caller to eventually release the structure
   104712 ** by passing the pointer returned by this function to sqlite3_free().
   104713 */
   104714 static sqlite3_index_info *allocateIndexInfo(
   104715   Parse *pParse,
   104716   WhereClause *pWC,
   104717   struct SrcList_item *pSrc,
   104718   ExprList *pOrderBy
   104719 ){
   104720   int i, j;
   104721   int nTerm;
   104722   struct sqlite3_index_constraint *pIdxCons;
   104723   struct sqlite3_index_orderby *pIdxOrderBy;
   104724   struct sqlite3_index_constraint_usage *pUsage;
   104725   WhereTerm *pTerm;
   104726   int nOrderBy;
   104727   sqlite3_index_info *pIdxInfo;
   104728 
   104729   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
   104730 
   104731   /* Count the number of possible WHERE clause constraints referring
   104732   ** to this virtual table */
   104733   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   104734     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   104735     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   104736     testcase( pTerm->eOperator==WO_IN );
   104737     testcase( pTerm->eOperator==WO_ISNULL );
   104738     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   104739     if( pTerm->wtFlags & TERM_VNULL ) continue;
   104740     nTerm++;
   104741   }
   104742 
   104743   /* If the ORDER BY clause contains only columns in the current
   104744   ** virtual table then allocate space for the aOrderBy part of
   104745   ** the sqlite3_index_info structure.
   104746   */
   104747   nOrderBy = 0;
   104748   if( pOrderBy ){
   104749     for(i=0; i<pOrderBy->nExpr; i++){
   104750       Expr *pExpr = pOrderBy->a[i].pExpr;
   104751       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   104752     }
   104753     if( i==pOrderBy->nExpr ){
   104754       nOrderBy = pOrderBy->nExpr;
   104755     }
   104756   }
   104757 
   104758   /* Allocate the sqlite3_index_info structure
   104759   */
   104760   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   104761                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   104762                            + sizeof(*pIdxOrderBy)*nOrderBy );
   104763   if( pIdxInfo==0 ){
   104764     sqlite3ErrorMsg(pParse, "out of memory");
   104765     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   104766     return 0;
   104767   }
   104768 
   104769   /* Initialize the structure.  The sqlite3_index_info structure contains
   104770   ** many fields that are declared "const" to prevent xBestIndex from
   104771   ** changing them.  We have to do some funky casting in order to
   104772   ** initialize those fields.
   104773   */
   104774   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   104775   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   104776   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   104777   *(int*)&pIdxInfo->nConstraint = nTerm;
   104778   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   104779   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   104780   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   104781   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   104782                                                                    pUsage;
   104783 
   104784   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   104785     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   104786     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   104787     testcase( pTerm->eOperator==WO_IN );
   104788     testcase( pTerm->eOperator==WO_ISNULL );
   104789     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   104790     if( pTerm->wtFlags & TERM_VNULL ) continue;
   104791     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   104792     pIdxCons[j].iTermOffset = i;
   104793     pIdxCons[j].op = (u8)pTerm->eOperator;
   104794     /* The direct assignment in the previous line is possible only because
   104795     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   104796     ** following asserts verify this fact. */
   104797     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   104798     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   104799     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   104800     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   104801     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   104802     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   104803     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   104804     j++;
   104805   }
   104806   for(i=0; i<nOrderBy; i++){
   104807     Expr *pExpr = pOrderBy->a[i].pExpr;
   104808     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   104809     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   104810   }
   104811 
   104812   return pIdxInfo;
   104813 }
   104814 
   104815 /*
   104816 ** The table object reference passed as the second argument to this function
   104817 ** must represent a virtual table. This function invokes the xBestIndex()
   104818 ** method of the virtual table with the sqlite3_index_info pointer passed
   104819 ** as the argument.
   104820 **
   104821 ** If an error occurs, pParse is populated with an error message and a
   104822 ** non-zero value is returned. Otherwise, 0 is returned and the output
   104823 ** part of the sqlite3_index_info structure is left populated.
   104824 **
   104825 ** Whether or not an error is returned, it is the responsibility of the
   104826 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   104827 ** that this is required.
   104828 */
   104829 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   104830   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   104831   int i;
   104832   int rc;
   104833 
   104834   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
   104835   TRACE_IDX_INPUTS(p);
   104836   rc = pVtab->pModule->xBestIndex(pVtab, p);
   104837   TRACE_IDX_OUTPUTS(p);
   104838 
   104839   if( rc!=SQLITE_OK ){
   104840     if( rc==SQLITE_NOMEM ){
   104841       pParse->db->mallocFailed = 1;
   104842     }else if( !pVtab->zErrMsg ){
   104843       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   104844     }else{
   104845       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   104846     }
   104847   }
   104848   sqlite3_free(pVtab->zErrMsg);
   104849   pVtab->zErrMsg = 0;
   104850 
   104851   for(i=0; i<p->nConstraint; i++){
   104852     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   104853       sqlite3ErrorMsg(pParse,
   104854           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   104855     }
   104856   }
   104857 
   104858   return pParse->nErr;
   104859 }
   104860 
   104861 
   104862 /*
   104863 ** Compute the best index for a virtual table.
   104864 **
   104865 ** The best index is computed by the xBestIndex method of the virtual
   104866 ** table module.  This routine is really just a wrapper that sets up
   104867 ** the sqlite3_index_info structure that is used to communicate with
   104868 ** xBestIndex.
   104869 **
   104870 ** In a join, this routine might be called multiple times for the
   104871 ** same virtual table.  The sqlite3_index_info structure is created
   104872 ** and initialized on the first invocation and reused on all subsequent
   104873 ** invocations.  The sqlite3_index_info structure is also used when
   104874 ** code is generated to access the virtual table.  The whereInfoDelete()
   104875 ** routine takes care of freeing the sqlite3_index_info structure after
   104876 ** everybody has finished with it.
   104877 */
   104878 static void bestVirtualIndex(
   104879   Parse *pParse,                  /* The parsing context */
   104880   WhereClause *pWC,               /* The WHERE clause */
   104881   struct SrcList_item *pSrc,      /* The FROM clause term to search */
   104882   Bitmask notReady,               /* Mask of cursors not available for index */
   104883   Bitmask notValid,               /* Cursors not valid for any purpose */
   104884   ExprList *pOrderBy,             /* The order by clause */
   104885   WhereCost *pCost,               /* Lowest cost query plan */
   104886   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
   104887 ){
   104888   Table *pTab = pSrc->pTab;
   104889   sqlite3_index_info *pIdxInfo;
   104890   struct sqlite3_index_constraint *pIdxCons;
   104891   struct sqlite3_index_constraint_usage *pUsage;
   104892   WhereTerm *pTerm;
   104893   int i, j;
   104894   int nOrderBy;
   104895   double rCost;
   104896 
   104897   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
   104898   ** malloc in allocateIndexInfo() fails and this function returns leaving
   104899   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
   104900   */
   104901   memset(pCost, 0, sizeof(*pCost));
   104902   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
   104903 
   104904   /* If the sqlite3_index_info structure has not been previously
   104905   ** allocated and initialized, then allocate and initialize it now.
   104906   */
   104907   pIdxInfo = *ppIdxInfo;
   104908   if( pIdxInfo==0 ){
   104909     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
   104910   }
   104911   if( pIdxInfo==0 ){
   104912     return;
   104913   }
   104914 
   104915   /* At this point, the sqlite3_index_info structure that pIdxInfo points
   104916   ** to will have been initialized, either during the current invocation or
   104917   ** during some prior invocation.  Now we just have to customize the
   104918   ** details of pIdxInfo for the current invocation and pass it to
   104919   ** xBestIndex.
   104920   */
   104921 
   104922   /* The module name must be defined. Also, by this point there must
   104923   ** be a pointer to an sqlite3_vtab structure. Otherwise
   104924   ** sqlite3ViewGetColumnNames() would have picked up the error.
   104925   */
   104926   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
   104927   assert( sqlite3GetVTable(pParse->db, pTab) );
   104928 
   104929   /* Set the aConstraint[].usable fields and initialize all
   104930   ** output variables to zero.
   104931   **
   104932   ** aConstraint[].usable is true for constraints where the right-hand
   104933   ** side contains only references to tables to the left of the current
   104934   ** table.  In other words, if the constraint is of the form:
   104935   **
   104936   **           column = expr
   104937   **
   104938   ** and we are evaluating a join, then the constraint on column is
   104939   ** only valid if all tables referenced in expr occur to the left
   104940   ** of the table containing column.
   104941   **
   104942   ** The aConstraints[] array contains entries for all constraints
   104943   ** on the current table.  That way we only have to compute it once
   104944   ** even though we might try to pick the best index multiple times.
   104945   ** For each attempt at picking an index, the order of tables in the
   104946   ** join might be different so we have to recompute the usable flag
   104947   ** each time.
   104948   */
   104949   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   104950   pUsage = pIdxInfo->aConstraintUsage;
   104951   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   104952     j = pIdxCons->iTermOffset;
   104953     pTerm = &pWC->a[j];
   104954     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
   104955   }
   104956   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   104957   if( pIdxInfo->needToFreeIdxStr ){
   104958     sqlite3_free(pIdxInfo->idxStr);
   104959   }
   104960   pIdxInfo->idxStr = 0;
   104961   pIdxInfo->idxNum = 0;
   104962   pIdxInfo->needToFreeIdxStr = 0;
   104963   pIdxInfo->orderByConsumed = 0;
   104964   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
   104965   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
   104966   nOrderBy = pIdxInfo->nOrderBy;
   104967   if( !pOrderBy ){
   104968     pIdxInfo->nOrderBy = 0;
   104969   }
   104970 
   104971   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
   104972     return;
   104973   }
   104974 
   104975   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   104976   for(i=0; i<pIdxInfo->nConstraint; i++){
   104977     if( pUsage[i].argvIndex>0 ){
   104978       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
   104979     }
   104980   }
   104981 
   104982   /* If there is an ORDER BY clause, and the selected virtual table index
   104983   ** does not satisfy it, increase the cost of the scan accordingly. This
   104984   ** matches the processing for non-virtual tables in bestBtreeIndex().
   104985   */
   104986   rCost = pIdxInfo->estimatedCost;
   104987   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
   104988     rCost += estLog(rCost)*rCost;
   104989   }
   104990 
   104991   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
   104992   ** inital value of lowestCost in this loop. If it is, then the
   104993   ** (cost<lowestCost) test below will never be true.
   104994   **
   104995   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
   104996   ** is defined.
   104997   */
   104998   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
   104999     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
   105000   }else{
   105001     pCost->rCost = rCost;
   105002   }
   105003   pCost->plan.u.pVtabIdx = pIdxInfo;
   105004   if( pIdxInfo->orderByConsumed ){
   105005     pCost->plan.wsFlags |= WHERE_ORDERBY;
   105006   }
   105007   pCost->plan.nEq = 0;
   105008   pIdxInfo->nOrderBy = nOrderBy;
   105009 
   105010   /* Try to find a more efficient access pattern by using multiple indexes
   105011   ** to optimize an OR expression within the WHERE clause.
   105012   */
   105013   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   105014 }
   105015 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   105016 
   105017 #ifdef SQLITE_ENABLE_STAT3
   105018 /*
   105019 ** Estimate the location of a particular key among all keys in an
   105020 ** index.  Store the results in aStat as follows:
   105021 **
   105022 **    aStat[0]      Est. number of rows less than pVal
   105023 **    aStat[1]      Est. number of rows equal to pVal
   105024 **
   105025 ** Return SQLITE_OK on success.
   105026 */
   105027 static int whereKeyStats(
   105028   Parse *pParse,              /* Database connection */
   105029   Index *pIdx,                /* Index to consider domain of */
   105030   sqlite3_value *pVal,        /* Value to consider */
   105031   int roundUp,                /* Round up if true.  Round down if false */
   105032   tRowcnt *aStat              /* OUT: stats written here */
   105033 ){
   105034   tRowcnt n;
   105035   IndexSample *aSample;
   105036   int i, eType;
   105037   int isEq = 0;
   105038   i64 v;
   105039   double r, rS;
   105040 
   105041   assert( roundUp==0 || roundUp==1 );
   105042   assert( pIdx->nSample>0 );
   105043   if( pVal==0 ) return SQLITE_ERROR;
   105044   n = pIdx->aiRowEst[0];
   105045   aSample = pIdx->aSample;
   105046   eType = sqlite3_value_type(pVal);
   105047 
   105048   if( eType==SQLITE_INTEGER ){
   105049     v = sqlite3_value_int64(pVal);
   105050     r = (i64)v;
   105051     for(i=0; i<pIdx->nSample; i++){
   105052       if( aSample[i].eType==SQLITE_NULL ) continue;
   105053       if( aSample[i].eType>=SQLITE_TEXT ) break;
   105054       if( aSample[i].eType==SQLITE_INTEGER ){
   105055         if( aSample[i].u.i>=v ){
   105056           isEq = aSample[i].u.i==v;
   105057           break;
   105058         }
   105059       }else{
   105060         assert( aSample[i].eType==SQLITE_FLOAT );
   105061         if( aSample[i].u.r>=r ){
   105062           isEq = aSample[i].u.r==r;
   105063           break;
   105064         }
   105065       }
   105066     }
   105067   }else if( eType==SQLITE_FLOAT ){
   105068     r = sqlite3_value_double(pVal);
   105069     for(i=0; i<pIdx->nSample; i++){
   105070       if( aSample[i].eType==SQLITE_NULL ) continue;
   105071       if( aSample[i].eType>=SQLITE_TEXT ) break;
   105072       if( aSample[i].eType==SQLITE_FLOAT ){
   105073         rS = aSample[i].u.r;
   105074       }else{
   105075         rS = aSample[i].u.i;
   105076       }
   105077       if( rS>=r ){
   105078         isEq = rS==r;
   105079         break;
   105080       }
   105081     }
   105082   }else if( eType==SQLITE_NULL ){
   105083     i = 0;
   105084     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
   105085   }else{
   105086     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   105087     for(i=0; i<pIdx->nSample; i++){
   105088       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
   105089         break;
   105090       }
   105091     }
   105092     if( i<pIdx->nSample ){
   105093       sqlite3 *db = pParse->db;
   105094       CollSeq *pColl;
   105095       const u8 *z;
   105096       if( eType==SQLITE_BLOB ){
   105097         z = (const u8 *)sqlite3_value_blob(pVal);
   105098         pColl = db->pDfltColl;
   105099         assert( pColl->enc==SQLITE_UTF8 );
   105100       }else{
   105101         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
   105102         if( pColl==0 ){
   105103           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
   105104                           *pIdx->azColl);
   105105           return SQLITE_ERROR;
   105106         }
   105107         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
   105108         if( !z ){
   105109           return SQLITE_NOMEM;
   105110         }
   105111         assert( z && pColl && pColl->xCmp );
   105112       }
   105113       n = sqlite3ValueBytes(pVal, pColl->enc);
   105114 
   105115       for(; i<pIdx->nSample; i++){
   105116         int c;
   105117         int eSampletype = aSample[i].eType;
   105118         if( eSampletype<eType ) continue;
   105119         if( eSampletype!=eType ) break;
   105120 #ifndef SQLITE_OMIT_UTF16
   105121         if( pColl->enc!=SQLITE_UTF8 ){
   105122           int nSample;
   105123           char *zSample = sqlite3Utf8to16(
   105124               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
   105125           );
   105126           if( !zSample ){
   105127             assert( db->mallocFailed );
   105128             return SQLITE_NOMEM;
   105129           }
   105130           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
   105131           sqlite3DbFree(db, zSample);
   105132         }else
   105133 #endif
   105134         {
   105135           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
   105136         }
   105137         if( c>=0 ){
   105138           if( c==0 ) isEq = 1;
   105139           break;
   105140         }
   105141       }
   105142     }
   105143   }
   105144 
   105145   /* At this point, aSample[i] is the first sample that is greater than
   105146   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
   105147   ** than pVal.  If aSample[i]==pVal, then isEq==1.
   105148   */
   105149   if( isEq ){
   105150     assert( i<pIdx->nSample );
   105151     aStat[0] = aSample[i].nLt;
   105152     aStat[1] = aSample[i].nEq;
   105153   }else{
   105154     tRowcnt iLower, iUpper, iGap;
   105155     if( i==0 ){
   105156       iLower = 0;
   105157       iUpper = aSample[0].nLt;
   105158     }else{
   105159       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
   105160       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
   105161     }
   105162     aStat[1] = pIdx->avgEq;
   105163     if( iLower>=iUpper ){
   105164       iGap = 0;
   105165     }else{
   105166       iGap = iUpper - iLower;
   105167     }
   105168     if( roundUp ){
   105169       iGap = (iGap*2)/3;
   105170     }else{
   105171       iGap = iGap/3;
   105172     }
   105173     aStat[0] = iLower + iGap;
   105174   }
   105175   return SQLITE_OK;
   105176 }
   105177 #endif /* SQLITE_ENABLE_STAT3 */
   105178 
   105179 /*
   105180 ** If expression pExpr represents a literal value, set *pp to point to
   105181 ** an sqlite3_value structure containing the same value, with affinity
   105182 ** aff applied to it, before returning. It is the responsibility of the
   105183 ** caller to eventually release this structure by passing it to
   105184 ** sqlite3ValueFree().
   105185 **
   105186 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
   105187 ** is an SQL variable that currently has a non-NULL value bound to it,
   105188 ** create an sqlite3_value structure containing this value, again with
   105189 ** affinity aff applied to it, instead.
   105190 **
   105191 ** If neither of the above apply, set *pp to NULL.
   105192 **
   105193 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
   105194 */
   105195 #ifdef SQLITE_ENABLE_STAT3
   105196 static int valueFromExpr(
   105197   Parse *pParse,
   105198   Expr *pExpr,
   105199   u8 aff,
   105200   sqlite3_value **pp
   105201 ){
   105202   if( pExpr->op==TK_VARIABLE
   105203    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
   105204   ){
   105205     int iVar = pExpr->iColumn;
   105206     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
   105207     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
   105208     return SQLITE_OK;
   105209   }
   105210   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
   105211 }
   105212 #endif
   105213 
   105214 /*
   105215 ** This function is used to estimate the number of rows that will be visited
   105216 ** by scanning an index for a range of values. The range may have an upper
   105217 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   105218 ** and lower bounds are represented by pLower and pUpper respectively. For
   105219 ** example, assuming that index p is on t1(a):
   105220 **
   105221 **   ... FROM t1 WHERE a > ? AND a < ? ...
   105222 **                    |_____|   |_____|
   105223 **                       |         |
   105224 **                     pLower    pUpper
   105225 **
   105226 ** If either of the upper or lower bound is not present, then NULL is passed in
   105227 ** place of the corresponding WhereTerm.
   105228 **
   105229 ** The nEq parameter is passed the index of the index column subject to the
   105230 ** range constraint. Or, equivalently, the number of equality constraints
   105231 ** optimized by the proposed index scan. For example, assuming index p is
   105232 ** on t1(a, b), and the SQL query is:
   105233 **
   105234 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   105235 **
   105236 ** then nEq should be passed the value 1 (as the range restricted column,
   105237 ** b, is the second left-most column of the index). Or, if the query is:
   105238 **
   105239 **   ... FROM t1 WHERE a > ? AND a < ? ...
   105240 **
   105241 ** then nEq should be passed 0.
   105242 **
   105243 ** The returned value is an integer divisor to reduce the estimated
   105244 ** search space.  A return value of 1 means that range constraints are
   105245 ** no help at all.  A return value of 2 means range constraints are
   105246 ** expected to reduce the search space by half.  And so forth...
   105247 **
   105248 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
   105249 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
   105250 ** results in a return of 4 and a range constraint (x>? AND x<?) results
   105251 ** in a return of 16.
   105252 */
   105253 static int whereRangeScanEst(
   105254   Parse *pParse,       /* Parsing & code generating context */
   105255   Index *p,            /* The index containing the range-compared column; "x" */
   105256   int nEq,             /* index into p->aCol[] of the range-compared column */
   105257   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   105258   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   105259   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
   105260 ){
   105261   int rc = SQLITE_OK;
   105262 
   105263 #ifdef SQLITE_ENABLE_STAT3
   105264 
   105265   if( nEq==0 && p->nSample ){
   105266     sqlite3_value *pRangeVal;
   105267     tRowcnt iLower = 0;
   105268     tRowcnt iUpper = p->aiRowEst[0];
   105269     tRowcnt a[2];
   105270     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   105271 
   105272     if( pLower ){
   105273       Expr *pExpr = pLower->pExpr->pRight;
   105274       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
   105275       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
   105276       if( rc==SQLITE_OK
   105277        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
   105278       ){
   105279         iLower = a[0];
   105280         if( pLower->eOperator==WO_GT ) iLower += a[1];
   105281       }
   105282       sqlite3ValueFree(pRangeVal);
   105283     }
   105284     if( rc==SQLITE_OK && pUpper ){
   105285       Expr *pExpr = pUpper->pExpr->pRight;
   105286       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
   105287       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
   105288       if( rc==SQLITE_OK
   105289        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
   105290       ){
   105291         iUpper = a[0];
   105292         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
   105293       }
   105294       sqlite3ValueFree(pRangeVal);
   105295     }
   105296     if( rc==SQLITE_OK ){
   105297       if( iUpper<=iLower ){
   105298         *pRangeDiv = (double)p->aiRowEst[0];
   105299       }else{
   105300         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
   105301       }
   105302       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
   105303                   (u32)iLower, (u32)iUpper, *pRangeDiv));
   105304       return SQLITE_OK;
   105305     }
   105306   }
   105307 #else
   105308   UNUSED_PARAMETER(pParse);
   105309   UNUSED_PARAMETER(p);
   105310   UNUSED_PARAMETER(nEq);
   105311 #endif
   105312   assert( pLower || pUpper );
   105313   *pRangeDiv = (double)1;
   105314   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
   105315   if( pUpper ) *pRangeDiv *= (double)4;
   105316   return rc;
   105317 }
   105318 
   105319 #ifdef SQLITE_ENABLE_STAT3
   105320 /*
   105321 ** Estimate the number of rows that will be returned based on
   105322 ** an equality constraint x=VALUE and where that VALUE occurs in
   105323 ** the histogram data.  This only works when x is the left-most
   105324 ** column of an index and sqlite_stat3 histogram data is available
   105325 ** for that index.  When pExpr==NULL that means the constraint is
   105326 ** "x IS NULL" instead of "x=VALUE".
   105327 **
   105328 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   105329 ** If unable to make an estimate, leave *pnRow unchanged and return
   105330 ** non-zero.
   105331 **
   105332 ** This routine can fail if it is unable to load a collating sequence
   105333 ** required for string comparison, or if unable to allocate memory
   105334 ** for a UTF conversion required for comparison.  The error is stored
   105335 ** in the pParse structure.
   105336 */
   105337 static int whereEqualScanEst(
   105338   Parse *pParse,       /* Parsing & code generating context */
   105339   Index *p,            /* The index whose left-most column is pTerm */
   105340   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
   105341   double *pnRow        /* Write the revised row estimate here */
   105342 ){
   105343   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
   105344   u8 aff;                   /* Column affinity */
   105345   int rc;                   /* Subfunction return code */
   105346   tRowcnt a[2];             /* Statistics */
   105347 
   105348   assert( p->aSample!=0 );
   105349   assert( p->nSample>0 );
   105350   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   105351   if( pExpr ){
   105352     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
   105353     if( rc ) goto whereEqualScanEst_cancel;
   105354   }else{
   105355     pRhs = sqlite3ValueNew(pParse->db);
   105356   }
   105357   if( pRhs==0 ) return SQLITE_NOTFOUND;
   105358   rc = whereKeyStats(pParse, p, pRhs, 0, a);
   105359   if( rc==SQLITE_OK ){
   105360     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
   105361     *pnRow = a[1];
   105362   }
   105363 whereEqualScanEst_cancel:
   105364   sqlite3ValueFree(pRhs);
   105365   return rc;
   105366 }
   105367 #endif /* defined(SQLITE_ENABLE_STAT3) */
   105368 
   105369 #ifdef SQLITE_ENABLE_STAT3
   105370 /*
   105371 ** Estimate the number of rows that will be returned based on
   105372 ** an IN constraint where the right-hand side of the IN operator
   105373 ** is a list of values.  Example:
   105374 **
   105375 **        WHERE x IN (1,2,3,4)
   105376 **
   105377 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   105378 ** If unable to make an estimate, leave *pnRow unchanged and return
   105379 ** non-zero.
   105380 **
   105381 ** This routine can fail if it is unable to load a collating sequence
   105382 ** required for string comparison, or if unable to allocate memory
   105383 ** for a UTF conversion required for comparison.  The error is stored
   105384 ** in the pParse structure.
   105385 */
   105386 static int whereInScanEst(
   105387   Parse *pParse,       /* Parsing & code generating context */
   105388   Index *p,            /* The index whose left-most column is pTerm */
   105389   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
   105390   double *pnRow        /* Write the revised row estimate here */
   105391 ){
   105392   int rc = SQLITE_OK;         /* Subfunction return code */
   105393   double nEst;                /* Number of rows for a single term */
   105394   double nRowEst = (double)0; /* New estimate of the number of rows */
   105395   int i;                      /* Loop counter */
   105396 
   105397   assert( p->aSample!=0 );
   105398   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
   105399     nEst = p->aiRowEst[0];
   105400     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
   105401     nRowEst += nEst;
   105402   }
   105403   if( rc==SQLITE_OK ){
   105404     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
   105405     *pnRow = nRowEst;
   105406     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
   105407   }
   105408   return rc;
   105409 }
   105410 #endif /* defined(SQLITE_ENABLE_STAT3) */
   105411 
   105412 
   105413 /*
   105414 ** Find the best query plan for accessing a particular table.  Write the
   105415 ** best query plan and its cost into the WhereCost object supplied as the
   105416 ** last parameter.
   105417 **
   105418 ** The lowest cost plan wins.  The cost is an estimate of the amount of
   105419 ** CPU and disk I/O needed to process the requested result.
   105420 ** Factors that influence cost include:
   105421 **
   105422 **    *  The estimated number of rows that will be retrieved.  (The
   105423 **       fewer the better.)
   105424 **
   105425 **    *  Whether or not sorting must occur.
   105426 **
   105427 **    *  Whether or not there must be separate lookups in the
   105428 **       index and in the main table.
   105429 **
   105430 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
   105431 ** the SQL statement, then this function only considers plans using the
   105432 ** named index. If no such plan is found, then the returned cost is
   105433 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
   105434 ** then the cost is calculated in the usual way.
   105435 **
   105436 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
   105437 ** in the SELECT statement, then no indexes are considered. However, the
   105438 ** selected plan may still take advantage of the built-in rowid primary key
   105439 ** index.
   105440 */
   105441 static void bestBtreeIndex(
   105442   Parse *pParse,              /* The parsing context */
   105443   WhereClause *pWC,           /* The WHERE clause */
   105444   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   105445   Bitmask notReady,           /* Mask of cursors not available for indexing */
   105446   Bitmask notValid,           /* Cursors not available for any purpose */
   105447   ExprList *pOrderBy,         /* The ORDER BY clause */
   105448   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
   105449   WhereCost *pCost            /* Lowest cost query plan */
   105450 ){
   105451   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   105452   Index *pProbe;              /* An index we are evaluating */
   105453   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
   105454   int eqTermMask;             /* Current mask of valid equality operators */
   105455   int idxEqTermMask;          /* Index mask of valid equality operators */
   105456   Index sPk;                  /* A fake index object for the primary key */
   105457   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
   105458   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   105459   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
   105460 
   105461   /* Initialize the cost to a worst-case value */
   105462   memset(pCost, 0, sizeof(*pCost));
   105463   pCost->rCost = SQLITE_BIG_DBL;
   105464 
   105465   /* If the pSrc table is the right table of a LEFT JOIN then we may not
   105466   ** use an index to satisfy IS NULL constraints on that table.  This is
   105467   ** because columns might end up being NULL if the table does not match -
   105468   ** a circumstance which the index cannot help us discover.  Ticket #2177.
   105469   */
   105470   if( pSrc->jointype & JT_LEFT ){
   105471     idxEqTermMask = WO_EQ|WO_IN;
   105472   }else{
   105473     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
   105474   }
   105475 
   105476   if( pSrc->pIndex ){
   105477     /* An INDEXED BY clause specifies a particular index to use */
   105478     pIdx = pProbe = pSrc->pIndex;
   105479     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   105480     eqTermMask = idxEqTermMask;
   105481   }else{
   105482     /* There is no INDEXED BY clause.  Create a fake Index object in local
   105483     ** variable sPk to represent the rowid primary key index.  Make this
   105484     ** fake index the first in a chain of Index objects with all of the real
   105485     ** indices to follow */
   105486     Index *pFirst;                  /* First of real indices on the table */
   105487     memset(&sPk, 0, sizeof(Index));
   105488     sPk.nColumn = 1;
   105489     sPk.aiColumn = &aiColumnPk;
   105490     sPk.aiRowEst = aiRowEstPk;
   105491     sPk.onError = OE_Replace;
   105492     sPk.pTable = pSrc->pTab;
   105493     aiRowEstPk[0] = pSrc->pTab->nRowEst;
   105494     aiRowEstPk[1] = 1;
   105495     pFirst = pSrc->pTab->pIndex;
   105496     if( pSrc->notIndexed==0 ){
   105497       /* The real indices of the table are only considered if the
   105498       ** NOT INDEXED qualifier is omitted from the FROM clause */
   105499       sPk.pNext = pFirst;
   105500     }
   105501     pProbe = &sPk;
   105502     wsFlagMask = ~(
   105503         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
   105504     );
   105505     eqTermMask = WO_EQ|WO_IN;
   105506     pIdx = 0;
   105507   }
   105508 
   105509   /* Loop over all indices looking for the best one to use
   105510   */
   105511   for(; pProbe; pIdx=pProbe=pProbe->pNext){
   105512     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
   105513     double cost;                /* Cost of using pProbe */
   105514     double nRow;                /* Estimated number of rows in result set */
   105515     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
   105516     int rev;                    /* True to scan in reverse order */
   105517     int wsFlags = 0;
   105518     Bitmask used = 0;
   105519 
   105520     /* The following variables are populated based on the properties of
   105521     ** index being evaluated. They are then used to determine the expected
   105522     ** cost and number of rows returned.
   105523     **
   105524     **  nEq:
   105525     **    Number of equality terms that can be implemented using the index.
   105526     **    In other words, the number of initial fields in the index that
   105527     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
   105528     **
   105529     **  nInMul:
   105530     **    The "in-multiplier". This is an estimate of how many seek operations
   105531     **    SQLite must perform on the index in question. For example, if the
   105532     **    WHERE clause is:
   105533     **
   105534     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
   105535     **
   105536     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
   105537     **    set to 9. Given the same schema and either of the following WHERE
   105538     **    clauses:
   105539     **
   105540     **      WHERE a =  1
   105541     **      WHERE a >= 2
   105542     **
   105543     **    nInMul is set to 1.
   105544     **
   105545     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
   105546     **    the sub-select is assumed to return 25 rows for the purposes of
   105547     **    determining nInMul.
   105548     **
   105549     **  bInEst:
   105550     **    Set to true if there was at least one "x IN (SELECT ...)" term used
   105551     **    in determining the value of nInMul.  Note that the RHS of the
   105552     **    IN operator must be a SELECT, not a value list, for this variable
   105553     **    to be true.
   105554     **
   105555     **  rangeDiv:
   105556     **    An estimate of a divisor by which to reduce the search space due
   105557     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
   105558     **    data, a single inequality reduces the search space to 1/4rd its
   105559     **    original size (rangeDiv==4).  Two inequalities reduce the search
   105560     **    space to 1/16th of its original size (rangeDiv==16).
   105561     **
   105562     **  bSort:
   105563     **    Boolean. True if there is an ORDER BY clause that will require an
   105564     **    external sort (i.e. scanning the index being evaluated will not
   105565     **    correctly order records).
   105566     **
   105567     **  bLookup:
   105568     **    Boolean. True if a table lookup is required for each index entry
   105569     **    visited.  In other words, true if this is not a covering index.
   105570     **    This is always false for the rowid primary key index of a table.
   105571     **    For other indexes, it is true unless all the columns of the table
   105572     **    used by the SELECT statement are present in the index (such an
   105573     **    index is sometimes described as a covering index).
   105574     **    For example, given the index on (a, b), the second of the following
   105575     **    two queries requires table b-tree lookups in order to find the value
   105576     **    of column c, but the first does not because columns a and b are
   105577     **    both available in the index.
   105578     **
   105579     **             SELECT a, b    FROM tbl WHERE a = 1;
   105580     **             SELECT a, b, c FROM tbl WHERE a = 1;
   105581     */
   105582     int nEq;                      /* Number of == or IN terms matching index */
   105583     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
   105584     int nInMul = 1;               /* Number of distinct equalities to lookup */
   105585     double rangeDiv = (double)1;  /* Estimated reduction in search space */
   105586     int nBound = 0;               /* Number of range constraints seen */
   105587     int bSort = !!pOrderBy;       /* True if external sort required */
   105588     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
   105589     int bLookup = 0;              /* True if not a covering index */
   105590     WhereTerm *pTerm;             /* A single term of the WHERE clause */
   105591 #ifdef SQLITE_ENABLE_STAT3
   105592     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
   105593 #endif
   105594 
   105595     /* Determine the values of nEq and nInMul */
   105596     for(nEq=0; nEq<pProbe->nColumn; nEq++){
   105597       int j = pProbe->aiColumn[nEq];
   105598       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
   105599       if( pTerm==0 ) break;
   105600       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
   105601       testcase( pTerm->pWC!=pWC );
   105602       if( pTerm->eOperator & WO_IN ){
   105603         Expr *pExpr = pTerm->pExpr;
   105604         wsFlags |= WHERE_COLUMN_IN;
   105605         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   105606           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
   105607           nInMul *= 25;
   105608           bInEst = 1;
   105609         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
   105610           /* "x IN (value, value, ...)" */
   105611           nInMul *= pExpr->x.pList->nExpr;
   105612         }
   105613       }else if( pTerm->eOperator & WO_ISNULL ){
   105614         wsFlags |= WHERE_COLUMN_NULL;
   105615       }
   105616 #ifdef SQLITE_ENABLE_STAT3
   105617       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
   105618 #endif
   105619       used |= pTerm->prereqRight;
   105620     }
   105621 
   105622     /* If the index being considered is UNIQUE, and there is an equality
   105623     ** constraint for all columns in the index, then this search will find
   105624     ** at most a single row. In this case set the WHERE_UNIQUE flag to
   105625     ** indicate this to the caller.
   105626     **
   105627     ** Otherwise, if the search may find more than one row, test to see if
   105628     ** there is a range constraint on indexed column (nEq+1) that can be
   105629     ** optimized using the index.
   105630     */
   105631     if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
   105632       testcase( wsFlags & WHERE_COLUMN_IN );
   105633       testcase( wsFlags & WHERE_COLUMN_NULL );
   105634       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
   105635         wsFlags |= WHERE_UNIQUE;
   105636       }
   105637     }else if( pProbe->bUnordered==0 ){
   105638       int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
   105639       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
   105640         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
   105641         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
   105642         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
   105643         if( pTop ){
   105644           nBound = 1;
   105645           wsFlags |= WHERE_TOP_LIMIT;
   105646           used |= pTop->prereqRight;
   105647           testcase( pTop->pWC!=pWC );
   105648         }
   105649         if( pBtm ){
   105650           nBound++;
   105651           wsFlags |= WHERE_BTM_LIMIT;
   105652           used |= pBtm->prereqRight;
   105653           testcase( pBtm->pWC!=pWC );
   105654         }
   105655         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
   105656       }
   105657     }
   105658 
   105659     /* If there is an ORDER BY clause and the index being considered will
   105660     ** naturally scan rows in the required order, set the appropriate flags
   105661     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
   105662     ** will scan rows in a different order, set the bSort variable.  */
   105663     if( isSortingIndex(
   105664           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
   105665     ){
   105666       bSort = 0;
   105667       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
   105668       wsFlags |= (rev ? WHERE_REVERSE : 0);
   105669     }
   105670 
   105671     /* If there is a DISTINCT qualifier and this index will scan rows in
   105672     ** order of the DISTINCT expressions, clear bDist and set the appropriate
   105673     ** flags in wsFlags. */
   105674     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
   105675      && (wsFlags & WHERE_COLUMN_IN)==0
   105676     ){
   105677       bDist = 0;
   105678       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
   105679     }
   105680 
   105681     /* If currently calculating the cost of using an index (not the IPK
   105682     ** index), determine if all required column data may be obtained without
   105683     ** using the main table (i.e. if the index is a covering
   105684     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
   105685     ** wsFlags. Otherwise, set the bLookup variable to true.  */
   105686     if( pIdx && wsFlags ){
   105687       Bitmask m = pSrc->colUsed;
   105688       int j;
   105689       for(j=0; j<pIdx->nColumn; j++){
   105690         int x = pIdx->aiColumn[j];
   105691         if( x<BMS-1 ){
   105692           m &= ~(((Bitmask)1)<<x);
   105693         }
   105694       }
   105695       if( m==0 ){
   105696         wsFlags |= WHERE_IDX_ONLY;
   105697       }else{
   105698         bLookup = 1;
   105699       }
   105700     }
   105701 
   105702     /*
   105703     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
   105704     ** constraint, do not let the estimate exceed half the rows in the table.
   105705     */
   105706     nRow = (double)(aiRowEst[nEq] * nInMul);
   105707     if( bInEst && nRow*2>aiRowEst[0] ){
   105708       nRow = aiRowEst[0]/2;
   105709       nInMul = (int)(nRow / aiRowEst[nEq]);
   105710     }
   105711 
   105712 #ifdef SQLITE_ENABLE_STAT3
   105713     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
   105714     ** and we do not think that values of x are unique and if histogram
   105715     ** data is available for column x, then it might be possible
   105716     ** to get a better estimate on the number of rows based on
   105717     ** VALUE and how common that value is according to the histogram.
   105718     */
   105719     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
   105720       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
   105721       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
   105722         testcase( pFirstTerm->eOperator==WO_EQ );
   105723         testcase( pFirstTerm->eOperator==WO_ISNULL );
   105724         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
   105725       }else if( bInEst==0 ){
   105726         assert( pFirstTerm->eOperator==WO_IN );
   105727         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
   105728       }
   105729     }
   105730 #endif /* SQLITE_ENABLE_STAT3 */
   105731 
   105732     /* Adjust the number of output rows and downward to reflect rows
   105733     ** that are excluded by range constraints.
   105734     */
   105735     nRow = nRow/rangeDiv;
   105736     if( nRow<1 ) nRow = 1;
   105737 
   105738     /* Experiments run on real SQLite databases show that the time needed
   105739     ** to do a binary search to locate a row in a table or index is roughly
   105740     ** log10(N) times the time to move from one row to the next row within
   105741     ** a table or index.  The actual times can vary, with the size of
   105742     ** records being an important factor.  Both moves and searches are
   105743     ** slower with larger records, presumably because fewer records fit
   105744     ** on one page and hence more pages have to be fetched.
   105745     **
   105746     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
   105747     ** not give us data on the relative sizes of table and index records.
   105748     ** So this computation assumes table records are about twice as big
   105749     ** as index records
   105750     */
   105751     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
   105752       /* The cost of a full table scan is a number of move operations equal
   105753       ** to the number of rows in the table.
   105754       **
   105755       ** We add an additional 4x penalty to full table scans.  This causes
   105756       ** the cost function to err on the side of choosing an index over
   105757       ** choosing a full scan.  This 4x full-scan penalty is an arguable
   105758       ** decision and one which we expect to revisit in the future.  But
   105759       ** it seems to be working well enough at the moment.
   105760       */
   105761       cost = aiRowEst[0]*4;
   105762     }else{
   105763       log10N = estLog(aiRowEst[0]);
   105764       cost = nRow;
   105765       if( pIdx ){
   105766         if( bLookup ){
   105767           /* For an index lookup followed by a table lookup:
   105768           **    nInMul index searches to find the start of each index range
   105769           **  + nRow steps through the index
   105770           **  + nRow table searches to lookup the table entry using the rowid
   105771           */
   105772           cost += (nInMul + nRow)*log10N;
   105773         }else{
   105774           /* For a covering index:
   105775           **     nInMul index searches to find the initial entry
   105776           **   + nRow steps through the index
   105777           */
   105778           cost += nInMul*log10N;
   105779         }
   105780       }else{
   105781         /* For a rowid primary key lookup:
   105782         **    nInMult table searches to find the initial entry for each range
   105783         **  + nRow steps through the table
   105784         */
   105785         cost += nInMul*log10N;
   105786       }
   105787     }
   105788 
   105789     /* Add in the estimated cost of sorting the result.  Actual experimental
   105790     ** measurements of sorting performance in SQLite show that sorting time
   105791     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
   105792     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
   105793     ** difference and select C of 3.0.
   105794     */
   105795     if( bSort ){
   105796       cost += nRow*estLog(nRow)*3;
   105797     }
   105798     if( bDist ){
   105799       cost += nRow*estLog(nRow)*3;
   105800     }
   105801 
   105802     /**** Cost of using this index has now been computed ****/
   105803 
   105804     /* If there are additional constraints on this table that cannot
   105805     ** be used with the current index, but which might lower the number
   105806     ** of output rows, adjust the nRow value accordingly.  This only
   105807     ** matters if the current index is the least costly, so do not bother
   105808     ** with this step if we already know this index will not be chosen.
   105809     ** Also, never reduce the output row count below 2 using this step.
   105810     **
   105811     ** It is critical that the notValid mask be used here instead of
   105812     ** the notReady mask.  When computing an "optimal" index, the notReady
   105813     ** mask will only have one bit set - the bit for the current table.
   105814     ** The notValid mask, on the other hand, always has all bits set for
   105815     ** tables that are not in outer loops.  If notReady is used here instead
   105816     ** of notValid, then a optimal index that depends on inner joins loops
   105817     ** might be selected even when there exists an optimal index that has
   105818     ** no such dependency.
   105819     */
   105820     if( nRow>2 && cost<=pCost->rCost ){
   105821       int k;                       /* Loop counter */
   105822       int nSkipEq = nEq;           /* Number of == constraints to skip */
   105823       int nSkipRange = nBound;     /* Number of < constraints to skip */
   105824       Bitmask thisTab;             /* Bitmap for pSrc */
   105825 
   105826       thisTab = getMask(pWC->pMaskSet, iCur);
   105827       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
   105828         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
   105829         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
   105830         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
   105831           if( nSkipEq ){
   105832             /* Ignore the first nEq equality matches since the index
   105833             ** has already accounted for these */
   105834             nSkipEq--;
   105835           }else{
   105836             /* Assume each additional equality match reduces the result
   105837             ** set size by a factor of 10 */
   105838             nRow /= 10;
   105839           }
   105840         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
   105841           if( nSkipRange ){
   105842             /* Ignore the first nSkipRange range constraints since the index
   105843             ** has already accounted for these */
   105844             nSkipRange--;
   105845           }else{
   105846             /* Assume each additional range constraint reduces the result
   105847             ** set size by a factor of 3.  Indexed range constraints reduce
   105848             ** the search space by a larger factor: 4.  We make indexed range
   105849             ** more selective intentionally because of the subjective
   105850             ** observation that indexed range constraints really are more
   105851             ** selective in practice, on average. */
   105852             nRow /= 3;
   105853           }
   105854         }else if( pTerm->eOperator!=WO_NOOP ){
   105855           /* Any other expression lowers the output row count by half */
   105856           nRow /= 2;
   105857         }
   105858       }
   105859       if( nRow<2 ) nRow = 2;
   105860     }
   105861 
   105862 
   105863     WHERETRACE((
   105864       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
   105865       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
   105866       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
   105867       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
   105868       notReady, log10N, nRow, cost, used
   105869     ));
   105870 
   105871     /* If this index is the best we have seen so far, then record this
   105872     ** index and its cost in the pCost structure.
   105873     */
   105874     if( (!pIdx || wsFlags)
   105875      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
   105876     ){
   105877       pCost->rCost = cost;
   105878       pCost->used = used;
   105879       pCost->plan.nRow = nRow;
   105880       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
   105881       pCost->plan.nEq = nEq;
   105882       pCost->plan.u.pIdx = pIdx;
   105883     }
   105884 
   105885     /* If there was an INDEXED BY clause, then only that one index is
   105886     ** considered. */
   105887     if( pSrc->pIndex ) break;
   105888 
   105889     /* Reset masks for the next index in the loop */
   105890     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   105891     eqTermMask = idxEqTermMask;
   105892   }
   105893 
   105894   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
   105895   ** is set, then reverse the order that the index will be scanned
   105896   ** in. This is used for application testing, to help find cases
   105897   ** where application behaviour depends on the (undefined) order that
   105898   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
   105899   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
   105900     pCost->plan.wsFlags |= WHERE_REVERSE;
   105901   }
   105902 
   105903   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
   105904   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
   105905   assert( pSrc->pIndex==0
   105906        || pCost->plan.u.pIdx==0
   105907        || pCost->plan.u.pIdx==pSrc->pIndex
   105908   );
   105909 
   105910   WHERETRACE(("best index is: %s\n",
   105911     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
   105912          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
   105913   ));
   105914 
   105915   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   105916   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
   105917   pCost->plan.wsFlags |= eqTermMask;
   105918 }
   105919 
   105920 /*
   105921 ** Find the query plan for accessing table pSrc->pTab. Write the
   105922 ** best query plan and its cost into the WhereCost object supplied
   105923 ** as the last parameter. This function may calculate the cost of
   105924 ** both real and virtual table scans.
   105925 */
   105926 static void bestIndex(
   105927   Parse *pParse,              /* The parsing context */
   105928   WhereClause *pWC,           /* The WHERE clause */
   105929   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   105930   Bitmask notReady,           /* Mask of cursors not available for indexing */
   105931   Bitmask notValid,           /* Cursors not available for any purpose */
   105932   ExprList *pOrderBy,         /* The ORDER BY clause */
   105933   WhereCost *pCost            /* Lowest cost query plan */
   105934 ){
   105935 #ifndef SQLITE_OMIT_VIRTUALTABLE
   105936   if( IsVirtual(pSrc->pTab) ){
   105937     sqlite3_index_info *p = 0;
   105938     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
   105939     if( p->needToFreeIdxStr ){
   105940       sqlite3_free(p->idxStr);
   105941     }
   105942     sqlite3DbFree(pParse->db, p);
   105943   }else
   105944 #endif
   105945   {
   105946     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
   105947   }
   105948 }
   105949 
   105950 /*
   105951 ** Disable a term in the WHERE clause.  Except, do not disable the term
   105952 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   105953 ** or USING clause of that join.
   105954 **
   105955 ** Consider the term t2.z='ok' in the following queries:
   105956 **
   105957 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   105958 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   105959 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   105960 **
   105961 ** The t2.z='ok' is disabled in the in (2) because it originates
   105962 ** in the ON clause.  The term is disabled in (3) because it is not part
   105963 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   105964 **
   105965 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
   105966 ** completely satisfied by indices.
   105967 **
   105968 ** Disabling a term causes that term to not be tested in the inner loop
   105969 ** of the join.  Disabling is an optimization.  When terms are satisfied
   105970 ** by indices, we disable them to prevent redundant tests in the inner
   105971 ** loop.  We would get the correct results if nothing were ever disabled,
   105972 ** but joins might run a little slower.  The trick is to disable as much
   105973 ** as we can without disabling too much.  If we disabled in (1), we'd get
   105974 ** the wrong answer.  See ticket #813.
   105975 */
   105976 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   105977   if( pTerm
   105978       && (pTerm->wtFlags & TERM_CODED)==0
   105979       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   105980   ){
   105981     pTerm->wtFlags |= TERM_CODED;
   105982     if( pTerm->iParent>=0 ){
   105983       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   105984       if( (--pOther->nChild)==0 ){
   105985         disableTerm(pLevel, pOther);
   105986       }
   105987     }
   105988   }
   105989 }
   105990 
   105991 /*
   105992 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   105993 ** to the n registers starting at base.
   105994 **
   105995 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   105996 ** beginning and end of zAff are ignored.  If all entries in zAff are
   105997 ** SQLITE_AFF_NONE, then no code gets generated.
   105998 **
   105999 ** This routine makes its own copy of zAff so that the caller is free
   106000 ** to modify zAff after this routine returns.
   106001 */
   106002 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   106003   Vdbe *v = pParse->pVdbe;
   106004   if( zAff==0 ){
   106005     assert( pParse->db->mallocFailed );
   106006     return;
   106007   }
   106008   assert( v!=0 );
   106009 
   106010   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   106011   ** and end of the affinity string.
   106012   */
   106013   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   106014     n--;
   106015     base++;
   106016     zAff++;
   106017   }
   106018   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   106019     n--;
   106020   }
   106021 
   106022   /* Code the OP_Affinity opcode if there is anything left to do. */
   106023   if( n>0 ){
   106024     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   106025     sqlite3VdbeChangeP4(v, -1, zAff, n);
   106026     sqlite3ExprCacheAffinityChange(pParse, base, n);
   106027   }
   106028 }
   106029 
   106030 
   106031 /*
   106032 ** Generate code for a single equality term of the WHERE clause.  An equality
   106033 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   106034 ** coded.
   106035 **
   106036 ** The current value for the constraint is left in register iReg.
   106037 **
   106038 ** For a constraint of the form X=expr, the expression is evaluated and its
   106039 ** result is left on the stack.  For constraints of the form X IN (...)
   106040 ** this routine sets up a loop that will iterate over all values of X.
   106041 */
   106042 static int codeEqualityTerm(
   106043   Parse *pParse,      /* The parsing context */
   106044   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   106045   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
   106046   int iTarget         /* Attempt to leave results in this register */
   106047 ){
   106048   Expr *pX = pTerm->pExpr;
   106049   Vdbe *v = pParse->pVdbe;
   106050   int iReg;                  /* Register holding results */
   106051 
   106052   assert( iTarget>0 );
   106053   if( pX->op==TK_EQ ){
   106054     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   106055   }else if( pX->op==TK_ISNULL ){
   106056     iReg = iTarget;
   106057     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   106058 #ifndef SQLITE_OMIT_SUBQUERY
   106059   }else{
   106060     int eType;
   106061     int iTab;
   106062     struct InLoop *pIn;
   106063 
   106064     assert( pX->op==TK_IN );
   106065     iReg = iTarget;
   106066     eType = sqlite3FindInIndex(pParse, pX, 0);
   106067     iTab = pX->iTable;
   106068     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   106069     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
   106070     if( pLevel->u.in.nIn==0 ){
   106071       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   106072     }
   106073     pLevel->u.in.nIn++;
   106074     pLevel->u.in.aInLoop =
   106075        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   106076                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   106077     pIn = pLevel->u.in.aInLoop;
   106078     if( pIn ){
   106079       pIn += pLevel->u.in.nIn - 1;
   106080       pIn->iCur = iTab;
   106081       if( eType==IN_INDEX_ROWID ){
   106082         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   106083       }else{
   106084         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   106085       }
   106086       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
   106087     }else{
   106088       pLevel->u.in.nIn = 0;
   106089     }
   106090 #endif
   106091   }
   106092   disableTerm(pLevel, pTerm);
   106093   return iReg;
   106094 }
   106095 
   106096 /*
   106097 ** Generate code that will evaluate all == and IN constraints for an
   106098 ** index.
   106099 **
   106100 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   106101 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   106102 ** The index has as many as three equality constraints, but in this
   106103 ** example, the third "c" value is an inequality.  So only two
   106104 ** constraints are coded.  This routine will generate code to evaluate
   106105 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   106106 ** in consecutive registers and the index of the first register is returned.
   106107 **
   106108 ** In the example above nEq==2.  But this subroutine works for any value
   106109 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   106110 ** The only thing it does is allocate the pLevel->iMem memory cell and
   106111 ** compute the affinity string.
   106112 **
   106113 ** This routine always allocates at least one memory cell and returns
   106114 ** the index of that memory cell. The code that
   106115 ** calls this routine will use that memory cell to store the termination
   106116 ** key value of the loop.  If one or more IN operators appear, then
   106117 ** this routine allocates an additional nEq memory cells for internal
   106118 ** use.
   106119 **
   106120 ** Before returning, *pzAff is set to point to a buffer containing a
   106121 ** copy of the column affinity string of the index allocated using
   106122 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   106123 ** with equality constraints that use NONE affinity are set to
   106124 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   106125 **
   106126 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   106127 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   106128 **
   106129 ** In the example above, the index on t1(a) has TEXT affinity. But since
   106130 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   106131 ** no conversion should be attempted before using a t2.b value as part of
   106132 ** a key to search the index. Hence the first byte in the returned affinity
   106133 ** string in this example would be set to SQLITE_AFF_NONE.
   106134 */
   106135 static int codeAllEqualityTerms(
   106136   Parse *pParse,        /* Parsing context */
   106137   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   106138   WhereClause *pWC,     /* The WHERE clause */
   106139   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
   106140   int nExtraReg,        /* Number of extra registers to allocate */
   106141   char **pzAff          /* OUT: Set to point to affinity string */
   106142 ){
   106143   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
   106144   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   106145   Index *pIdx;                  /* The index being used for this loop */
   106146   int iCur = pLevel->iTabCur;   /* The cursor of the table */
   106147   WhereTerm *pTerm;             /* A single constraint term */
   106148   int j;                        /* Loop counter */
   106149   int regBase;                  /* Base register */
   106150   int nReg;                     /* Number of registers to allocate */
   106151   char *zAff;                   /* Affinity string to return */
   106152 
   106153   /* This module is only called on query plans that use an index. */
   106154   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
   106155   pIdx = pLevel->plan.u.pIdx;
   106156 
   106157   /* Figure out how many memory cells we will need then allocate them.
   106158   */
   106159   regBase = pParse->nMem + 1;
   106160   nReg = pLevel->plan.nEq + nExtraReg;
   106161   pParse->nMem += nReg;
   106162 
   106163   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   106164   if( !zAff ){
   106165     pParse->db->mallocFailed = 1;
   106166   }
   106167 
   106168   /* Evaluate the equality constraints
   106169   */
   106170   assert( pIdx->nColumn>=nEq );
   106171   for(j=0; j<nEq; j++){
   106172     int r1;
   106173     int k = pIdx->aiColumn[j];
   106174     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
   106175     if( NEVER(pTerm==0) ) break;
   106176     /* The following true for indices with redundant columns.
   106177     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   106178     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   106179     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106180     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
   106181     if( r1!=regBase+j ){
   106182       if( nReg==1 ){
   106183         sqlite3ReleaseTempReg(pParse, regBase);
   106184         regBase = r1;
   106185       }else{
   106186         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   106187       }
   106188     }
   106189     testcase( pTerm->eOperator & WO_ISNULL );
   106190     testcase( pTerm->eOperator & WO_IN );
   106191     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   106192       Expr *pRight = pTerm->pExpr->pRight;
   106193       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
   106194       if( zAff ){
   106195         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   106196           zAff[j] = SQLITE_AFF_NONE;
   106197         }
   106198         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   106199           zAff[j] = SQLITE_AFF_NONE;
   106200         }
   106201       }
   106202     }
   106203   }
   106204   *pzAff = zAff;
   106205   return regBase;
   106206 }
   106207 
   106208 #ifndef SQLITE_OMIT_EXPLAIN
   106209 /*
   106210 ** This routine is a helper for explainIndexRange() below
   106211 **
   106212 ** pStr holds the text of an expression that we are building up one term
   106213 ** at a time.  This routine adds a new term to the end of the expression.
   106214 ** Terms are separated by AND so add the "AND" text for second and subsequent
   106215 ** terms only.
   106216 */
   106217 static void explainAppendTerm(
   106218   StrAccum *pStr,             /* The text expression being built */
   106219   int iTerm,                  /* Index of this term.  First is zero */
   106220   const char *zColumn,        /* Name of the column */
   106221   const char *zOp             /* Name of the operator */
   106222 ){
   106223   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   106224   sqlite3StrAccumAppend(pStr, zColumn, -1);
   106225   sqlite3StrAccumAppend(pStr, zOp, 1);
   106226   sqlite3StrAccumAppend(pStr, "?", 1);
   106227 }
   106228 
   106229 /*
   106230 ** Argument pLevel describes a strategy for scanning table pTab. This
   106231 ** function returns a pointer to a string buffer containing a description
   106232 ** of the subset of table rows scanned by the strategy in the form of an
   106233 ** SQL expression. Or, if all rows are scanned, NULL is returned.
   106234 **
   106235 ** For example, if the query:
   106236 **
   106237 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   106238 **
   106239 ** is run and there is an index on (a, b), then this function returns a
   106240 ** string similar to:
   106241 **
   106242 **   "a=? AND b>?"
   106243 **
   106244 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
   106245 ** It is the responsibility of the caller to free the buffer when it is
   106246 ** no longer required.
   106247 */
   106248 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
   106249   WherePlan *pPlan = &pLevel->plan;
   106250   Index *pIndex = pPlan->u.pIdx;
   106251   int nEq = pPlan->nEq;
   106252   int i, j;
   106253   Column *aCol = pTab->aCol;
   106254   int *aiColumn = pIndex->aiColumn;
   106255   StrAccum txt;
   106256 
   106257   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
   106258     return 0;
   106259   }
   106260   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
   106261   txt.db = db;
   106262   sqlite3StrAccumAppend(&txt, " (", 2);
   106263   for(i=0; i<nEq; i++){
   106264     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
   106265   }
   106266 
   106267   j = i;
   106268   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
   106269     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
   106270     explainAppendTerm(&txt, i++, z, ">");
   106271   }
   106272   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
   106273     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
   106274     explainAppendTerm(&txt, i, z, "<");
   106275   }
   106276   sqlite3StrAccumAppend(&txt, ")", 1);
   106277   return sqlite3StrAccumFinish(&txt);
   106278 }
   106279 
   106280 /*
   106281 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   106282 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
   106283 ** record is added to the output to describe the table scan strategy in
   106284 ** pLevel.
   106285 */
   106286 static void explainOneScan(
   106287   Parse *pParse,                  /* Parse context */
   106288   SrcList *pTabList,              /* Table list this loop refers to */
   106289   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   106290   int iLevel,                     /* Value for "level" column of output */
   106291   int iFrom,                      /* Value for "from" column of output */
   106292   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   106293 ){
   106294   if( pParse->explain==2 ){
   106295     u32 flags = pLevel->plan.wsFlags;
   106296     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   106297     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   106298     sqlite3 *db = pParse->db;     /* Database handle */
   106299     char *zMsg;                   /* Text to add to EQP output */
   106300     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
   106301     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   106302     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   106303 
   106304     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
   106305 
   106306     isSearch = (pLevel->plan.nEq>0)
   106307              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   106308              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   106309 
   106310     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
   106311     if( pItem->pSelect ){
   106312       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
   106313     }else{
   106314       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
   106315     }
   106316 
   106317     if( pItem->zAlias ){
   106318       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   106319     }
   106320     if( (flags & WHERE_INDEXED)!=0 ){
   106321       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
   106322       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
   106323           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
   106324           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
   106325           ((flags & WHERE_TEMP_INDEX)?"":" "),
   106326           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
   106327           zWhere
   106328       );
   106329       sqlite3DbFree(db, zWhere);
   106330     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   106331       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
   106332 
   106333       if( flags&WHERE_ROWID_EQ ){
   106334         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
   106335       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   106336         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
   106337       }else if( flags&WHERE_BTM_LIMIT ){
   106338         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
   106339       }else if( flags&WHERE_TOP_LIMIT ){
   106340         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
   106341       }
   106342     }
   106343 #ifndef SQLITE_OMIT_VIRTUALTABLE
   106344     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   106345       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   106346       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   106347                   pVtabIdx->idxNum, pVtabIdx->idxStr);
   106348     }
   106349 #endif
   106350     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
   106351       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
   106352       nRow = 1;
   106353     }else{
   106354       nRow = (sqlite3_int64)pLevel->plan.nRow;
   106355     }
   106356     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
   106357     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
   106358   }
   106359 }
   106360 #else
   106361 # define explainOneScan(u,v,w,x,y,z)
   106362 #endif /* SQLITE_OMIT_EXPLAIN */
   106363 
   106364 
   106365 /*
   106366 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   106367 ** implementation described by pWInfo.
   106368 */
   106369 static Bitmask codeOneLoopStart(
   106370   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   106371   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   106372   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
   106373   Bitmask notReady     /* Which tables are currently available */
   106374 ){
   106375   int j, k;            /* Loop counters */
   106376   int iCur;            /* The VDBE cursor for the table */
   106377   int addrNxt;         /* Where to jump to continue with the next IN case */
   106378   int omitTable;       /* True if we use the index only */
   106379   int bRev;            /* True if we need to scan in reverse order */
   106380   WhereLevel *pLevel;  /* The where level to be coded */
   106381   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   106382   WhereTerm *pTerm;               /* A WHERE clause term */
   106383   Parse *pParse;                  /* Parsing context */
   106384   Vdbe *v;                        /* The prepared stmt under constructions */
   106385   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   106386   int addrBrk;                    /* Jump here to break out of the loop */
   106387   int addrCont;                   /* Jump here to continue with next cycle */
   106388   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   106389   int iReleaseReg = 0;      /* Temp register to free before returning */
   106390 
   106391   pParse = pWInfo->pParse;
   106392   v = pParse->pVdbe;
   106393   pWC = pWInfo->pWC;
   106394   pLevel = &pWInfo->a[iLevel];
   106395   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   106396   iCur = pTabItem->iCursor;
   106397   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
   106398   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
   106399            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
   106400 
   106401   /* Create labels for the "break" and "continue" instructions
   106402   ** for the current loop.  Jump to addrBrk to break out of a loop.
   106403   ** Jump to cont to go immediately to the next iteration of the
   106404   ** loop.
   106405   **
   106406   ** When there is an IN operator, we also have a "addrNxt" label that
   106407   ** means to continue with the next IN value combination.  When
   106408   ** there are no IN operators in the constraints, the "addrNxt" label
   106409   ** is the same as "addrBrk".
   106410   */
   106411   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   106412   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   106413 
   106414   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   106415   ** initialize a memory cell that records if this table matches any
   106416   ** row of the left table of the join.
   106417   */
   106418   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   106419     pLevel->iLeftJoin = ++pParse->nMem;
   106420     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   106421     VdbeComment((v, "init LEFT JOIN no-match flag"));
   106422   }
   106423 
   106424 #ifndef SQLITE_OMIT_VIRTUALTABLE
   106425   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   106426     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
   106427     **          to access the data.
   106428     */
   106429     int iReg;   /* P3 Value for OP_VFilter */
   106430     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   106431     int nConstraint = pVtabIdx->nConstraint;
   106432     struct sqlite3_index_constraint_usage *aUsage =
   106433                                                 pVtabIdx->aConstraintUsage;
   106434     const struct sqlite3_index_constraint *aConstraint =
   106435                                                 pVtabIdx->aConstraint;
   106436 
   106437     sqlite3ExprCachePush(pParse);
   106438     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   106439     for(j=1; j<=nConstraint; j++){
   106440       for(k=0; k<nConstraint; k++){
   106441         if( aUsage[k].argvIndex==j ){
   106442           int iTerm = aConstraint[k].iTermOffset;
   106443           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
   106444           break;
   106445         }
   106446       }
   106447       if( k==nConstraint ) break;
   106448     }
   106449     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
   106450     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
   106451     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
   106452                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
   106453     pVtabIdx->needToFreeIdxStr = 0;
   106454     for(j=0; j<nConstraint; j++){
   106455       if( aUsage[j].omit ){
   106456         int iTerm = aConstraint[j].iTermOffset;
   106457         disableTerm(pLevel, &pWC->a[iTerm]);
   106458       }
   106459     }
   106460     pLevel->op = OP_VNext;
   106461     pLevel->p1 = iCur;
   106462     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   106463     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   106464     sqlite3ExprCachePop(pParse, 1);
   106465   }else
   106466 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   106467 
   106468   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
   106469     /* Case 1:  We can directly reference a single row using an
   106470     **          equality comparison against the ROWID field.  Or
   106471     **          we reference multiple rows using a "rowid IN (...)"
   106472     **          construct.
   106473     */
   106474     iReleaseReg = sqlite3GetTempReg(pParse);
   106475     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
   106476     assert( pTerm!=0 );
   106477     assert( pTerm->pExpr!=0 );
   106478     assert( pTerm->leftCursor==iCur );
   106479     assert( omitTable==0 );
   106480     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106481     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
   106482     addrNxt = pLevel->addrNxt;
   106483     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
   106484     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   106485     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106486     VdbeComment((v, "pk"));
   106487     pLevel->op = OP_Noop;
   106488   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
   106489     /* Case 2:  We have an inequality comparison against the ROWID field.
   106490     */
   106491     int testOp = OP_Noop;
   106492     int start;
   106493     int memEndValue = 0;
   106494     WhereTerm *pStart, *pEnd;
   106495 
   106496     assert( omitTable==0 );
   106497     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
   106498     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
   106499     if( bRev ){
   106500       pTerm = pStart;
   106501       pStart = pEnd;
   106502       pEnd = pTerm;
   106503     }
   106504     if( pStart ){
   106505       Expr *pX;             /* The expression that defines the start bound */
   106506       int r1, rTemp;        /* Registers for holding the start boundary */
   106507 
   106508       /* The following constant maps TK_xx codes into corresponding
   106509       ** seek opcodes.  It depends on a particular ordering of TK_xx
   106510       */
   106511       const u8 aMoveOp[] = {
   106512            /* TK_GT */  OP_SeekGt,
   106513            /* TK_LE */  OP_SeekLe,
   106514            /* TK_LT */  OP_SeekLt,
   106515            /* TK_GE */  OP_SeekGe
   106516       };
   106517       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   106518       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   106519       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   106520 
   106521       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106522       pX = pStart->pExpr;
   106523       assert( pX!=0 );
   106524       assert( pStart->leftCursor==iCur );
   106525       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   106526       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   106527       VdbeComment((v, "pk"));
   106528       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   106529       sqlite3ReleaseTempReg(pParse, rTemp);
   106530       disableTerm(pLevel, pStart);
   106531     }else{
   106532       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   106533     }
   106534     if( pEnd ){
   106535       Expr *pX;
   106536       pX = pEnd->pExpr;
   106537       assert( pX!=0 );
   106538       assert( pEnd->leftCursor==iCur );
   106539       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106540       memEndValue = ++pParse->nMem;
   106541       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   106542       if( pX->op==TK_LT || pX->op==TK_GT ){
   106543         testOp = bRev ? OP_Le : OP_Ge;
   106544       }else{
   106545         testOp = bRev ? OP_Lt : OP_Gt;
   106546       }
   106547       disableTerm(pLevel, pEnd);
   106548     }
   106549     start = sqlite3VdbeCurrentAddr(v);
   106550     pLevel->op = bRev ? OP_Prev : OP_Next;
   106551     pLevel->p1 = iCur;
   106552     pLevel->p2 = start;
   106553     if( pStart==0 && pEnd==0 ){
   106554       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   106555     }else{
   106556       assert( pLevel->p5==0 );
   106557     }
   106558     if( testOp!=OP_Noop ){
   106559       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   106560       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   106561       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106562       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   106563       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   106564     }
   106565   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
   106566     /* Case 3: A scan using an index.
   106567     **
   106568     **         The WHERE clause may contain zero or more equality
   106569     **         terms ("==" or "IN" operators) that refer to the N
   106570     **         left-most columns of the index. It may also contain
   106571     **         inequality constraints (>, <, >= or <=) on the indexed
   106572     **         column that immediately follows the N equalities. Only
   106573     **         the right-most column can be an inequality - the rest must
   106574     **         use the "==" and "IN" operators. For example, if the
   106575     **         index is on (x,y,z), then the following clauses are all
   106576     **         optimized:
   106577     **
   106578     **            x=5
   106579     **            x=5 AND y=10
   106580     **            x=5 AND y<10
   106581     **            x=5 AND y>5 AND y<10
   106582     **            x=5 AND y=5 AND z<=10
   106583     **
   106584     **         The z<10 term of the following cannot be used, only
   106585     **         the x=5 term:
   106586     **
   106587     **            x=5 AND z<10
   106588     **
   106589     **         N may be zero if there are inequality constraints.
   106590     **         If there are no inequality constraints, then N is at
   106591     **         least one.
   106592     **
   106593     **         This case is also used when there are no WHERE clause
   106594     **         constraints but an index is selected anyway, in order
   106595     **         to force the output order to conform to an ORDER BY.
   106596     */
   106597     static const u8 aStartOp[] = {
   106598       0,
   106599       0,
   106600       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   106601       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   106602       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
   106603       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
   106604       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
   106605       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
   106606     };
   106607     static const u8 aEndOp[] = {
   106608       OP_Noop,             /* 0: (!end_constraints) */
   106609       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
   106610       OP_IdxLT             /* 2: (end_constraints && bRev) */
   106611     };
   106612     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
   106613     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
   106614     int regBase;                 /* Base register holding constraint values */
   106615     int r1;                      /* Temp register */
   106616     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   106617     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   106618     int startEq;                 /* True if range start uses ==, >= or <= */
   106619     int endEq;                   /* True if range end uses ==, >= or <= */
   106620     int start_constraints;       /* Start of range is constrained */
   106621     int nConstraint;             /* Number of constraint terms */
   106622     Index *pIdx;                 /* The index we will be using */
   106623     int iIdxCur;                 /* The VDBE cursor for the index */
   106624     int nExtraReg = 0;           /* Number of extra registers needed */
   106625     int op;                      /* Instruction opcode */
   106626     char *zStartAff;             /* Affinity for start of range constraint */
   106627     char *zEndAff;               /* Affinity for end of range constraint */
   106628 
   106629     pIdx = pLevel->plan.u.pIdx;
   106630     iIdxCur = pLevel->iIdxCur;
   106631     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
   106632 
   106633     /* If this loop satisfies a sort order (pOrderBy) request that
   106634     ** was passed to this function to implement a "SELECT min(x) ..."
   106635     ** query, then the caller will only allow the loop to run for
   106636     ** a single iteration. This means that the first row returned
   106637     ** should not have a NULL value stored in 'x'. If column 'x' is
   106638     ** the first one after the nEq equality constraints in the index,
   106639     ** this requires some special handling.
   106640     */
   106641     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
   106642      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
   106643      && (pIdx->nColumn>nEq)
   106644     ){
   106645       /* assert( pOrderBy->nExpr==1 ); */
   106646       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
   106647       isMinQuery = 1;
   106648       nExtraReg = 1;
   106649     }
   106650 
   106651     /* Find any inequality constraint terms for the start and end
   106652     ** of the range.
   106653     */
   106654     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
   106655       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
   106656       nExtraReg = 1;
   106657     }
   106658     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
   106659       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
   106660       nExtraReg = 1;
   106661     }
   106662 
   106663     /* Generate code to evaluate all constraint terms using == or IN
   106664     ** and store the values of those terms in an array of registers
   106665     ** starting at regBase.
   106666     */
   106667     regBase = codeAllEqualityTerms(
   106668         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
   106669     );
   106670     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
   106671     addrNxt = pLevel->addrNxt;
   106672 
   106673     /* If we are doing a reverse order scan on an ascending index, or
   106674     ** a forward order scan on a descending index, interchange the
   106675     ** start and end terms (pRangeStart and pRangeEnd).
   106676     */
   106677     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
   106678      || (bRev && pIdx->nColumn==nEq)
   106679     ){
   106680       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   106681     }
   106682 
   106683     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
   106684     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
   106685     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
   106686     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
   106687     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   106688     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   106689     start_constraints = pRangeStart || nEq>0;
   106690 
   106691     /* Seek the index cursor to the start of the range. */
   106692     nConstraint = nEq;
   106693     if( pRangeStart ){
   106694       Expr *pRight = pRangeStart->pExpr->pRight;
   106695       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   106696       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
   106697         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   106698       }
   106699       if( zStartAff ){
   106700         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
   106701           /* Since the comparison is to be performed with no conversions
   106702           ** applied to the operands, set the affinity to apply to pRight to
   106703           ** SQLITE_AFF_NONE.  */
   106704           zStartAff[nEq] = SQLITE_AFF_NONE;
   106705         }
   106706         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
   106707           zStartAff[nEq] = SQLITE_AFF_NONE;
   106708         }
   106709       }
   106710       nConstraint++;
   106711       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106712     }else if( isMinQuery ){
   106713       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   106714       nConstraint++;
   106715       startEq = 0;
   106716       start_constraints = 1;
   106717     }
   106718     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
   106719     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   106720     assert( op!=0 );
   106721     testcase( op==OP_Rewind );
   106722     testcase( op==OP_Last );
   106723     testcase( op==OP_SeekGt );
   106724     testcase( op==OP_SeekGe );
   106725     testcase( op==OP_SeekLe );
   106726     testcase( op==OP_SeekLt );
   106727     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   106728 
   106729     /* Load the value for the inequality constraint at the end of the
   106730     ** range (if any).
   106731     */
   106732     nConstraint = nEq;
   106733     if( pRangeEnd ){
   106734       Expr *pRight = pRangeEnd->pExpr->pRight;
   106735       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   106736       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   106737       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
   106738         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   106739       }
   106740       if( zEndAff ){
   106741         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
   106742           /* Since the comparison is to be performed with no conversions
   106743           ** applied to the operands, set the affinity to apply to pRight to
   106744           ** SQLITE_AFF_NONE.  */
   106745           zEndAff[nEq] = SQLITE_AFF_NONE;
   106746         }
   106747         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
   106748           zEndAff[nEq] = SQLITE_AFF_NONE;
   106749         }
   106750       }
   106751       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
   106752       nConstraint++;
   106753       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106754     }
   106755     sqlite3DbFree(pParse->db, zStartAff);
   106756     sqlite3DbFree(pParse->db, zEndAff);
   106757 
   106758     /* Top of the loop body */
   106759     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   106760 
   106761     /* Check if the index cursor is past the end of the range. */
   106762     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
   106763     testcase( op==OP_Noop );
   106764     testcase( op==OP_IdxGE );
   106765     testcase( op==OP_IdxLT );
   106766     if( op!=OP_Noop ){
   106767       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   106768       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
   106769     }
   106770 
   106771     /* If there are inequality constraints, check that the value
   106772     ** of the table column that the inequality contrains is not NULL.
   106773     ** If it is, jump to the next iteration of the loop.
   106774     */
   106775     r1 = sqlite3GetTempReg(pParse);
   106776     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
   106777     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
   106778     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
   106779       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
   106780       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
   106781     }
   106782     sqlite3ReleaseTempReg(pParse, r1);
   106783 
   106784     /* Seek the table cursor, if required */
   106785     disableTerm(pLevel, pRangeStart);
   106786     disableTerm(pLevel, pRangeEnd);
   106787     if( !omitTable ){
   106788       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   106789       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   106790       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106791       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   106792     }
   106793 
   106794     /* Record the instruction used to terminate the loop. Disable
   106795     ** WHERE clause terms made redundant by the index range scan.
   106796     */
   106797     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
   106798       pLevel->op = OP_Noop;
   106799     }else if( bRev ){
   106800       pLevel->op = OP_Prev;
   106801     }else{
   106802       pLevel->op = OP_Next;
   106803     }
   106804     pLevel->p1 = iIdxCur;
   106805   }else
   106806 
   106807 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   106808   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
   106809     /* Case 4:  Two or more separately indexed terms connected by OR
   106810     **
   106811     ** Example:
   106812     **
   106813     **   CREATE TABLE t1(a,b,c,d);
   106814     **   CREATE INDEX i1 ON t1(a);
   106815     **   CREATE INDEX i2 ON t1(b);
   106816     **   CREATE INDEX i3 ON t1(c);
   106817     **
   106818     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   106819     **
   106820     ** In the example, there are three indexed terms connected by OR.
   106821     ** The top of the loop looks like this:
   106822     **
   106823     **          Null       1                # Zero the rowset in reg 1
   106824     **
   106825     ** Then, for each indexed term, the following. The arguments to
   106826     ** RowSetTest are such that the rowid of the current row is inserted
   106827     ** into the RowSet. If it is already present, control skips the
   106828     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   106829     **
   106830     **        sqlite3WhereBegin(<term>)
   106831     **          RowSetTest                  # Insert rowid into rowset
   106832     **          Gosub      2 A
   106833     **        sqlite3WhereEnd()
   106834     **
   106835     ** Following the above, code to terminate the loop. Label A, the target
   106836     ** of the Gosub above, jumps to the instruction right after the Goto.
   106837     **
   106838     **          Null       1                # Zero the rowset in reg 1
   106839     **          Goto       B                # The loop is finished.
   106840     **
   106841     **       A: <loop body>                 # Return data, whatever.
   106842     **
   106843     **          Return     2                # Jump back to the Gosub
   106844     **
   106845     **       B: <after the loop>
   106846     **
   106847     */
   106848     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   106849     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   106850 
   106851     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   106852     int regRowset = 0;                        /* Register for RowSet object */
   106853     int regRowid = 0;                         /* Register holding rowid */
   106854     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   106855     int iRetInit;                             /* Address of regReturn init */
   106856     int untestedTerms = 0;             /* Some terms not completely tested */
   106857     int ii;                            /* Loop counter */
   106858     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
   106859 
   106860     pTerm = pLevel->plan.u.pTerm;
   106861     assert( pTerm!=0 );
   106862     assert( pTerm->eOperator==WO_OR );
   106863     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   106864     pOrWc = &pTerm->u.pOrInfo->wc;
   106865     pLevel->op = OP_Return;
   106866     pLevel->p1 = regReturn;
   106867 
   106868     /* Set up a new SrcList ni pOrTab containing the table being scanned
   106869     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   106870     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   106871     */
   106872     if( pWInfo->nLevel>1 ){
   106873       int nNotReady;                 /* The number of notReady tables */
   106874       struct SrcList_item *origSrc;     /* Original list of tables */
   106875       nNotReady = pWInfo->nLevel - iLevel - 1;
   106876       pOrTab = sqlite3StackAllocRaw(pParse->db,
   106877                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   106878       if( pOrTab==0 ) return notReady;
   106879       pOrTab->nAlloc = (i16)(nNotReady + 1);
   106880       pOrTab->nSrc = pOrTab->nAlloc;
   106881       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   106882       origSrc = pWInfo->pTabList->a;
   106883       for(k=1; k<=nNotReady; k++){
   106884         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   106885       }
   106886     }else{
   106887       pOrTab = pWInfo->pTabList;
   106888     }
   106889 
   106890     /* Initialize the rowset register to contain NULL. An SQL NULL is
   106891     ** equivalent to an empty rowset.
   106892     **
   106893     ** Also initialize regReturn to contain the address of the instruction
   106894     ** immediately following the OP_Return at the bottom of the loop. This
   106895     ** is required in a few obscure LEFT JOIN cases where control jumps
   106896     ** over the top of the loop into the body of it. In this case the
   106897     ** correct response for the end-of-loop code (the OP_Return) is to
   106898     ** fall through to the next instruction, just as an OP_Next does if
   106899     ** called on an uninitialized cursor.
   106900     */
   106901     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   106902       regRowset = ++pParse->nMem;
   106903       regRowid = ++pParse->nMem;
   106904       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   106905     }
   106906     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   106907 
   106908     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
   106909     ** Then for every term xN, evaluate as the subexpression: xN AND z
   106910     ** That way, terms in y that are factored into the disjunction will
   106911     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
   106912     **
   106913     ** Actually, each subexpression is converted to "xN AND w" where w is
   106914     ** the "interesting" terms of z - terms that did not originate in the
   106915     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
   106916     ** indices.
   106917     */
   106918     if( pWC->nTerm>1 ){
   106919       int iTerm;
   106920       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
   106921         Expr *pExpr = pWC->a[iTerm].pExpr;
   106922         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
   106923         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
   106924         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
   106925         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
   106926         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
   106927       }
   106928       if( pAndExpr ){
   106929         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
   106930       }
   106931     }
   106932 
   106933     for(ii=0; ii<pOrWc->nTerm; ii++){
   106934       WhereTerm *pOrTerm = &pOrWc->a[ii];
   106935       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
   106936         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
   106937         Expr *pOrExpr = pOrTerm->pExpr;
   106938         if( pAndExpr ){
   106939           pAndExpr->pLeft = pOrExpr;
   106940           pOrExpr = pAndExpr;
   106941         }
   106942         /* Loop through table entries that match term pOrTerm. */
   106943         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
   106944                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
   106945                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
   106946         if( pSubWInfo ){
   106947           explainOneScan(
   106948               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   106949           );
   106950           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   106951             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   106952             int r;
   106953             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
   106954                                          regRowid);
   106955             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
   106956                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
   106957           }
   106958           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   106959 
   106960           /* The pSubWInfo->untestedTerms flag means that this OR term
   106961           ** contained one or more AND term from a notReady table.  The
   106962           ** terms from the notReady table could not be tested and will
   106963           ** need to be tested later.
   106964           */
   106965           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   106966 
   106967           /* Finish the loop through table entries that match term pOrTerm. */
   106968           sqlite3WhereEnd(pSubWInfo);
   106969         }
   106970       }
   106971     }
   106972     if( pAndExpr ){
   106973       pAndExpr->pLeft = 0;
   106974       sqlite3ExprDelete(pParse->db, pAndExpr);
   106975     }
   106976     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   106977     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   106978     sqlite3VdbeResolveLabel(v, iLoopBody);
   106979 
   106980     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
   106981     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   106982   }else
   106983 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   106984 
   106985   {
   106986     /* Case 5:  There is no usable index.  We must do a complete
   106987     **          scan of the entire table.
   106988     */
   106989     static const u8 aStep[] = { OP_Next, OP_Prev };
   106990     static const u8 aStart[] = { OP_Rewind, OP_Last };
   106991     assert( bRev==0 || bRev==1 );
   106992     assert( omitTable==0 );
   106993     pLevel->op = aStep[bRev];
   106994     pLevel->p1 = iCur;
   106995     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   106996     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   106997   }
   106998   notReady &= ~getMask(pWC->pMaskSet, iCur);
   106999 
   107000   /* Insert code to test every subexpression that can be completely
   107001   ** computed using the current set of tables.
   107002   **
   107003   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
   107004   ** the use of indices become tests that are evaluated against each row of
   107005   ** the relevant input tables.
   107006   */
   107007   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   107008     Expr *pE;
   107009     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
   107010     testcase( pTerm->wtFlags & TERM_CODED );
   107011     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   107012     if( (pTerm->prereqAll & notReady)!=0 ){
   107013       testcase( pWInfo->untestedTerms==0
   107014                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   107015       pWInfo->untestedTerms = 1;
   107016       continue;
   107017     }
   107018     pE = pTerm->pExpr;
   107019     assert( pE!=0 );
   107020     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   107021       continue;
   107022     }
   107023     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   107024     pTerm->wtFlags |= TERM_CODED;
   107025   }
   107026 
   107027   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   107028   ** at least one row of the right table has matched the left table.
   107029   */
   107030   if( pLevel->iLeftJoin ){
   107031     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   107032     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   107033     VdbeComment((v, "record LEFT JOIN hit"));
   107034     sqlite3ExprCacheClear(pParse);
   107035     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   107036       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
   107037       testcase( pTerm->wtFlags & TERM_CODED );
   107038       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   107039       if( (pTerm->prereqAll & notReady)!=0 ){
   107040         assert( pWInfo->untestedTerms );
   107041         continue;
   107042       }
   107043       assert( pTerm->pExpr );
   107044       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   107045       pTerm->wtFlags |= TERM_CODED;
   107046     }
   107047   }
   107048   sqlite3ReleaseTempReg(pParse, iReleaseReg);
   107049 
   107050   return notReady;
   107051 }
   107052 
   107053 #if defined(SQLITE_TEST)
   107054 /*
   107055 ** The following variable holds a text description of query plan generated
   107056 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
   107057 ** overwrites the previous.  This information is used for testing and
   107058 ** analysis only.
   107059 */
   107060 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
   107061 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
   107062 
   107063 #endif /* SQLITE_TEST */
   107064 
   107065 
   107066 /*
   107067 ** Free a WhereInfo structure
   107068 */
   107069 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   107070   if( ALWAYS(pWInfo) ){
   107071     int i;
   107072     for(i=0; i<pWInfo->nLevel; i++){
   107073       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
   107074       if( pInfo ){
   107075         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
   107076         if( pInfo->needToFreeIdxStr ){
   107077           sqlite3_free(pInfo->idxStr);
   107078         }
   107079         sqlite3DbFree(db, pInfo);
   107080       }
   107081       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
   107082         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
   107083         if( pIdx ){
   107084           sqlite3DbFree(db, pIdx->zColAff);
   107085           sqlite3DbFree(db, pIdx);
   107086         }
   107087       }
   107088     }
   107089     whereClauseClear(pWInfo->pWC);
   107090     sqlite3DbFree(db, pWInfo);
   107091   }
   107092 }
   107093 
   107094 
   107095 /*
   107096 ** Generate the beginning of the loop used for WHERE clause processing.
   107097 ** The return value is a pointer to an opaque structure that contains
   107098 ** information needed to terminate the loop.  Later, the calling routine
   107099 ** should invoke sqlite3WhereEnd() with the return value of this function
   107100 ** in order to complete the WHERE clause processing.
   107101 **
   107102 ** If an error occurs, this routine returns NULL.
   107103 **
   107104 ** The basic idea is to do a nested loop, one loop for each table in
   107105 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   107106 ** same as a SELECT with only a single table in the FROM clause.)  For
   107107 ** example, if the SQL is this:
   107108 **
   107109 **       SELECT * FROM t1, t2, t3 WHERE ...;
   107110 **
   107111 ** Then the code generated is conceptually like the following:
   107112 **
   107113 **      foreach row1 in t1 do       \    Code generated
   107114 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   107115 **          foreach row3 in t3 do   /
   107116 **            ...
   107117 **          end                     \    Code generated
   107118 **        end                        |-- by sqlite3WhereEnd()
   107119 **      end                         /
   107120 **
   107121 ** Note that the loops might not be nested in the order in which they
   107122 ** appear in the FROM clause if a different order is better able to make
   107123 ** use of indices.  Note also that when the IN operator appears in
   107124 ** the WHERE clause, it might result in additional nested loops for
   107125 ** scanning through all values on the right-hand side of the IN.
   107126 **
   107127 ** There are Btree cursors associated with each table.  t1 uses cursor
   107128 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   107129 ** And so forth.  This routine generates code to open those VDBE cursors
   107130 ** and sqlite3WhereEnd() generates the code to close them.
   107131 **
   107132 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   107133 ** in pTabList pointing at their appropriate entries.  The [...] code
   107134 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   107135 ** data from the various tables of the loop.
   107136 **
   107137 ** If the WHERE clause is empty, the foreach loops must each scan their
   107138 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   107139 ** the tables have indices and there are terms in the WHERE clause that
   107140 ** refer to those indices, a complete table scan can be avoided and the
   107141 ** code will run much faster.  Most of the work of this routine is checking
   107142 ** to see if there are indices that can be used to speed up the loop.
   107143 **
   107144 ** Terms of the WHERE clause are also used to limit which rows actually
   107145 ** make it to the "..." in the middle of the loop.  After each "foreach",
   107146 ** terms of the WHERE clause that use only terms in that loop and outer
   107147 ** loops are evaluated and if false a jump is made around all subsequent
   107148 ** inner loops (or around the "..." if the test occurs within the inner-
   107149 ** most loop)
   107150 **
   107151 ** OUTER JOINS
   107152 **
   107153 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   107154 **
   107155 **    foreach row1 in t1 do
   107156 **      flag = 0
   107157 **      foreach row2 in t2 do
   107158 **        start:
   107159 **          ...
   107160 **          flag = 1
   107161 **      end
   107162 **      if flag==0 then
   107163 **        move the row2 cursor to a null row
   107164 **        goto start
   107165 **      fi
   107166 **    end
   107167 **
   107168 ** ORDER BY CLAUSE PROCESSING
   107169 **
   107170 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
   107171 ** if there is one.  If there is no ORDER BY clause or if this routine
   107172 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
   107173 **
   107174 ** If an index can be used so that the natural output order of the table
   107175 ** scan is correct for the ORDER BY clause, then that index is used and
   107176 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
   107177 ** unnecessary sort of the result set if an index appropriate for the
   107178 ** ORDER BY clause already exists.
   107179 **
   107180 ** If the where clause loops cannot be arranged to provide the correct
   107181 ** output order, then the *ppOrderBy is unchanged.
   107182 */
   107183 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   107184   Parse *pParse,        /* The parser context */
   107185   SrcList *pTabList,    /* A list of all tables to be scanned */
   107186   Expr *pWhere,         /* The WHERE clause */
   107187   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
   107188   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
   107189   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
   107190 ){
   107191   int i;                     /* Loop counter */
   107192   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   107193   int nTabList;              /* Number of elements in pTabList */
   107194   WhereInfo *pWInfo;         /* Will become the return value of this function */
   107195   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   107196   Bitmask notReady;          /* Cursors that are not yet positioned */
   107197   WhereMaskSet *pMaskSet;    /* The expression mask set */
   107198   WhereClause *pWC;               /* Decomposition of the WHERE clause */
   107199   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
   107200   WhereLevel *pLevel;             /* A single level in the pWInfo list */
   107201   int iFrom;                      /* First unused FROM clause element */
   107202   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
   107203   sqlite3 *db;               /* Database connection */
   107204 
   107205   /* The number of tables in the FROM clause is limited by the number of
   107206   ** bits in a Bitmask
   107207   */
   107208   testcase( pTabList->nSrc==BMS );
   107209   if( pTabList->nSrc>BMS ){
   107210     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   107211     return 0;
   107212   }
   107213 
   107214   /* This function normally generates a nested loop for all tables in
   107215   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   107216   ** only generate code for the first table in pTabList and assume that
   107217   ** any cursors associated with subsequent tables are uninitialized.
   107218   */
   107219   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   107220 
   107221   /* Allocate and initialize the WhereInfo structure that will become the
   107222   ** return value. A single allocation is used to store the WhereInfo
   107223   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   107224   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   107225   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   107226   ** some architectures. Hence the ROUND8() below.
   107227   */
   107228   db = pParse->db;
   107229   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   107230   pWInfo = sqlite3DbMallocZero(db,
   107231       nByteWInfo +
   107232       sizeof(WhereClause) +
   107233       sizeof(WhereMaskSet)
   107234   );
   107235   if( db->mallocFailed ){
   107236     sqlite3DbFree(db, pWInfo);
   107237     pWInfo = 0;
   107238     goto whereBeginError;
   107239   }
   107240   pWInfo->nLevel = nTabList;
   107241   pWInfo->pParse = pParse;
   107242   pWInfo->pTabList = pTabList;
   107243   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
   107244   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
   107245   pWInfo->wctrlFlags = wctrlFlags;
   107246   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   107247   pMaskSet = (WhereMaskSet*)&pWC[1];
   107248 
   107249   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
   107250   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
   107251   if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
   107252 
   107253   /* Split the WHERE clause into separate subexpressions where each
   107254   ** subexpression is separated by an AND operator.
   107255   */
   107256   initMaskSet(pMaskSet);
   107257   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
   107258   sqlite3ExprCodeConstants(pParse, pWhere);
   107259   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
   107260 
   107261   /* Special case: a WHERE clause that is constant.  Evaluate the
   107262   ** expression and either jump over all of the code or fall thru.
   107263   */
   107264   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
   107265     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
   107266     pWhere = 0;
   107267   }
   107268 
   107269   /* Assign a bit from the bitmask to every term in the FROM clause.
   107270   **
   107271   ** When assigning bitmask values to FROM clause cursors, it must be
   107272   ** the case that if X is the bitmask for the N-th FROM clause term then
   107273   ** the bitmask for all FROM clause terms to the left of the N-th term
   107274   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   107275   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   107276   ** of the join.  Subtracting one from the right table bitmask gives a
   107277   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   107278   ** for all tables to the left of a left join is important.  Ticket #3015.
   107279   **
   107280   ** Configure the WhereClause.vmask variable so that bits that correspond
   107281   ** to virtual table cursors are set. This is used to selectively disable
   107282   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
   107283   ** with virtual tables.
   107284   **
   107285   ** Note that bitmasks are created for all pTabList->nSrc tables in
   107286   ** pTabList, not just the first nTabList tables.  nTabList is normally
   107287   ** equal to pTabList->nSrc but might be shortened to 1 if the
   107288   ** WHERE_ONETABLE_ONLY flag is set.
   107289   */
   107290   assert( pWC->vmask==0 && pMaskSet->n==0 );
   107291   for(i=0; i<pTabList->nSrc; i++){
   107292     createMask(pMaskSet, pTabList->a[i].iCursor);
   107293 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107294     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
   107295       pWC->vmask |= ((Bitmask)1 << i);
   107296     }
   107297 #endif
   107298   }
   107299 #ifndef NDEBUG
   107300   {
   107301     Bitmask toTheLeft = 0;
   107302     for(i=0; i<pTabList->nSrc; i++){
   107303       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
   107304       assert( (m-1)==toTheLeft );
   107305       toTheLeft |= m;
   107306     }
   107307   }
   107308 #endif
   107309 
   107310   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   107311   ** add new virtual terms onto the end of the WHERE clause.  We do not
   107312   ** want to analyze these virtual terms, so start analyzing at the end
   107313   ** and work forward so that the added virtual terms are never processed.
   107314   */
   107315   exprAnalyzeAll(pTabList, pWC);
   107316   if( db->mallocFailed ){
   107317     goto whereBeginError;
   107318   }
   107319 
   107320   /* Check if the DISTINCT qualifier, if there is one, is redundant.
   107321   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
   107322   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
   107323   */
   107324   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
   107325     pDistinct = 0;
   107326     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   107327   }
   107328 
   107329   /* Chose the best index to use for each table in the FROM clause.
   107330   **
   107331   ** This loop fills in the following fields:
   107332   **
   107333   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
   107334   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
   107335   **   pWInfo->a[].nEq       The number of == and IN constraints
   107336   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
   107337   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
   107338   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
   107339   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
   107340   **
   107341   ** This loop also figures out the nesting order of tables in the FROM
   107342   ** clause.
   107343   */
   107344   notReady = ~(Bitmask)0;
   107345   andFlags = ~0;
   107346   WHERETRACE(("*** Optimizer Start ***\n"));
   107347   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   107348     WhereCost bestPlan;         /* Most efficient plan seen so far */
   107349     Index *pIdx;                /* Index for FROM table at pTabItem */
   107350     int j;                      /* For looping over FROM tables */
   107351     int bestJ = -1;             /* The value of j */
   107352     Bitmask m;                  /* Bitmask value for j or bestJ */
   107353     int isOptimal;              /* Iterator for optimal/non-optimal search */
   107354     int nUnconstrained;         /* Number tables without INDEXED BY */
   107355     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
   107356 
   107357     memset(&bestPlan, 0, sizeof(bestPlan));
   107358     bestPlan.rCost = SQLITE_BIG_DBL;
   107359     WHERETRACE(("*** Begin search for loop %d ***\n", i));
   107360 
   107361     /* Loop through the remaining entries in the FROM clause to find the
   107362     ** next nested loop. The loop tests all FROM clause entries
   107363     ** either once or twice.
   107364     **
   107365     ** The first test is always performed if there are two or more entries
   107366     ** remaining and never performed if there is only one FROM clause entry
   107367     ** to choose from.  The first test looks for an "optimal" scan.  In
   107368     ** this context an optimal scan is one that uses the same strategy
   107369     ** for the given FROM clause entry as would be selected if the entry
   107370     ** were used as the innermost nested loop.  In other words, a table
   107371     ** is chosen such that the cost of running that table cannot be reduced
   107372     ** by waiting for other tables to run first.  This "optimal" test works
   107373     ** by first assuming that the FROM clause is on the inner loop and finding
   107374     ** its query plan, then checking to see if that query plan uses any
   107375     ** other FROM clause terms that are notReady.  If no notReady terms are
   107376     ** used then the "optimal" query plan works.
   107377     **
   107378     ** Note that the WhereCost.nRow parameter for an optimal scan might
   107379     ** not be as small as it would be if the table really were the innermost
   107380     ** join.  The nRow value can be reduced by WHERE clause constraints
   107381     ** that do not use indices.  But this nRow reduction only happens if the
   107382     ** table really is the innermost join.
   107383     **
   107384     ** The second loop iteration is only performed if no optimal scan
   107385     ** strategies were found by the first iteration. This second iteration
   107386     ** is used to search for the lowest cost scan overall.
   107387     **
   107388     ** Previous versions of SQLite performed only the second iteration -
   107389     ** the next outermost loop was always that with the lowest overall
   107390     ** cost. However, this meant that SQLite could select the wrong plan
   107391     ** for scripts such as the following:
   107392     **
   107393     **   CREATE TABLE t1(a, b);
   107394     **   CREATE TABLE t2(c, d);
   107395     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
   107396     **
   107397     ** The best strategy is to iterate through table t1 first. However it
   107398     ** is not possible to determine this with a simple greedy algorithm.
   107399     ** Since the cost of a linear scan through table t2 is the same
   107400     ** as the cost of a linear scan through table t1, a simple greedy
   107401     ** algorithm may choose to use t2 for the outer loop, which is a much
   107402     ** costlier approach.
   107403     */
   107404     nUnconstrained = 0;
   107405     notIndexed = 0;
   107406     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
   107407       Bitmask mask;             /* Mask of tables not yet ready */
   107408       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
   107409         int doNotReorder;    /* True if this table should not be reordered */
   107410         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
   107411         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
   107412         ExprList *pDist;     /* DISTINCT clause for index to optimize */
   107413 
   107414         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
   107415         if( j!=iFrom && doNotReorder ) break;
   107416         m = getMask(pMaskSet, pTabItem->iCursor);
   107417         if( (m & notReady)==0 ){
   107418           if( j==iFrom ) iFrom++;
   107419           continue;
   107420         }
   107421         mask = (isOptimal ? m : notReady);
   107422         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
   107423         pDist = (i==0 ? pDistinct : 0);
   107424         if( pTabItem->pIndex==0 ) nUnconstrained++;
   107425 
   107426         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
   107427                     j, isOptimal));
   107428         assert( pTabItem->pTab );
   107429 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107430         if( IsVirtual(pTabItem->pTab) ){
   107431           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
   107432           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   107433                            &sCost, pp);
   107434         }else
   107435 #endif
   107436         {
   107437           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   107438               pDist, &sCost);
   107439         }
   107440         assert( isOptimal || (sCost.used&notReady)==0 );
   107441 
   107442         /* If an INDEXED BY clause is present, then the plan must use that
   107443         ** index if it uses any index at all */
   107444         assert( pTabItem->pIndex==0
   107445                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
   107446                   || sCost.plan.u.pIdx==pTabItem->pIndex );
   107447 
   107448         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
   107449           notIndexed |= m;
   107450         }
   107451 
   107452         /* Conditions under which this table becomes the best so far:
   107453         **
   107454         **   (1) The table must not depend on other tables that have not
   107455         **       yet run.
   107456         **
   107457         **   (2) A full-table-scan plan cannot supercede indexed plan unless
   107458         **       the full-table-scan is an "optimal" plan as defined above.
   107459         **
   107460         **   (3) All tables have an INDEXED BY clause or this table lacks an
   107461         **       INDEXED BY clause or this table uses the specific
   107462         **       index specified by its INDEXED BY clause.  This rule ensures
   107463         **       that a best-so-far is always selected even if an impossible
   107464         **       combination of INDEXED BY clauses are given.  The error
   107465         **       will be detected and relayed back to the application later.
   107466         **       The NEVER() comes about because rule (2) above prevents
   107467         **       An indexable full-table-scan from reaching rule (3).
   107468         **
   107469         **   (4) The plan cost must be lower than prior plans or else the
   107470         **       cost must be the same and the number of rows must be lower.
   107471         */
   107472         if( (sCost.used&notReady)==0                       /* (1) */
   107473             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
   107474                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
   107475                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
   107476             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
   107477                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
   107478             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
   107479                 || (sCost.rCost<=bestPlan.rCost
   107480                  && sCost.plan.nRow<bestPlan.plan.nRow))
   107481         ){
   107482           WHERETRACE(("=== table %d is best so far"
   107483                       " with cost=%g and nRow=%g\n",
   107484                       j, sCost.rCost, sCost.plan.nRow));
   107485           bestPlan = sCost;
   107486           bestJ = j;
   107487         }
   107488         if( doNotReorder ) break;
   107489       }
   107490     }
   107491     assert( bestJ>=0 );
   107492     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
   107493     WHERETRACE(("*** Optimizer selects table %d for loop %d"
   107494                 " with cost=%g and nRow=%g\n",
   107495                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
   107496     /* The ALWAYS() that follows was added to hush up clang scan-build */
   107497     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
   107498       *ppOrderBy = 0;
   107499     }
   107500     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
   107501       assert( pWInfo->eDistinct==0 );
   107502       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   107503     }
   107504     andFlags &= bestPlan.plan.wsFlags;
   107505     pLevel->plan = bestPlan.plan;
   107506     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
   107507     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
   107508     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
   107509       pLevel->iIdxCur = pParse->nTab++;
   107510     }else{
   107511       pLevel->iIdxCur = -1;
   107512     }
   107513     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
   107514     pLevel->iFrom = (u8)bestJ;
   107515     if( bestPlan.plan.nRow>=(double)1 ){
   107516       pParse->nQueryLoop *= bestPlan.plan.nRow;
   107517     }
   107518 
   107519     /* Check that if the table scanned by this loop iteration had an
   107520     ** INDEXED BY clause attached to it, that the named index is being
   107521     ** used for the scan. If not, then query compilation has failed.
   107522     ** Return an error.
   107523     */
   107524     pIdx = pTabList->a[bestJ].pIndex;
   107525     if( pIdx ){
   107526       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
   107527         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
   107528         goto whereBeginError;
   107529       }else{
   107530         /* If an INDEXED BY clause is used, the bestIndex() function is
   107531         ** guaranteed to find the index specified in the INDEXED BY clause
   107532         ** if it find an index at all. */
   107533         assert( bestPlan.plan.u.pIdx==pIdx );
   107534       }
   107535     }
   107536   }
   107537   WHERETRACE(("*** Optimizer Finished ***\n"));
   107538   if( pParse->nErr || db->mallocFailed ){
   107539     goto whereBeginError;
   107540   }
   107541 
   107542   /* If the total query only selects a single row, then the ORDER BY
   107543   ** clause is irrelevant.
   107544   */
   107545   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
   107546     *ppOrderBy = 0;
   107547   }
   107548 
   107549   /* If the caller is an UPDATE or DELETE statement that is requesting
   107550   ** to use a one-pass algorithm, determine if this is appropriate.
   107551   ** The one-pass algorithm only works if the WHERE clause constraints
   107552   ** the statement to update a single row.
   107553   */
   107554   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   107555   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
   107556     pWInfo->okOnePass = 1;
   107557     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
   107558   }
   107559 
   107560   /* Open all tables in the pTabList and any indices selected for
   107561   ** searching those tables.
   107562   */
   107563   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
   107564   notReady = ~(Bitmask)0;
   107565   pWInfo->nRowOut = (double)1;
   107566   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   107567     Table *pTab;     /* Table to open */
   107568     int iDb;         /* Index of database containing table/index */
   107569 
   107570     pTabItem = &pTabList->a[pLevel->iFrom];
   107571     pTab = pTabItem->pTab;
   107572     pLevel->iTabCur = pTabItem->iCursor;
   107573     pWInfo->nRowOut *= pLevel->plan.nRow;
   107574     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   107575     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   107576       /* Do nothing */
   107577     }else
   107578 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107579     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   107580       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   107581       int iCur = pTabItem->iCursor;
   107582       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   107583     }else
   107584 #endif
   107585     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107586          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
   107587       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
   107588       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   107589       testcase( pTab->nCol==BMS-1 );
   107590       testcase( pTab->nCol==BMS );
   107591       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
   107592         Bitmask b = pTabItem->colUsed;
   107593         int n = 0;
   107594         for(; b; b=b>>1, n++){}
   107595         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   107596                             SQLITE_INT_TO_PTR(n), P4_INT32);
   107597         assert( n<=pTab->nCol );
   107598       }
   107599     }else{
   107600       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   107601     }
   107602 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   107603     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
   107604       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
   107605     }else
   107606 #endif
   107607     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   107608       Index *pIx = pLevel->plan.u.pIdx;
   107609       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
   107610       int iIdxCur = pLevel->iIdxCur;
   107611       assert( pIx->pSchema==pTab->pSchema );
   107612       assert( iIdxCur>=0 );
   107613       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
   107614                         (char*)pKey, P4_KEYINFO_HANDOFF);
   107615       VdbeComment((v, "%s", pIx->zName));
   107616     }
   107617     sqlite3CodeVerifySchema(pParse, iDb);
   107618     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
   107619   }
   107620   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   107621   if( db->mallocFailed ) goto whereBeginError;
   107622 
   107623   /* Generate the code to do the search.  Each iteration of the for
   107624   ** loop below generates code for a single nested loop of the VM
   107625   ** program.
   107626   */
   107627   notReady = ~(Bitmask)0;
   107628   for(i=0; i<nTabList; i++){
   107629     pLevel = &pWInfo->a[i];
   107630     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
   107631     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
   107632     pWInfo->iContinue = pLevel->addrCont;
   107633   }
   107634 
   107635 #ifdef SQLITE_TEST  /* For testing and debugging use only */
   107636   /* Record in the query plan information about the current table
   107637   ** and the index used to access it (if any).  If the table itself
   107638   ** is not used, its name is just '{}'.  If no index is used
   107639   ** the index is listed as "{}".  If the primary key is used the
   107640   ** index name is '*'.
   107641   */
   107642   for(i=0; i<nTabList; i++){
   107643     char *z;
   107644     int n;
   107645     pLevel = &pWInfo->a[i];
   107646     pTabItem = &pTabList->a[pLevel->iFrom];
   107647     z = pTabItem->zAlias;
   107648     if( z==0 ) z = pTabItem->pTab->zName;
   107649     n = sqlite3Strlen30(z);
   107650     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
   107651       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
   107652         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
   107653         nQPlan += 2;
   107654       }else{
   107655         memcpy(&sqlite3_query_plan[nQPlan], z, n);
   107656         nQPlan += n;
   107657       }
   107658       sqlite3_query_plan[nQPlan++] = ' ';
   107659     }
   107660     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
   107661     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
   107662     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   107663       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
   107664       nQPlan += 2;
   107665     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   107666       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
   107667       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
   107668         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
   107669         nQPlan += n;
   107670         sqlite3_query_plan[nQPlan++] = ' ';
   107671       }
   107672     }else{
   107673       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
   107674       nQPlan += 3;
   107675     }
   107676   }
   107677   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
   107678     sqlite3_query_plan[--nQPlan] = 0;
   107679   }
   107680   sqlite3_query_plan[nQPlan] = 0;
   107681   nQPlan = 0;
   107682 #endif /* SQLITE_TEST // Testing and debugging use only */
   107683 
   107684   /* Record the continuation address in the WhereInfo structure.  Then
   107685   ** clean up and return.
   107686   */
   107687   return pWInfo;
   107688 
   107689   /* Jump here if malloc fails */
   107690 whereBeginError:
   107691   if( pWInfo ){
   107692     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   107693     whereInfoFree(db, pWInfo);
   107694   }
   107695   return 0;
   107696 }
   107697 
   107698 /*
   107699 ** Generate the end of the WHERE loop.  See comments on
   107700 ** sqlite3WhereBegin() for additional information.
   107701 */
   107702 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   107703   Parse *pParse = pWInfo->pParse;
   107704   Vdbe *v = pParse->pVdbe;
   107705   int i;
   107706   WhereLevel *pLevel;
   107707   SrcList *pTabList = pWInfo->pTabList;
   107708   sqlite3 *db = pParse->db;
   107709 
   107710   /* Generate loop termination code.
   107711   */
   107712   sqlite3ExprCacheClear(pParse);
   107713   for(i=pWInfo->nLevel-1; i>=0; i--){
   107714     pLevel = &pWInfo->a[i];
   107715     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   107716     if( pLevel->op!=OP_Noop ){
   107717       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
   107718       sqlite3VdbeChangeP5(v, pLevel->p5);
   107719     }
   107720     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   107721       struct InLoop *pIn;
   107722       int j;
   107723       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   107724       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   107725         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   107726         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
   107727         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   107728       }
   107729       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   107730     }
   107731     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   107732     if( pLevel->iLeftJoin ){
   107733       int addr;
   107734       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
   107735       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107736            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
   107737       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
   107738         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   107739       }
   107740       if( pLevel->iIdxCur>=0 ){
   107741         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   107742       }
   107743       if( pLevel->op==OP_Return ){
   107744         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   107745       }else{
   107746         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   107747       }
   107748       sqlite3VdbeJumpHere(v, addr);
   107749     }
   107750   }
   107751 
   107752   /* The "break" point is here, just past the end of the outer loop.
   107753   ** Set it.
   107754   */
   107755   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   107756 
   107757   /* Close all of the cursors that were opened by sqlite3WhereBegin.
   107758   */
   107759   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
   107760   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   107761     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   107762     Table *pTab = pTabItem->pTab;
   107763     assert( pTab!=0 );
   107764     if( (pTab->tabFlags & TF_Ephemeral)==0
   107765      && pTab->pSelect==0
   107766      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
   107767     ){
   107768       int ws = pLevel->plan.wsFlags;
   107769       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
   107770         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   107771       }
   107772       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
   107773         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   107774       }
   107775     }
   107776 
   107777     /* If this scan uses an index, make code substitutions to read data
   107778     ** from the index in preference to the table. Sometimes, this means
   107779     ** the table need never be read from. This is a performance boost,
   107780     ** as the vdbe level waits until the table is read before actually
   107781     ** seeking the table cursor to the record corresponding to the current
   107782     ** position in the index.
   107783     **
   107784     ** Calls to the code generator in between sqlite3WhereBegin and
   107785     ** sqlite3WhereEnd will have created code that references the table
   107786     ** directly.  This loop scans all that code looking for opcodes
   107787     ** that reference the table and converts them into opcodes that
   107788     ** reference the index.
   107789     */
   107790     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
   107791       int k, j, last;
   107792       VdbeOp *pOp;
   107793       Index *pIdx = pLevel->plan.u.pIdx;
   107794 
   107795       assert( pIdx!=0 );
   107796       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
   107797       last = sqlite3VdbeCurrentAddr(v);
   107798       for(k=pWInfo->iTop; k<last; k++, pOp++){
   107799         if( pOp->p1!=pLevel->iTabCur ) continue;
   107800         if( pOp->opcode==OP_Column ){
   107801           for(j=0; j<pIdx->nColumn; j++){
   107802             if( pOp->p2==pIdx->aiColumn[j] ){
   107803               pOp->p2 = j;
   107804               pOp->p1 = pLevel->iIdxCur;
   107805               break;
   107806             }
   107807           }
   107808           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107809                || j<pIdx->nColumn );
   107810         }else if( pOp->opcode==OP_Rowid ){
   107811           pOp->p1 = pLevel->iIdxCur;
   107812           pOp->opcode = OP_IdxRowid;
   107813         }
   107814       }
   107815     }
   107816   }
   107817 
   107818   /* Final cleanup
   107819   */
   107820   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   107821   whereInfoFree(db, pWInfo);
   107822   return;
   107823 }
   107824 
   107825 /************** End of where.c ***********************************************/
   107826 /************** Begin file parse.c *******************************************/
   107827 /* Driver template for the LEMON parser generator.
   107828 ** The author disclaims copyright to this source code.
   107829 **
   107830 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   107831 ** The only modifications are the addition of a couple of NEVER()
   107832 ** macros to disable tests that are needed in the case of a general
   107833 ** LALR(1) grammar but which are always false in the
   107834 ** specific grammar used by SQLite.
   107835 */
   107836 /* First off, code is included that follows the "include" declaration
   107837 ** in the input grammar file. */
   107838 /* #include <stdio.h> */
   107839 
   107840 
   107841 /*
   107842 ** Disable all error recovery processing in the parser push-down
   107843 ** automaton.
   107844 */
   107845 #define YYNOERRORRECOVERY 1
   107846 
   107847 /*
   107848 ** Make yytestcase() the same as testcase()
   107849 */
   107850 #define yytestcase(X) testcase(X)
   107851 
   107852 /*
   107853 ** An instance of this structure holds information about the
   107854 ** LIMIT clause of a SELECT statement.
   107855 */
   107856 struct LimitVal {
   107857   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   107858   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   107859 };
   107860 
   107861 /*
   107862 ** An instance of this structure is used to store the LIKE,
   107863 ** GLOB, NOT LIKE, and NOT GLOB operators.
   107864 */
   107865 struct LikeOp {
   107866   Token eOperator;  /* "like" or "glob" or "regexp" */
   107867   int not;         /* True if the NOT keyword is present */
   107868 };
   107869 
   107870 /*
   107871 ** An instance of the following structure describes the event of a
   107872 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   107873 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   107874 **
   107875 **      UPDATE ON (a,b,c)
   107876 **
   107877 ** Then the "b" IdList records the list "a,b,c".
   107878 */
   107879 struct TrigEvent { int a; IdList * b; };
   107880 
   107881 /*
   107882 ** An instance of this structure holds the ATTACH key and the key type.
   107883 */
   107884 struct AttachKey { int type;  Token key; };
   107885 
   107886 /*
   107887 ** One or more VALUES claues
   107888 */
   107889 struct ValueList {
   107890   ExprList *pList;
   107891   Select *pSelect;
   107892 };
   107893 
   107894 
   107895   /* This is a utility routine used to set the ExprSpan.zStart and
   107896   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   107897   ** range of text beginning with pStart and going to the end of pEnd.
   107898   */
   107899   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   107900     pOut->zStart = pStart->z;
   107901     pOut->zEnd = &pEnd->z[pEnd->n];
   107902   }
   107903 
   107904   /* Construct a new Expr object from a single identifier.  Use the
   107905   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   107906   ** that created the expression.
   107907   */
   107908   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   107909     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   107910     pOut->zStart = pValue->z;
   107911     pOut->zEnd = &pValue->z[pValue->n];
   107912   }
   107913 
   107914   /* This routine constructs a binary expression node out of two ExprSpan
   107915   ** objects and uses the result to populate a new ExprSpan object.
   107916   */
   107917   static void spanBinaryExpr(
   107918     ExprSpan *pOut,     /* Write the result here */
   107919     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   107920     int op,             /* The binary operation */
   107921     ExprSpan *pLeft,    /* The left operand */
   107922     ExprSpan *pRight    /* The right operand */
   107923   ){
   107924     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   107925     pOut->zStart = pLeft->zStart;
   107926     pOut->zEnd = pRight->zEnd;
   107927   }
   107928 
   107929   /* Construct an expression node for a unary postfix operator
   107930   */
   107931   static void spanUnaryPostfix(
   107932     ExprSpan *pOut,        /* Write the new expression node here */
   107933     Parse *pParse,         /* Parsing context to record errors */
   107934     int op,                /* The operator */
   107935     ExprSpan *pOperand,    /* The operand */
   107936     Token *pPostOp         /* The operand token for setting the span */
   107937   ){
   107938     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   107939     pOut->zStart = pOperand->zStart;
   107940     pOut->zEnd = &pPostOp->z[pPostOp->n];
   107941   }
   107942 
   107943   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   107944   ** unary TK_ISNULL or TK_NOTNULL expression. */
   107945   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   107946     sqlite3 *db = pParse->db;
   107947     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   107948       pA->op = (u8)op;
   107949       sqlite3ExprDelete(db, pA->pRight);
   107950       pA->pRight = 0;
   107951     }
   107952   }
   107953 
   107954   /* Construct an expression node for a unary prefix operator
   107955   */
   107956   static void spanUnaryPrefix(
   107957     ExprSpan *pOut,        /* Write the new expression node here */
   107958     Parse *pParse,         /* Parsing context to record errors */
   107959     int op,                /* The operator */
   107960     ExprSpan *pOperand,    /* The operand */
   107961     Token *pPreOp         /* The operand token for setting the span */
   107962   ){
   107963     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   107964     pOut->zStart = pPreOp->z;
   107965     pOut->zEnd = pOperand->zEnd;
   107966   }
   107967 /* Next is all token values, in a form suitable for use by makeheaders.
   107968 ** This section will be null unless lemon is run with the -m switch.
   107969 */
   107970 /*
   107971 ** These constants (all generated automatically by the parser generator)
   107972 ** specify the various kinds of tokens (terminals) that the parser
   107973 ** understands.
   107974 **
   107975 ** Each symbol here is a terminal symbol in the grammar.
   107976 */
   107977 /* Make sure the INTERFACE macro is defined.
   107978 */
   107979 #ifndef INTERFACE
   107980 # define INTERFACE 1
   107981 #endif
   107982 /* The next thing included is series of defines which control
   107983 ** various aspects of the generated parser.
   107984 **    YYCODETYPE         is the data type used for storing terminal
   107985 **                       and nonterminal numbers.  "unsigned char" is
   107986 **                       used if there are fewer than 250 terminals
   107987 **                       and nonterminals.  "int" is used otherwise.
   107988 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   107989 **                       to no legal terminal or nonterminal number.  This
   107990 **                       number is used to fill in empty slots of the hash
   107991 **                       table.
   107992 **    YYFALLBACK         If defined, this indicates that one or more tokens
   107993 **                       have fall-back values which should be used if the
   107994 **                       original value of the token will not parse.
   107995 **    YYACTIONTYPE       is the data type used for storing terminal
   107996 **                       and nonterminal numbers.  "unsigned char" is
   107997 **                       used if there are fewer than 250 rules and
   107998 **                       states combined.  "int" is used otherwise.
   107999 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   108000 **                       directly to the parser from the tokenizer.
   108001 **    YYMINORTYPE        is the data type used for all minor tokens.
   108002 **                       This is typically a union of many types, one of
   108003 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   108004 **                       for base tokens is called "yy0".
   108005 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   108006 **                       zero the stack is dynamically sized using realloc()
   108007 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   108008 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   108009 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   108010 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   108011 **    YYNSTATE           the combined number of states.
   108012 **    YYNRULE            the number of rules in the grammar
   108013 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   108014 **                       defined, then do no error processing.
   108015 */
   108016 #define YYCODETYPE unsigned char
   108017 #define YYNOCODE 251
   108018 #define YYACTIONTYPE unsigned short int
   108019 #define YYWILDCARD 67
   108020 #define sqlite3ParserTOKENTYPE Token
   108021 typedef union {
   108022   int yyinit;
   108023   sqlite3ParserTOKENTYPE yy0;
   108024   struct LimitVal yy64;
   108025   Expr* yy122;
   108026   Select* yy159;
   108027   IdList* yy180;
   108028   struct {int value; int mask;} yy207;
   108029   u8 yy258;
   108030   struct LikeOp yy318;
   108031   TriggerStep* yy327;
   108032   ExprSpan yy342;
   108033   SrcList* yy347;
   108034   int yy392;
   108035   struct TrigEvent yy410;
   108036   ExprList* yy442;
   108037   struct ValueList yy487;
   108038 } YYMINORTYPE;
   108039 #ifndef YYSTACKDEPTH
   108040 #define YYSTACKDEPTH 100
   108041 #endif
   108042 #define sqlite3ParserARG_SDECL Parse *pParse;
   108043 #define sqlite3ParserARG_PDECL ,Parse *pParse
   108044 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   108045 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   108046 #define YYNSTATE 629
   108047 #define YYNRULE 327
   108048 #define YYFALLBACK 1
   108049 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   108050 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   108051 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   108052 
   108053 /* The yyzerominor constant is used to initialize instances of
   108054 ** YYMINORTYPE objects to zero. */
   108055 static const YYMINORTYPE yyzerominor = { 0 };
   108056 
   108057 /* Define the yytestcase() macro to be a no-op if is not already defined
   108058 ** otherwise.
   108059 **
   108060 ** Applications can choose to define yytestcase() in the %include section
   108061 ** to a macro that can assist in verifying code coverage.  For production
   108062 ** code the yytestcase() macro should be turned off.  But it is useful
   108063 ** for testing.
   108064 */
   108065 #ifndef yytestcase
   108066 # define yytestcase(X)
   108067 #endif
   108068 
   108069 
   108070 /* Next are the tables used to determine what action to take based on the
   108071 ** current state and lookahead token.  These tables are used to implement
   108072 ** functions that take a state number and lookahead value and return an
   108073 ** action integer.
   108074 **
   108075 ** Suppose the action integer is N.  Then the action is determined as
   108076 ** follows
   108077 **
   108078 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   108079 **                                      token onto the stack and goto state N.
   108080 **
   108081 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   108082 **
   108083 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   108084 **
   108085 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   108086 **
   108087 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   108088 **                                      slots in the yy_action[] table.
   108089 **
   108090 ** The action table is constructed as a single large table named yy_action[].
   108091 ** Given state S and lookahead X, the action is computed as
   108092 **
   108093 **      yy_action[ yy_shift_ofst[S] + X ]
   108094 **
   108095 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   108096 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   108097 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   108098 ** and that yy_default[S] should be used instead.
   108099 **
   108100 ** The formula above is for computing the action when the lookahead is
   108101 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   108102 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   108103 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   108104 ** YY_SHIFT_USE_DFLT.
   108105 **
   108106 ** The following are the tables generated in this section:
   108107 **
   108108 **  yy_action[]        A single table containing all actions.
   108109 **  yy_lookahead[]     A table containing the lookahead for each entry in
   108110 **                     yy_action.  Used to detect hash collisions.
   108111 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   108112 **                     shifting terminals.
   108113 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   108114 **                     shifting non-terminals after a reduce.
   108115 **  yy_default[]       Default action for each state.
   108116 */
   108117 #define YY_ACTTAB_COUNT (1580)
   108118 static const YYACTIONTYPE yy_action[] = {
   108119  /*     0 */   310,  328,  574,  573,   15,  172,  187,  596,   56,   56,
   108120  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
   108121  /*    20 */    52,   52,   51,  234,  622,  621,  626,  622,  621,  299,
   108122  /*    30 */   589,  583,   56,   56,   56,   56,  236,   54,   54,   54,
   108123  /*    40 */    54,   53,   53,   52,   52,   52,   51,  234,  351,   57,
   108124  /*    50 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108125  /*    60 */    56,   56,  570,   54,   54,   54,   54,   53,   53,   52,
   108126  /*    70 */    52,   52,   51,  234,  310,  596,  326,  607,  233,  232,
   108127  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108128  /*    90 */    51,  234,  619,  618,  326,  619,  618,  166,  605,  492,
   108129  /*   100 */   381,  378,  377,  235,  589,  583,  554,  495,    1,   59,
   108130  /*   110 */    19,  376,  622,  621,   53,   53,   52,   52,   52,   51,
   108131  /*   120 */   234,  571,  571,   57,   58,   48,  581,  580,  582,  582,
   108132  /*   130 */    55,   55,   56,   56,   56,   56,  215,   54,   54,   54,
   108133  /*   140 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  224,
   108134  /*   150 */    50,   47,  147,  177,  139,  281,  384,  276,  383,  169,
   108135  /*   160 */   408,  553,  578,  578,  622,  621,  272,  224,  439,  550,
   108136  /*   170 */   552,  410,  139,  281,  384,  276,  383,  169,  589,  583,
   108137  /*   180 */   619,  618,  280,  620,  272,  195,  413,  309,  440,  441,
   108138  /*   190 */   567,  491,  214,  279,  560,  600,   92,   57,   58,   48,
   108139  /*   200 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108140  /*   210 */   559,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108141  /*   220 */    51,  234,  310,  464,  233,  232,  558,  133,  519,   50,
   108142  /*   230 */    47,  147,  619,  618,  565,  436,  397,  515,  514,  518,
   108143  /*   240 */   410,  387,  438,  389,  437,  622,  621,  442,  570,  433,
   108144  /*   250 */   203,  390,  589,  583,    6,  413,  166,  670,  250,  381,
   108145  /*   260 */   378,  377,  525,  190,  600,   92,  594,  571,  571,  465,
   108146  /*   270 */   376,   57,   58,   48,  581,  580,  582,  582,   55,   55,
   108147  /*   280 */    56,   56,   56,   56,  599,   54,   54,   54,   54,   53,
   108148  /*   290 */    53,   52,   52,   52,   51,  234,  310,  592,  592,  592,
   108149  /*   300 */   490,  182,  247,  548,  249,  397,  273,  410,    7,  439,
   108150  /*   310 */   398,  606,   67,  619,  618,  620,  472,  256,  347,  255,
   108151  /*   320 */   473,  620,  413,  576,  620,   65,  589,  583,  236,  440,
   108152  /*   330 */   336,  600,   92,   68,  364,  192,  481,  622,  621,  547,
   108153  /*   340 */   622,  621,  560,  323,  207,   57,   58,   48,  581,  580,
   108154  /*   350 */   582,  582,   55,   55,   56,   56,   56,   56,  559,   54,
   108155  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108156  /*   370 */   310,  410,  397,  146,  558,  531,  401,  348,  599,  166,
   108157  /*   380 */   248,  204,  381,  378,  377,  541,  413,  171,  337,  570,
   108158  /*   390 */   622,  621,   40,  376,   38,  600,   74,  465,  548,  490,
   108159  /*   400 */   589,  583,  532,  350,  579,  619,  618,  297,  619,  618,
   108160  /*   410 */   480,   67,  470,   39,  620,  599,  406,  574,  573,   57,
   108161  /*   420 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108162  /*   430 */    56,   56,  577,   54,   54,   54,   54,   53,   53,   52,
   108163  /*   440 */    52,   52,   51,  234,  310,  256,  347,  255,  530,   52,
   108164  /*   450 */    52,   52,   51,  234,  345,  564,  236,  386,  619,  618,
   108165  /*   460 */   957,  185,  418,    2,  408,  410,  578,  578,  198,  197,
   108166  /*   470 */   196,  499,  183,  167,  589,  583,  671,  570,  505,  506,
   108167  /*   480 */   413,  267,  601,  672,  546,  208,  602,   36,  601,  600,
   108168  /*   490 */    91,  468,  602,   57,   58,   48,  581,  580,  582,  582,
   108169  /*   500 */    55,   55,   56,   56,   56,   56,  202,   54,   54,   54,
   108170  /*   510 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  599,
   108171  /*   520 */   157,  408,  527,  578,  578,  263,  490,  265,  410,  873,
   108172  /*   530 */   410,  474,  474,  366,  373,  410,  504,  428,   67,  290,
   108173  /*   540 */   599,  620,  352,  413,  408,  413,  578,  578,  589,  583,
   108174  /*   550 */   413,  382,  600,   92,  600,   16,  543,   62,  503,  600,
   108175  /*   560 */    92,  408,  346,  578,  578,  168,   45,   57,   58,   48,
   108176  /*   570 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108177  /*   580 */   200,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108178  /*   590 */    51,  234,  310,  393,  395,  534,  510,  617,  616,  615,
   108179  /*   600 */   318,  314,  172,   66,  596,  410,  338,  596,  324,  571,
   108180  /*   610 */   571,   50,   47,  147,  599,  629,  627,  330,  539,  315,
   108181  /*   620 */   413,   30,  589,  583,  272,  236,  199,  144,  176,  600,
   108182  /*   630 */    73,  420,  947,  620,  947,  420,  946,  351,  946,  175,
   108183  /*   640 */   596,   57,   58,   48,  581,  580,  582,  582,   55,   55,
   108184  /*   650 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
   108185  /*   660 */    53,   52,   52,   52,   51,  234,  310,  261,  410,  413,
   108186  /*   670 */   269,  208,  596,  363,  410,  596,  424,  360,  600,   69,
   108187  /*   680 */   424,  327,  620,  413,   50,   47,  147,  410,  358,  413,
   108188  /*   690 */   575,  553,  600,   94,  483,  509,  589,  583,  600,   97,
   108189  /*   700 */   552,  484,  413,  620,  188,  599,  551,  563,  596,  566,
   108190  /*   710 */   334,  600,   95,  205,  201,   57,   58,   48,  581,  580,
   108191  /*   720 */   582,  582,   55,   55,   56,   56,   56,   56,  352,   54,
   108192  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108193  /*   740 */   310,  410,  261,  410,  167,   22,  356,  599,  359,  623,
   108194  /*   750 */    50,   47,  147,  548,  357,  562,  413,  620,  413,  332,
   108195  /*   760 */   523,  270,  410,  167,  620,  600,  104,  600,  103,  603,
   108196  /*   770 */   589,  583,  339,  539,  304,  423,  222,  413,  174,  304,
   108197  /*   780 */   422,  561,  567,  405,  214,  260,  600,  106,  620,   57,
   108198  /*   790 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108199  /*   800 */    56,   56,  410,   54,   54,   54,   54,   53,   53,   52,
   108200  /*   810 */    52,   52,   51,  234,  310,  410,  557,  413,  410,  421,
   108201  /*   820 */   273,   35,  512,  146,  421,   12,  600,  107,  213,  144,
   108202  /*   830 */   413,  410,   32,  413,  410,  620,  365,  353,  358,  600,
   108203  /*   840 */   134,   11,  600,  135,  589,  583,  413,   21,  548,  413,
   108204  /*   850 */   316,  148,  620,  620,  170,  600,   98,  223,  600,  102,
   108205  /*   860 */   374,  168,  167,   57,   58,   48,  581,  580,  582,  582,
   108206  /*   870 */    55,   55,   56,   56,   56,   56,  410,   54,   54,   54,
   108207  /*   880 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  410,
   108208  /*   890 */   273,  413,  410,  273,  212,  469,  410,  167,  628,    2,
   108209  /*   900 */   600,  101,  545,  221,  413,  620,  130,  413,  620,  410,
   108210  /*   910 */   539,  413,  537,  600,   93,  315,  600,  100,  589,  583,
   108211  /*   920 */   600,   77,  425,  305,  413,  620,  254,  322,  599,  458,
   108212  /*   930 */   320,  171,  543,  600,   96,  521,  520,   57,   58,   48,
   108213  /*   940 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108214  /*   950 */   410,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108215  /*   960 */    51,  234,  310,  410,  273,  413,  410,  457,  358,   35,
   108216  /*   970 */   426,  230,  306,  319,  600,  138,  467,  520,  413,  620,
   108217  /*   980 */   143,  413,  410,  620,  410,  353,  529,  600,  137,  142,
   108218  /*   990 */   600,  136,  589,  583,  604,  261,  528,  413,  229,  413,
   108219  /*  1000 */   620,  321,  495,   28,  543,  543,  600,   76,  600,   90,
   108220  /*  1010 */   620,   57,   46,   48,  581,  580,  582,  582,   55,   55,
   108221  /*  1020 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
   108222  /*  1030 */    53,   52,   52,   52,   51,  234,  310,  261,  451,  413,
   108223  /*  1040 */   410,  211,  611,  285,  283,  610,  609,  502,  600,   89,
   108224  /*  1050 */   380,  217,  620,  128,  140,  413,  220,  620,  410,  409,
   108225  /*  1060 */   620,  620,  588,  587,  600,   75,  589,  583,  271,  620,
   108226  /*  1070 */    51,  234,  127,  413,  620,  599,  627,  330,   27,  375,
   108227  /*  1080 */   449,  279,  600,   88,  585,  584,   58,   48,  581,  580,
   108228  /*  1090 */   582,  582,   55,   55,   56,   56,   56,   56,  410,   54,
   108229  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108230  /*  1110 */   310,  586,  410,  413,  410,  261,  593,  165,  399,  556,
   108231  /*  1120 */   126,  371,  600,   87,  478,  186,  123,  413,  367,  413,
   108232  /*  1130 */   620,  620,  410,  620,  620,  410,  600,   99,  600,   86,
   108233  /*  1140 */   589,  583,  475,  122,  258,  171,  471,  413,  160,  121,
   108234  /*  1150 */   413,   14,  159,  463,   25,   24,  600,   17,  448,  600,
   108235  /*  1160 */    85,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108236  /*  1170 */    56,   56,  158,   54,   54,   54,   54,   53,   53,   52,
   108237  /*  1180 */    52,   52,   51,  234,   44,  404,  261,    3,  544,  261,
   108238  /*  1190 */   540,  414,  621,  460,  119,  118,  538,  275,   10,  349,
   108239  /*  1200 */     4,  620,  407,  620,  620,  620,  116,   44,  404,  410,
   108240  /*  1210 */     3,  620,  620,  410,  414,  621,  456,  454,  252,  450,
   108241  /*  1220 */   508,  402,  111,  109,  413,  407,  155,  444,  413,  447,
   108242  /*  1230 */   435,  565,  219,  600,   84,  620,  108,  600,   83,   64,
   108243  /*  1240 */   434,  417,  625,  150,  402,  333,  410,  237,  238,  124,
   108244  /*  1250 */   274,   41,   42,  533,  565,  206,  189,  261,   43,  412,
   108245  /*  1260 */   411,  413,  261,  594,  488,  620,  329,  149,  419,  268,
   108246  /*  1270 */   600,   72,  620,  266,   41,   42,  181,  620,  410,  620,
   108247  /*  1280 */   105,   43,  412,  411,  620,  624,  594,  614,  620,  599,
   108248  /*  1290 */   228,  125,  313,  413,  592,  592,  592,  591,  590,   13,
   108249  /*  1300 */   218,  410,  600,   71,  236,  244,   44,  404,  264,    3,
   108250  /*  1310 */   312,  613,  340,  414,  621,  180,  413,  592,  592,  592,
   108251  /*  1320 */   591,  590,   13,  620,  407,  600,   82,  410,  416,   34,
   108252  /*  1330 */   404,  410,    3,  410,  262,  410,  414,  621,  612,  331,
   108253  /*  1340 */   178,  415,  413,  402,    8,  236,  413,  407,  413,  620,
   108254  /*  1350 */   413,  600,   81,  565,  257,  600,   80,  600,   70,  600,
   108255  /*  1360 */    18,  598,  361,  462,  461,   30,  402,  294,   31,  620,
   108256  /*  1370 */   293,  354,  251,   41,   42,  410,  565,  620,  620,  620,
   108257  /*  1380 */    43,  412,  411,  453,  396,  594,  620,  620,  394,   61,
   108258  /*  1390 */   413,  292,  443,  622,  621,  243,   41,   42,  620,  600,
   108259  /*  1400 */    79,  597,  291,   43,  412,  411,   60,  620,  594,  240,
   108260  /*  1410 */   620,  410,  231,   37,  555,  173,  592,  592,  592,  591,
   108261  /*  1420 */   590,   13,  216,  239,  620,  184,  413,  302,  301,  300,
   108262  /*  1430 */   179,  298,  388,  565,  452,  600,   78,  286,  620,  592,
   108263  /*  1440 */   592,  592,  591,  590,   13,  429,   29,  413,  151,  289,
   108264  /*  1450 */   242,  145,  392,  194,  193,  288,  600,    9,  542,  241,
   108265  /*  1460 */   620,  525,  391,  284,  620,  594,  620,  620,  522,  536,
   108266  /*  1470 */   620,  535,  153,  385,  465,  516,  282,  325,  154,  517,
   108267  /*  1480 */   277,  152,  512,  511,  513,  129,  226,  308,  487,  486,
   108268  /*  1490 */   485,  164,  372,  493,  307,  227,  592,  592,  592,  225,
   108269  /*  1500 */   479,  163,  368,  370,  162,  476,  210,  477,   26,  259,
   108270  /*  1510 */   161,  466,  362,  141,  132,  120,  117,  455,  156,  115,
   108271  /*  1520 */   344,  343,  256,  342,  245,  114,  113,  446,  311,  112,
   108272  /*  1530 */    23,  317,  432,  236,  131,  431,  110,  430,   20,  427,
   108273  /*  1540 */   608,  595,  295,   63,  379,  287,  509,  191,  278,  403,
   108274  /*  1550 */   572,  569,  497,  498,  496,  494,  335,  459,  445,  303,
   108275  /*  1560 */   296,  246,  341,  355,    5,  568,  369,  507,  253,  549,
   108276  /*  1570 */   526,  209,  400,  501,  500,  524,  234,  958,  489,  482,
   108277 };
   108278 static const YYCODETYPE yy_lookahead[] = {
   108279  /*     0 */    19,  169,  170,  171,   22,   24,   24,   26,   77,   78,
   108280  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
   108281  /*    20 */    89,   90,   91,   92,   26,   27,    1,   26,   27,   15,
   108282  /*    30 */    49,   50,   77,   78,   79,   80,  116,   82,   83,   84,
   108283  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,  128,   68,
   108284  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108285  /*    60 */    79,   80,  230,   82,   83,   84,   85,   86,   87,   88,
   108286  /*    70 */    89,   90,   91,   92,   19,   94,   19,   23,   86,   87,
   108287  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108288  /*    90 */    91,   92,   94,   95,   19,   94,   95,   96,  172,  173,
   108289  /*   100 */    99,  100,  101,  197,   49,   50,  177,  181,   22,   54,
   108290  /*   110 */   204,  110,   26,   27,   86,   87,   88,   89,   90,   91,
   108291  /*   120 */    92,  129,  130,   68,   69,   70,   71,   72,   73,   74,
   108292  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
   108293  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
   108294  /*   150 */   221,  222,  223,   96,   97,   98,   99,  100,  101,  102,
   108295  /*   160 */   112,   32,  114,  115,   26,   27,  109,   92,  150,   25,
   108296  /*   170 */    41,  150,   97,   98,   99,  100,  101,  102,   49,   50,
   108297  /*   180 */    94,   95,   98,  165,  109,   25,  165,  163,  170,  171,
   108298  /*   190 */   166,  167,  168,  109,   12,  174,  175,   68,   69,   70,
   108299  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108300  /*   210 */    28,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108301  /*   220 */    91,   92,   19,   11,   86,   87,   44,   24,   46,  221,
   108302  /*   230 */   222,  223,   94,   95,   66,   97,  215,    7,    8,   57,
   108303  /*   240 */   150,  220,  104,   19,  106,   26,   27,  229,  230,  241,
   108304  /*   250 */   160,   27,   49,   50,   22,  165,   96,  118,   16,   99,
   108305  /*   260 */   100,  101,   94,  119,  174,  175,   98,  129,  130,   57,
   108306  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108307  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
   108308  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
   108309  /*   300 */   150,   23,   60,   25,   62,  215,  150,  150,   76,  150,
   108310  /*   310 */   220,  161,  162,   94,   95,  165,   30,  105,  106,  107,
   108311  /*   320 */    34,  165,  165,   23,  165,   25,   49,   50,  116,  170,
   108312  /*   330 */   171,  174,  175,   22,   48,  185,  186,   26,   27,  120,
   108313  /*   340 */    26,   27,   12,  187,  160,   68,   69,   70,   71,   72,
   108314  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   28,   82,
   108315  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108316  /*   370 */    19,  150,  215,   95,   44,   23,   46,  220,  194,   96,
   108317  /*   380 */   138,  160,   99,  100,  101,   23,  165,   25,  229,  230,
   108318  /*   390 */    26,   27,  135,  110,  137,  174,  175,   57,  120,  150,
   108319  /*   400 */    49,   50,   88,  219,  113,   94,   95,  158,   94,   95,
   108320  /*   410 */   161,  162,   21,  136,  165,  194,  169,  170,  171,   68,
   108321  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108322  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
   108323  /*   440 */    89,   90,   91,   92,   19,  105,  106,  107,   23,   88,
   108324  /*   450 */    89,   90,   91,   92,   63,   23,  116,   88,   94,   95,
   108325  /*   460 */   142,  143,  144,  145,  112,  150,  114,  115,  105,  106,
   108326  /*   470 */   107,   23,   23,   25,   49,   50,  118,  230,   97,   98,
   108327  /*   480 */   165,   16,  113,  118,  120,  160,  117,  136,  113,  174,
   108328  /*   490 */   175,  100,  117,   68,   69,   70,   71,   72,   73,   74,
   108329  /*   500 */    75,   76,   77,   78,   79,   80,  160,   82,   83,   84,
   108330  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
   108331  /*   520 */    25,  112,   23,  114,  115,   60,  150,   62,  150,  138,
   108332  /*   530 */   150,  105,  106,  107,   19,  150,   36,  161,  162,  224,
   108333  /*   540 */   194,  165,  217,  165,  112,  165,  114,  115,   49,   50,
   108334  /*   550 */   165,   51,  174,  175,  174,  175,  166,  232,   58,  174,
   108335  /*   560 */   175,  112,  237,  114,  115,   50,   22,   68,   69,   70,
   108336  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108337  /*   580 */   160,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108338  /*   590 */    91,   92,   19,  215,  214,  205,   23,    7,    8,    9,
   108339  /*   600 */   215,  155,   24,   22,   26,  150,   97,   26,  108,  129,
   108340  /*   610 */   130,  221,  222,  223,  194,    0,    1,    2,  150,  104,
   108341  /*   620 */   165,  126,   49,   50,  109,  116,  206,  207,  118,  174,
   108342  /*   630 */   175,   22,   23,  165,   25,   22,   23,  128,   25,  118,
   108343  /*   640 */    26,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108344  /*   650 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   108345  /*   660 */    87,   88,   89,   90,   91,   92,   19,  150,  150,  165,
   108346  /*   670 */    23,  160,   94,  227,  150,   94,   67,  231,  174,  175,
   108347  /*   680 */    67,  213,  165,  165,  221,  222,  223,  150,  150,  165,
   108348  /*   690 */    23,   32,  174,  175,  181,  182,   49,   50,  174,  175,
   108349  /*   700 */    41,  188,  165,  165,   22,  194,  177,   11,   94,   23,
   108350  /*   710 */   193,  174,  175,  160,   22,   68,   69,   70,   71,   72,
   108351  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  217,   82,
   108352  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108353  /*   740 */    19,  150,  150,  150,   25,   24,   19,  194,  237,  150,
   108354  /*   750 */   221,  222,  223,   25,   27,   23,  165,  165,  165,  242,
   108355  /*   760 */   165,   23,  150,   25,  165,  174,  175,  174,  175,  174,
   108356  /*   770 */    49,   50,  219,  150,   22,   23,  238,  165,   25,   22,
   108357  /*   780 */    23,   23,  166,  167,  168,  193,  174,  175,  165,   68,
   108358  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108359  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
   108360  /*   810 */    89,   90,   91,   92,   19,  150,   23,  165,  150,   67,
   108361  /*   820 */   150,   25,  103,   95,   67,   35,  174,  175,  206,  207,
   108362  /*   830 */   165,  150,   25,  165,  150,  165,  213,  150,  150,  174,
   108363  /*   840 */   175,   35,  174,  175,   49,   50,  165,   52,  120,  165,
   108364  /*   850 */   245,  246,  165,  165,   35,  174,  175,  187,  174,  175,
   108365  /*   860 */    23,   50,   25,   68,   69,   70,   71,   72,   73,   74,
   108366  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
   108367  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
   108368  /*   890 */   150,  165,  150,  150,  160,   23,  150,   25,  144,  145,
   108369  /*   900 */   174,  175,  120,  216,  165,  165,   22,  165,  165,  150,
   108370  /*   910 */   150,  165,   27,  174,  175,  104,  174,  175,   49,   50,
   108371  /*   920 */   174,  175,  247,  248,  165,  165,  238,  187,  194,   23,
   108372  /*   930 */   187,   25,  166,  174,  175,  190,  191,   68,   69,   70,
   108373  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108374  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108375  /*   960 */    91,   92,   19,  150,  150,  165,  150,   23,  150,   25,
   108376  /*   970 */    23,  205,   25,  213,  174,  175,  190,  191,  165,  165,
   108377  /*   980 */   118,  165,  150,  165,  150,  150,   23,  174,  175,   39,
   108378  /*   990 */   174,  175,   49,   50,  173,  150,   23,  165,   52,  165,
   108379  /*  1000 */   165,  187,  181,   22,  166,  166,  174,  175,  174,  175,
   108380  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108381  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   108382  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
   108383  /*  1040 */   150,  160,  150,  205,  205,  150,  150,   29,  174,  175,
   108384  /*  1050 */    52,  216,  165,   22,  150,  165,  238,  165,  150,  150,
   108385  /*  1060 */   165,  165,   49,   50,  174,  175,   49,   50,   23,  165,
   108386  /*  1070 */    91,   92,   22,  165,  165,  194,    1,    2,   22,   52,
   108387  /*  1080 */   193,  109,  174,  175,   71,   72,   69,   70,   71,   72,
   108388  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
   108389  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108390  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  102,  150,  150,
   108391  /*  1120 */    22,   19,  174,  175,   20,   24,  104,  165,   43,  165,
   108392  /*  1130 */   165,  165,  150,  165,  165,  150,  174,  175,  174,  175,
   108393  /*  1140 */    49,   50,   59,   53,  138,   25,   53,  165,  104,   22,
   108394  /*  1150 */   165,    5,  118,    1,   76,   76,  174,  175,  193,  174,
   108395  /*  1160 */   175,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108396  /*  1170 */    79,   80,   35,   82,   83,   84,   85,   86,   87,   88,
   108397  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,  150,
   108398  /*  1190 */   150,   26,   27,   27,  108,  127,  150,  150,   22,   25,
   108399  /*  1200 */    22,  165,   37,  165,  165,  165,  119,   19,   20,  150,
   108400  /*  1210 */    22,  165,  165,  150,   26,   27,   23,    1,   16,   20,
   108401  /*  1220 */   150,   56,  119,  108,  165,   37,  121,  128,  165,  193,
   108402  /*  1230 */    23,   66,  193,  174,  175,  165,  127,  174,  175,   16,
   108403  /*  1240 */    23,  146,  147,   15,   56,   65,  150,  152,  140,  154,
   108404  /*  1250 */   150,   86,   87,   88,   66,  160,   22,  150,   93,   94,
   108405  /*  1260 */    95,  165,  150,   98,  150,  165,    3,  246,    4,  150,
   108406  /*  1270 */   174,  175,  165,  150,   86,   87,    6,  165,  150,  165,
   108407  /*  1280 */   164,   93,   94,   95,  165,  149,   98,  149,  165,  194,
   108408  /*  1290 */   180,  180,  249,  165,  129,  130,  131,  132,  133,  134,
   108409  /*  1300 */   193,  150,  174,  175,  116,  193,   19,   20,  150,   22,
   108410  /*  1310 */   249,  149,  217,   26,   27,  151,  165,  129,  130,  131,
   108411  /*  1320 */   132,  133,  134,  165,   37,  174,  175,  150,  149,   19,
   108412  /*  1330 */    20,  150,   22,  150,  150,  150,   26,   27,   13,  244,
   108413  /*  1340 */   151,  159,  165,   56,   25,  116,  165,   37,  165,  165,
   108414  /*  1350 */   165,  174,  175,   66,  150,  174,  175,  174,  175,  174,
   108415  /*  1360 */   175,  194,  150,  150,  150,  126,   56,  199,  124,  165,
   108416  /*  1370 */   200,  150,  150,   86,   87,  150,   66,  165,  165,  165,
   108417  /*  1380 */    93,   94,   95,  150,  122,   98,  165,  165,  123,   22,
   108418  /*  1390 */   165,  201,  150,   26,   27,  150,   86,   87,  165,  174,
   108419  /*  1400 */   175,  203,  202,   93,   94,   95,  125,  165,   98,  150,
   108420  /*  1410 */   165,  150,  225,  135,  157,  118,  129,  130,  131,  132,
   108421  /*  1420 */   133,  134,    5,  150,  165,  157,  165,   10,   11,   12,
   108422  /*  1430 */    13,   14,  150,   66,   17,  174,  175,  210,  165,  129,
   108423  /*  1440 */   130,  131,  132,  133,  134,  150,  104,  165,   31,  150,
   108424  /*  1450 */    33,  150,  150,   86,   87,  150,  174,  175,  211,   42,
   108425  /*  1460 */   165,   94,  121,  210,  165,   98,  165,  165,  176,  211,
   108426  /*  1470 */   165,  211,   55,  104,   57,  184,  210,   47,   61,  176,
   108427  /*  1480 */   176,   64,  103,  176,  178,   22,   92,  179,  176,  176,
   108428  /*  1490 */   176,  156,   18,  184,  179,  228,  129,  130,  131,  228,
   108429  /*  1500 */   157,  156,   45,  157,  156,  236,  157,  157,  135,  235,
   108430  /*  1510 */   156,  189,  157,   68,  218,  189,   22,  199,  156,  192,
   108431  /*  1520 */   157,   18,  105,  106,  107,  192,  192,  199,  111,  192,
   108432  /*  1530 */   240,  157,   40,  116,  218,  157,  189,  157,  240,   38,
   108433  /*  1540 */   153,  166,  198,  243,  178,  209,  182,  196,  177,  226,
   108434  /*  1550 */   230,  230,  166,  177,  177,  166,  139,  199,  199,  148,
   108435  /*  1560 */   195,  209,  209,  239,  196,  166,  234,  183,  239,  208,
   108436  /*  1570 */   174,  233,  191,  183,  183,  174,   92,  250,  186,  186,
   108437 };
   108438 #define YY_SHIFT_USE_DFLT (-81)
   108439 #define YY_SHIFT_COUNT (417)
   108440 #define YY_SHIFT_MIN   (-80)
   108441 #define YY_SHIFT_MAX   (1503)
   108442 static const short yy_shift_ofst[] = {
   108443  /*     0 */  1075, 1188, 1417, 1188, 1287, 1287,  138,  138,    1,  -19,
   108444  /*    10 */  1287, 1287, 1287, 1287,  340,   -2,  129,  129,  795, 1165,
   108445  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108446  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108447  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
   108448  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108449  /*    60 */  1287, 1287,  212,   -2,   -2,   -8,   -8,  614, 1229,   55,
   108450  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
   108451  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
   108452  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
   108453  /*   100 */   -45,  -45,  -45,  -45,   -1,   57,   28,  361,   -2,   -2,
   108454  /*   110 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108455  /*   120 */    -2,   -2,   -2,   -2,  391,  515,   -2,   -2,   -2,   -2,
   108456  /*   130 */    -2,  509,  -80,  614,  979, 1484,  -81,  -81,  -81, 1367,
   108457  /*   140 */    75,  182,  182,  314,  311,  364,  219,   86,  613,  609,
   108458  /*   150 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108459  /*   160 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108460  /*   170 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108461  /*   180 */    -2,   -2,  578,  578,  578,  615, 1229, 1229, 1229,  -81,
   108462  /*   190 */   -81,  -81,  160,  168,  168,  283,  500,  500,  500,  278,
   108463  /*   200 */   449,  330,  432,  409,  352,   48,   48,   48,   48,  426,
   108464  /*   210 */   286,   48,   48,  728,  581,  369,  590,  495,  224,  224,
   108465  /*   220 */   727,  495,  727,  719,  614,  659,  614,  659,  811,  659,
   108466  /*   230 */   224,  257,  480,  480,  614,  144,  375,  -18, 1501, 1297,
   108467  /*   240 */  1297, 1492, 1492, 1297, 1494, 1445, 1239, 1503, 1503, 1503,
   108468  /*   250 */  1503, 1297, 1474, 1239, 1494, 1445, 1445, 1297, 1474, 1373,
   108469  /*   260 */  1457, 1297, 1297, 1474, 1297, 1474, 1297, 1474, 1463, 1369,
   108470  /*   270 */  1369, 1369, 1430, 1394, 1394, 1463, 1369, 1379, 1369, 1430,
   108471  /*   280 */  1369, 1369, 1341, 1342, 1341, 1342, 1341, 1342, 1297, 1297,
   108472  /*   290 */  1278, 1281, 1262, 1244, 1265, 1239, 1229, 1319, 1325, 1325,
   108473  /*   300 */  1270, 1270, 1270, 1270,  -81,  -81,  -81,  -81,  -81,  -81,
   108474  /*   310 */  1013,  242,  757,  752,  465,  363,  947,  232,  944,  906,
   108475  /*   320 */   872,  837,  738,  448,  381,  230,   84,  362,  300, 1264,
   108476  /*   330 */  1263, 1234, 1108, 1228, 1180, 1223, 1217, 1207, 1099, 1174,
   108477  /*   340 */  1109, 1115, 1103, 1199, 1105, 1202, 1216, 1087, 1193, 1178,
   108478  /*   350 */  1174, 1176, 1068, 1079, 1078, 1086, 1166, 1137, 1034, 1152,
   108479  /*   360 */  1146, 1127, 1044, 1006, 1093, 1120, 1090, 1083, 1085, 1022,
   108480  /*   370 */  1101, 1104, 1102,  972, 1015, 1098, 1027, 1056, 1050, 1045,
   108481  /*   380 */  1031,  998, 1018,  981,  946,  950,  973,  963,  862,  885,
   108482  /*   390 */   819,  884,  782,  796,  806,  807,  790,  796,  793,  758,
   108483  /*   400 */   753,  732,  692,  696,  682,  686,  667,  544,  291,  521,
   108484  /*   410 */   510,  365,  358,  139,  114,   54,   14,   25,
   108485 };
   108486 #define YY_REDUCE_USE_DFLT (-169)
   108487 #define YY_REDUCE_COUNT (309)
   108488 #define YY_REDUCE_MIN   (-168)
   108489 #define YY_REDUCE_MAX   (1411)
   108490 static const short yy_reduce_ofst[] = {
   108491  /*     0 */   318,   90, 1095,  221,  157,   21,  159,   18,  150,  390,
   108492  /*    10 */   385,  378,  380,  315,  325,  249,  529,  -71,    8, 1282,
   108493  /*    20 */  1261, 1225, 1185, 1183, 1181, 1177, 1151, 1128, 1096, 1063,
   108494  /*    30 */  1059,  985,  982,  964,  962,  948,  908,  890,  874,  834,
   108495  /*    40 */   832,  816,  813,  800,  759,  746,  742,  739,  726,  684,
   108496  /*    50 */   681,  668,  665,  652,  612,  593,  591,  537,  524,  518,
   108497  /*    60 */   504,  455,  511,  376,  517,  247, -168,   24,  420,  463,
   108498  /*    70 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108499  /*    80 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108500  /*    90 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108501  /*   100 */   463,  463,  463,  463,  463,  -74,  463,  463, 1112,  835,
   108502  /*   110 */  1107, 1039, 1036,  965,  887,  845,  818,  760,  688,  687,
   108503  /*   120 */   538,  743,  623,  592,  446,  513,  814,  740,  670,  156,
   108504  /*   130 */   468,  553,  184,  616,  463,  463,  463,  463,  463,  595,
   108505  /*   140 */   821,  786,  745,  909, 1305, 1302, 1301, 1299,  675,  675,
   108506  /*   150 */  1295, 1273, 1259, 1245, 1242, 1233, 1222, 1221, 1214, 1213,
   108507  /*   160 */  1212, 1204, 1184, 1158, 1123, 1119, 1114, 1100, 1070, 1047,
   108508  /*   170 */  1046, 1040, 1038,  969,  968,  966,  909,  904,  896,  895,
   108509  /*   180 */   892,  599,  839,  838,  766,  754,  881,  734,  346,  605,
   108510  /*   190 */   622,  -94, 1393, 1401, 1396, 1392, 1391, 1390, 1384, 1361,
   108511  /*   200 */  1365, 1381, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1332,
   108512  /*   210 */  1338, 1365, 1365, 1361, 1399, 1368, 1411, 1359, 1353, 1352,
   108513  /*   220 */  1329, 1358, 1324, 1366, 1389, 1377, 1386, 1376, 1364, 1371,
   108514  /*   230 */  1336, 1323, 1321, 1320, 1375, 1344, 1351, 1387, 1300, 1380,
   108515  /*   240 */  1378, 1298, 1290, 1374, 1316, 1347, 1328, 1337, 1334, 1333,
   108516  /*   250 */  1327, 1363, 1362, 1318, 1296, 1326, 1322, 1355, 1354, 1269,
   108517  /*   260 */  1274, 1350, 1349, 1348, 1346, 1345, 1343, 1335, 1315, 1314,
   108518  /*   270 */  1313, 1312, 1309, 1271, 1267, 1308, 1307, 1306, 1304, 1291,
   108519  /*   280 */  1303, 1292, 1260, 1266, 1258, 1253, 1247, 1227, 1268, 1257,
   108520  /*   290 */  1187, 1198, 1200, 1190, 1170, 1168, 1167, 1182, 1189, 1164,
   108521  /*   300 */  1179, 1162, 1138, 1136, 1061, 1043, 1021, 1111, 1110, 1116,
   108522 };
   108523 static const YYACTIONTYPE yy_default[] = {
   108524  /*     0 */   634,  868,  956,  956,  868,  868,  956,  956,  956,  758,
   108525  /*    10 */   956,  956,  956,  866,  956,  956,  786,  786,  930,  956,
   108526  /*    20 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108527  /*    30 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108528  /*    40 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108529  /*    50 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108530  /*    60 */   956,  956,  956,  956,  956,  956,  956,  673,  762,  792,
   108531  /*    70 */   956,  956,  956,  956,  956,  956,  956,  956,  929,  931,
   108532  /*    80 */   800,  799,  909,  773,  797,  790,  794,  869,  862,  863,
   108533  /*    90 */   861,  865,  870,  956,  793,  829,  846,  828,  840,  845,
   108534  /*   100 */   852,  844,  841,  831,  830,  665,  832,  833,  956,  956,
   108535  /*   110 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108536  /*   120 */   956,  956,  956,  956,  660,  727,  956,  956,  956,  956,
   108537  /*   130 */   956,  956,  956,  956,  834,  835,  849,  848,  847,  956,
   108538  /*   140 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108539  /*   150 */   956,  936,  934,  956,  881,  956,  956,  956,  956,  956,
   108540  /*   160 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108541  /*   170 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108542  /*   180 */   956,  640,  758,  758,  758,  634,  956,  956,  956,  948,
   108543  /*   190 */   762,  752,  718,  956,  956,  956,  956,  956,  956,  956,
   108544  /*   200 */   956,  956,  956,  956,  956,  802,  741,  919,  921,  956,
   108545  /*   210 */   902,  739,  662,  760,  675,  750,  642,  796,  775,  775,
   108546  /*   220 */   914,  796,  914,  699,  956,  786,  956,  786,  696,  786,
   108547  /*   230 */   775,  864,  956,  956,  956,  759,  750,  956,  941,  766,
   108548  /*   240 */   766,  933,  933,  766,  808,  731,  796,  738,  738,  738,
   108549  /*   250 */   738,  766,  657,  796,  808,  731,  731,  766,  657,  908,
   108550  /*   260 */   906,  766,  766,  657,  766,  657,  766,  657,  874,  729,
   108551  /*   270 */   729,  729,  714,  878,  878,  874,  729,  699,  729,  714,
   108552  /*   280 */   729,  729,  779,  774,  779,  774,  779,  774,  766,  766,
   108553  /*   290 */   956,  791,  780,  789,  787,  796,  956,  717,  650,  650,
   108554  /*   300 */   639,  639,  639,  639,  953,  953,  948,  701,  701,  683,
   108555  /*   310 */   956,  956,  956,  956,  956,  956,  956,  883,  956,  956,
   108556  /*   320 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108557  /*   330 */   635,  943,  956,  956,  940,  956,  956,  956,  956,  801,
   108558  /*   340 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108559  /*   350 */   918,  956,  956,  956,  956,  956,  956,  956,  912,  956,
   108560  /*   360 */   956,  956,  956,  956,  956,  905,  904,  956,  956,  956,
   108561  /*   370 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108562  /*   380 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108563  /*   390 */   956,  956,  956,  788,  956,  781,  956,  867,  956,  956,
   108564  /*   400 */   956,  956,  956,  956,  956,  956,  956,  956,  744,  817,
   108565  /*   410 */   956,  816,  820,  815,  667,  956,  648,  956,  631,  636,
   108566  /*   420 */   952,  955,  954,  951,  950,  949,  944,  942,  939,  938,
   108567  /*   430 */   937,  935,  932,  928,  887,  885,  892,  891,  890,  889,
   108568  /*   440 */   888,  886,  884,  882,  803,  798,  795,  927,  880,  740,
   108569  /*   450 */   737,  736,  656,  945,  911,  920,  807,  806,  809,  917,
   108570  /*   460 */   916,  915,  913,  910,  897,  805,  804,  732,  872,  871,
   108571  /*   470 */   659,  901,  900,  899,  903,  907,  898,  768,  658,  655,
   108572  /*   480 */   664,  721,  720,  728,  726,  725,  724,  723,  722,  719,
   108573  /*   490 */   666,  674,  685,  713,  698,  697,  877,  879,  876,  875,
   108574  /*   500 */   706,  705,  711,  710,  709,  708,  707,  704,  703,  702,
   108575  /*   510 */   695,  694,  700,  693,  716,  715,  712,  692,  735,  734,
   108576  /*   520 */   733,  730,  691,  690,  689,  820,  688,  687,  826,  825,
   108577  /*   530 */   813,  856,  755,  754,  753,  765,  764,  777,  776,  811,
   108578  /*   540 */   810,  778,  763,  757,  756,  772,  771,  770,  769,  761,
   108579  /*   550 */   751,  783,  785,  784,  782,  858,  767,  855,  926,  925,
   108580  /*   560 */   924,  923,  922,  860,  859,  827,  824,  678,  679,  895,
   108581  /*   570 */   894,  896,  893,  681,  680,  677,  676,  857,  746,  745,
   108582  /*   580 */   853,  850,  842,  838,  854,  851,  843,  839,  837,  836,
   108583  /*   590 */   822,  821,  819,  818,  814,  823,  669,  747,  743,  742,
   108584  /*   600 */   812,  749,  748,  686,  684,  682,  663,  661,  654,  652,
   108585  /*   610 */   651,  653,  649,  647,  646,  645,  644,  643,  672,  671,
   108586  /*   620 */   670,  668,  667,  641,  638,  637,  633,  632,  630,
   108587 };
   108588 
   108589 /* The next table maps tokens into fallback tokens.  If a construct
   108590 ** like the following:
   108591 **
   108592 **      %fallback ID X Y Z.
   108593 **
   108594 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   108595 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   108596 ** but it does not parse, the type of the token is changed to ID and
   108597 ** the parse is retried before an error is thrown.
   108598 */
   108599 #ifdef YYFALLBACK
   108600 static const YYCODETYPE yyFallback[] = {
   108601     0,  /*          $ => nothing */
   108602     0,  /*       SEMI => nothing */
   108603    26,  /*    EXPLAIN => ID */
   108604    26,  /*      QUERY => ID */
   108605    26,  /*       PLAN => ID */
   108606    26,  /*      BEGIN => ID */
   108607     0,  /* TRANSACTION => nothing */
   108608    26,  /*   DEFERRED => ID */
   108609    26,  /*  IMMEDIATE => ID */
   108610    26,  /*  EXCLUSIVE => ID */
   108611     0,  /*     COMMIT => nothing */
   108612    26,  /*        END => ID */
   108613    26,  /*   ROLLBACK => ID */
   108614    26,  /*  SAVEPOINT => ID */
   108615    26,  /*    RELEASE => ID */
   108616     0,  /*         TO => nothing */
   108617     0,  /*      TABLE => nothing */
   108618     0,  /*     CREATE => nothing */
   108619    26,  /*         IF => ID */
   108620     0,  /*        NOT => nothing */
   108621     0,  /*     EXISTS => nothing */
   108622    26,  /*       TEMP => ID */
   108623     0,  /*         LP => nothing */
   108624     0,  /*         RP => nothing */
   108625     0,  /*         AS => nothing */
   108626     0,  /*      COMMA => nothing */
   108627     0,  /*         ID => nothing */
   108628     0,  /*    INDEXED => nothing */
   108629    26,  /*      ABORT => ID */
   108630    26,  /*     ACTION => ID */
   108631    26,  /*      AFTER => ID */
   108632    26,  /*    ANALYZE => ID */
   108633    26,  /*        ASC => ID */
   108634    26,  /*     ATTACH => ID */
   108635    26,  /*     BEFORE => ID */
   108636    26,  /*         BY => ID */
   108637    26,  /*    CASCADE => ID */
   108638    26,  /*       CAST => ID */
   108639    26,  /*   COLUMNKW => ID */
   108640    26,  /*   CONFLICT => ID */
   108641    26,  /*   DATABASE => ID */
   108642    26,  /*       DESC => ID */
   108643    26,  /*     DETACH => ID */
   108644    26,  /*       EACH => ID */
   108645    26,  /*       FAIL => ID */
   108646    26,  /*        FOR => ID */
   108647    26,  /*     IGNORE => ID */
   108648    26,  /*  INITIALLY => ID */
   108649    26,  /*    INSTEAD => ID */
   108650    26,  /*    LIKE_KW => ID */
   108651    26,  /*      MATCH => ID */
   108652    26,  /*         NO => ID */
   108653    26,  /*        KEY => ID */
   108654    26,  /*         OF => ID */
   108655    26,  /*     OFFSET => ID */
   108656    26,  /*     PRAGMA => ID */
   108657    26,  /*      RAISE => ID */
   108658    26,  /*    REPLACE => ID */
   108659    26,  /*   RESTRICT => ID */
   108660    26,  /*        ROW => ID */
   108661    26,  /*    TRIGGER => ID */
   108662    26,  /*     VACUUM => ID */
   108663    26,  /*       VIEW => ID */
   108664    26,  /*    VIRTUAL => ID */
   108665    26,  /*    REINDEX => ID */
   108666    26,  /*     RENAME => ID */
   108667    26,  /*   CTIME_KW => ID */
   108668 };
   108669 #endif /* YYFALLBACK */
   108670 
   108671 /* The following structure represents a single element of the
   108672 ** parser's stack.  Information stored includes:
   108673 **
   108674 **   +  The state number for the parser at this level of the stack.
   108675 **
   108676 **   +  The value of the token stored at this level of the stack.
   108677 **      (In other words, the "major" token.)
   108678 **
   108679 **   +  The semantic value stored at this level of the stack.  This is
   108680 **      the information used by the action routines in the grammar.
   108681 **      It is sometimes called the "minor" token.
   108682 */
   108683 struct yyStackEntry {
   108684   YYACTIONTYPE stateno;  /* The state-number */
   108685   YYCODETYPE major;      /* The major token value.  This is the code
   108686                          ** number for the token at this stack level */
   108687   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   108688                          ** is the value of the token  */
   108689 };
   108690 typedef struct yyStackEntry yyStackEntry;
   108691 
   108692 /* The state of the parser is completely contained in an instance of
   108693 ** the following structure */
   108694 struct yyParser {
   108695   int yyidx;                    /* Index of top element in stack */
   108696 #ifdef YYTRACKMAXSTACKDEPTH
   108697   int yyidxMax;                 /* Maximum value of yyidx */
   108698 #endif
   108699   int yyerrcnt;                 /* Shifts left before out of the error */
   108700   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   108701 #if YYSTACKDEPTH<=0
   108702   int yystksz;                  /* Current side of the stack */
   108703   yyStackEntry *yystack;        /* The parser's stack */
   108704 #else
   108705   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   108706 #endif
   108707 };
   108708 typedef struct yyParser yyParser;
   108709 
   108710 #ifndef NDEBUG
   108711 /* #include <stdio.h> */
   108712 static FILE *yyTraceFILE = 0;
   108713 static char *yyTracePrompt = 0;
   108714 #endif /* NDEBUG */
   108715 
   108716 #ifndef NDEBUG
   108717 /*
   108718 ** Turn parser tracing on by giving a stream to which to write the trace
   108719 ** and a prompt to preface each trace message.  Tracing is turned off
   108720 ** by making either argument NULL
   108721 **
   108722 ** Inputs:
   108723 ** <ul>
   108724 ** <li> A FILE* to which trace output should be written.
   108725 **      If NULL, then tracing is turned off.
   108726 ** <li> A prefix string written at the beginning of every
   108727 **      line of trace output.  If NULL, then tracing is
   108728 **      turned off.
   108729 ** </ul>
   108730 **
   108731 ** Outputs:
   108732 ** None.
   108733 */
   108734 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   108735   yyTraceFILE = TraceFILE;
   108736   yyTracePrompt = zTracePrompt;
   108737   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   108738   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   108739 }
   108740 #endif /* NDEBUG */
   108741 
   108742 #ifndef NDEBUG
   108743 /* For tracing shifts, the names of all terminals and nonterminals
   108744 ** are required.  The following table supplies these names */
   108745 static const char *const yyTokenName[] = {
   108746   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   108747   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   108748   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   108749   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   108750   "TABLE",         "CREATE",        "IF",            "NOT",
   108751   "EXISTS",        "TEMP",          "LP",            "RP",
   108752   "AS",            "COMMA",         "ID",            "INDEXED",
   108753   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
   108754   "ASC",           "ATTACH",        "BEFORE",        "BY",
   108755   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
   108756   "DATABASE",      "DESC",          "DETACH",        "EACH",
   108757   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
   108758   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
   108759   "KEY",           "OF",            "OFFSET",        "PRAGMA",
   108760   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
   108761   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
   108762   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
   108763   "OR",            "AND",           "IS",            "BETWEEN",
   108764   "IN",            "ISNULL",        "NOTNULL",       "NE",
   108765   "EQ",            "GT",            "LE",            "LT",
   108766   "GE",            "ESCAPE",        "BITAND",        "BITOR",
   108767   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
   108768   "STAR",          "SLASH",         "REM",           "CONCAT",
   108769   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
   108770   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
   108771   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
   108772   "ON",            "INSERT",        "DELETE",        "UPDATE",
   108773   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
   108774   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
   108775   "SELECT",        "DISTINCT",      "DOT",           "FROM",
   108776   "JOIN",          "USING",         "ORDER",         "GROUP",
   108777   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   108778   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
   108779   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
   108780   "THEN",          "ELSE",          "INDEX",         "ALTER",
   108781   "ADD",           "error",         "input",         "cmdlist",
   108782   "ecmd",          "explain",       "cmdx",          "cmd",
   108783   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
   108784   "create_table",  "create_table_args",  "createkw",      "temp",
   108785   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
   108786   "select",        "column",        "columnid",      "type",
   108787   "carglist",      "id",            "ids",           "typetoken",
   108788   "typename",      "signed",        "plus_num",      "minus_num",
   108789   "carg",          "ccons",         "term",          "expr",
   108790   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   108791   "refargs",       "defer_subclause",  "refarg",        "refact",
   108792   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
   108793   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
   108794   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
   108795   "distinct",      "selcollist",    "from",          "where_opt",
   108796   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
   108797   "sclp",          "as",            "seltablist",    "stl_prefix",
   108798   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
   108799   "joinop2",       "inscollist",    "sortlist",      "nexprlist",
   108800   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
   108801   "exprlist",      "likeop",        "between_op",    "in_op",
   108802   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
   108803   "collate",       "nmnum",         "number",        "trigger_decl",
   108804   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
   108805   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
   108806   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
   108807   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
   108808   "lp",            "anylist",
   108809 };
   108810 #endif /* NDEBUG */
   108811 
   108812 #ifndef NDEBUG
   108813 /* For tracing reduce actions, the names of all rules are required.
   108814 */
   108815 static const char *const yyRuleName[] = {
   108816  /*   0 */ "input ::= cmdlist",
   108817  /*   1 */ "cmdlist ::= cmdlist ecmd",
   108818  /*   2 */ "cmdlist ::= ecmd",
   108819  /*   3 */ "ecmd ::= SEMI",
   108820  /*   4 */ "ecmd ::= explain cmdx SEMI",
   108821  /*   5 */ "explain ::=",
   108822  /*   6 */ "explain ::= EXPLAIN",
   108823  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   108824  /*   8 */ "cmdx ::= cmd",
   108825  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   108826  /*  10 */ "trans_opt ::=",
   108827  /*  11 */ "trans_opt ::= TRANSACTION",
   108828  /*  12 */ "trans_opt ::= TRANSACTION nm",
   108829  /*  13 */ "transtype ::=",
   108830  /*  14 */ "transtype ::= DEFERRED",
   108831  /*  15 */ "transtype ::= IMMEDIATE",
   108832  /*  16 */ "transtype ::= EXCLUSIVE",
   108833  /*  17 */ "cmd ::= COMMIT trans_opt",
   108834  /*  18 */ "cmd ::= END trans_opt",
   108835  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   108836  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   108837  /*  21 */ "savepoint_opt ::=",
   108838  /*  22 */ "cmd ::= SAVEPOINT nm",
   108839  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   108840  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   108841  /*  25 */ "cmd ::= create_table create_table_args",
   108842  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   108843  /*  27 */ "createkw ::= CREATE",
   108844  /*  28 */ "ifnotexists ::=",
   108845  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   108846  /*  30 */ "temp ::= TEMP",
   108847  /*  31 */ "temp ::=",
   108848  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
   108849  /*  33 */ "create_table_args ::= AS select",
   108850  /*  34 */ "columnlist ::= columnlist COMMA column",
   108851  /*  35 */ "columnlist ::= column",
   108852  /*  36 */ "column ::= columnid type carglist",
   108853  /*  37 */ "columnid ::= nm",
   108854  /*  38 */ "id ::= ID",
   108855  /*  39 */ "id ::= INDEXED",
   108856  /*  40 */ "ids ::= ID|STRING",
   108857  /*  41 */ "nm ::= id",
   108858  /*  42 */ "nm ::= STRING",
   108859  /*  43 */ "nm ::= JOIN_KW",
   108860  /*  44 */ "type ::=",
   108861  /*  45 */ "type ::= typetoken",
   108862  /*  46 */ "typetoken ::= typename",
   108863  /*  47 */ "typetoken ::= typename LP signed RP",
   108864  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
   108865  /*  49 */ "typename ::= ids",
   108866  /*  50 */ "typename ::= typename ids",
   108867  /*  51 */ "signed ::= plus_num",
   108868  /*  52 */ "signed ::= minus_num",
   108869  /*  53 */ "carglist ::= carglist carg",
   108870  /*  54 */ "carglist ::=",
   108871  /*  55 */ "carg ::= CONSTRAINT nm ccons",
   108872  /*  56 */ "carg ::= ccons",
   108873  /*  57 */ "ccons ::= DEFAULT term",
   108874  /*  58 */ "ccons ::= DEFAULT LP expr RP",
   108875  /*  59 */ "ccons ::= DEFAULT PLUS term",
   108876  /*  60 */ "ccons ::= DEFAULT MINUS term",
   108877  /*  61 */ "ccons ::= DEFAULT id",
   108878  /*  62 */ "ccons ::= NULL onconf",
   108879  /*  63 */ "ccons ::= NOT NULL onconf",
   108880  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   108881  /*  65 */ "ccons ::= UNIQUE onconf",
   108882  /*  66 */ "ccons ::= CHECK LP expr RP",
   108883  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   108884  /*  68 */ "ccons ::= defer_subclause",
   108885  /*  69 */ "ccons ::= COLLATE ids",
   108886  /*  70 */ "autoinc ::=",
   108887  /*  71 */ "autoinc ::= AUTOINCR",
   108888  /*  72 */ "refargs ::=",
   108889  /*  73 */ "refargs ::= refargs refarg",
   108890  /*  74 */ "refarg ::= MATCH nm",
   108891  /*  75 */ "refarg ::= ON INSERT refact",
   108892  /*  76 */ "refarg ::= ON DELETE refact",
   108893  /*  77 */ "refarg ::= ON UPDATE refact",
   108894  /*  78 */ "refact ::= SET NULL",
   108895  /*  79 */ "refact ::= SET DEFAULT",
   108896  /*  80 */ "refact ::= CASCADE",
   108897  /*  81 */ "refact ::= RESTRICT",
   108898  /*  82 */ "refact ::= NO ACTION",
   108899  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   108900  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   108901  /*  85 */ "init_deferred_pred_opt ::=",
   108902  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   108903  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   108904  /*  88 */ "conslist_opt ::=",
   108905  /*  89 */ "conslist_opt ::= COMMA conslist",
   108906  /*  90 */ "conslist ::= conslist COMMA tcons",
   108907  /*  91 */ "conslist ::= conslist tcons",
   108908  /*  92 */ "conslist ::= tcons",
   108909  /*  93 */ "tcons ::= CONSTRAINT nm",
   108910  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   108911  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   108912  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
   108913  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   108914  /*  98 */ "defer_subclause_opt ::=",
   108915  /*  99 */ "defer_subclause_opt ::= defer_subclause",
   108916  /* 100 */ "onconf ::=",
   108917  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
   108918  /* 102 */ "orconf ::=",
   108919  /* 103 */ "orconf ::= OR resolvetype",
   108920  /* 104 */ "resolvetype ::= raisetype",
   108921  /* 105 */ "resolvetype ::= IGNORE",
   108922  /* 106 */ "resolvetype ::= REPLACE",
   108923  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
   108924  /* 108 */ "ifexists ::= IF EXISTS",
   108925  /* 109 */ "ifexists ::=",
   108926  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   108927  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
   108928  /* 112 */ "cmd ::= select",
   108929  /* 113 */ "select ::= oneselect",
   108930  /* 114 */ "select ::= select multiselect_op oneselect",
   108931  /* 115 */ "multiselect_op ::= UNION",
   108932  /* 116 */ "multiselect_op ::= UNION ALL",
   108933  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   108934  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   108935  /* 119 */ "distinct ::= DISTINCT",
   108936  /* 120 */ "distinct ::= ALL",
   108937  /* 121 */ "distinct ::=",
   108938  /* 122 */ "sclp ::= selcollist COMMA",
   108939  /* 123 */ "sclp ::=",
   108940  /* 124 */ "selcollist ::= sclp expr as",
   108941  /* 125 */ "selcollist ::= sclp STAR",
   108942  /* 126 */ "selcollist ::= sclp nm DOT STAR",
   108943  /* 127 */ "as ::= AS nm",
   108944  /* 128 */ "as ::= ids",
   108945  /* 129 */ "as ::=",
   108946  /* 130 */ "from ::=",
   108947  /* 131 */ "from ::= FROM seltablist",
   108948  /* 132 */ "stl_prefix ::= seltablist joinop",
   108949  /* 133 */ "stl_prefix ::=",
   108950  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   108951  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   108952  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   108953  /* 137 */ "dbnm ::=",
   108954  /* 138 */ "dbnm ::= DOT nm",
   108955  /* 139 */ "fullname ::= nm dbnm",
   108956  /* 140 */ "joinop ::= COMMA|JOIN",
   108957  /* 141 */ "joinop ::= JOIN_KW JOIN",
   108958  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
   108959  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
   108960  /* 144 */ "on_opt ::= ON expr",
   108961  /* 145 */ "on_opt ::=",
   108962  /* 146 */ "indexed_opt ::=",
   108963  /* 147 */ "indexed_opt ::= INDEXED BY nm",
   108964  /* 148 */ "indexed_opt ::= NOT INDEXED",
   108965  /* 149 */ "using_opt ::= USING LP inscollist RP",
   108966  /* 150 */ "using_opt ::=",
   108967  /* 151 */ "orderby_opt ::=",
   108968  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
   108969  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
   108970  /* 154 */ "sortlist ::= expr sortorder",
   108971  /* 155 */ "sortorder ::= ASC",
   108972  /* 156 */ "sortorder ::= DESC",
   108973  /* 157 */ "sortorder ::=",
   108974  /* 158 */ "groupby_opt ::=",
   108975  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
   108976  /* 160 */ "having_opt ::=",
   108977  /* 161 */ "having_opt ::= HAVING expr",
   108978  /* 162 */ "limit_opt ::=",
   108979  /* 163 */ "limit_opt ::= LIMIT expr",
   108980  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
   108981  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
   108982  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
   108983  /* 167 */ "where_opt ::=",
   108984  /* 168 */ "where_opt ::= WHERE expr",
   108985  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
   108986  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
   108987  /* 171 */ "setlist ::= nm EQ expr",
   108988  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
   108989  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
   108990  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   108991  /* 175 */ "insert_cmd ::= INSERT orconf",
   108992  /* 176 */ "insert_cmd ::= REPLACE",
   108993  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
   108994  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
   108995  /* 179 */ "inscollist_opt ::=",
   108996  /* 180 */ "inscollist_opt ::= LP inscollist RP",
   108997  /* 181 */ "inscollist ::= inscollist COMMA nm",
   108998  /* 182 */ "inscollist ::= nm",
   108999  /* 183 */ "expr ::= term",
   109000  /* 184 */ "expr ::= LP expr RP",
   109001  /* 185 */ "term ::= NULL",
   109002  /* 186 */ "expr ::= id",
   109003  /* 187 */ "expr ::= JOIN_KW",
   109004  /* 188 */ "expr ::= nm DOT nm",
   109005  /* 189 */ "expr ::= nm DOT nm DOT nm",
   109006  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
   109007  /* 191 */ "term ::= STRING",
   109008  /* 192 */ "expr ::= REGISTER",
   109009  /* 193 */ "expr ::= VARIABLE",
   109010  /* 194 */ "expr ::= expr COLLATE ids",
   109011  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
   109012  /* 196 */ "expr ::= ID LP distinct exprlist RP",
   109013  /* 197 */ "expr ::= ID LP STAR RP",
   109014  /* 198 */ "term ::= CTIME_KW",
   109015  /* 199 */ "expr ::= expr AND expr",
   109016  /* 200 */ "expr ::= expr OR expr",
   109017  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
   109018  /* 202 */ "expr ::= expr EQ|NE expr",
   109019  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   109020  /* 204 */ "expr ::= expr PLUS|MINUS expr",
   109021  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
   109022  /* 206 */ "expr ::= expr CONCAT expr",
   109023  /* 207 */ "likeop ::= LIKE_KW",
   109024  /* 208 */ "likeop ::= NOT LIKE_KW",
   109025  /* 209 */ "likeop ::= MATCH",
   109026  /* 210 */ "likeop ::= NOT MATCH",
   109027  /* 211 */ "expr ::= expr likeop expr",
   109028  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
   109029  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
   109030  /* 214 */ "expr ::= expr NOT NULL",
   109031  /* 215 */ "expr ::= expr IS expr",
   109032  /* 216 */ "expr ::= expr IS NOT expr",
   109033  /* 217 */ "expr ::= NOT expr",
   109034  /* 218 */ "expr ::= BITNOT expr",
   109035  /* 219 */ "expr ::= MINUS expr",
   109036  /* 220 */ "expr ::= PLUS expr",
   109037  /* 221 */ "between_op ::= BETWEEN",
   109038  /* 222 */ "between_op ::= NOT BETWEEN",
   109039  /* 223 */ "expr ::= expr between_op expr AND expr",
   109040  /* 224 */ "in_op ::= IN",
   109041  /* 225 */ "in_op ::= NOT IN",
   109042  /* 226 */ "expr ::= expr in_op LP exprlist RP",
   109043  /* 227 */ "expr ::= LP select RP",
   109044  /* 228 */ "expr ::= expr in_op LP select RP",
   109045  /* 229 */ "expr ::= expr in_op nm dbnm",
   109046  /* 230 */ "expr ::= EXISTS LP select RP",
   109047  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
   109048  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   109049  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
   109050  /* 234 */ "case_else ::= ELSE expr",
   109051  /* 235 */ "case_else ::=",
   109052  /* 236 */ "case_operand ::= expr",
   109053  /* 237 */ "case_operand ::=",
   109054  /* 238 */ "exprlist ::= nexprlist",
   109055  /* 239 */ "exprlist ::=",
   109056  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
   109057  /* 241 */ "nexprlist ::= expr",
   109058  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
   109059  /* 243 */ "uniqueflag ::= UNIQUE",
   109060  /* 244 */ "uniqueflag ::=",
   109061  /* 245 */ "idxlist_opt ::=",
   109062  /* 246 */ "idxlist_opt ::= LP idxlist RP",
   109063  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   109064  /* 248 */ "idxlist ::= nm collate sortorder",
   109065  /* 249 */ "collate ::=",
   109066  /* 250 */ "collate ::= COLLATE ids",
   109067  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
   109068  /* 252 */ "cmd ::= VACUUM",
   109069  /* 253 */ "cmd ::= VACUUM nm",
   109070  /* 254 */ "cmd ::= PRAGMA nm dbnm",
   109071  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   109072  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   109073  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   109074  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   109075  /* 259 */ "nmnum ::= plus_num",
   109076  /* 260 */ "nmnum ::= nm",
   109077  /* 261 */ "nmnum ::= ON",
   109078  /* 262 */ "nmnum ::= DELETE",
   109079  /* 263 */ "nmnum ::= DEFAULT",
   109080  /* 264 */ "plus_num ::= PLUS number",
   109081  /* 265 */ "plus_num ::= number",
   109082  /* 266 */ "minus_num ::= MINUS number",
   109083  /* 267 */ "number ::= INTEGER|FLOAT",
   109084  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   109085  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   109086  /* 270 */ "trigger_time ::= BEFORE",
   109087  /* 271 */ "trigger_time ::= AFTER",
   109088  /* 272 */ "trigger_time ::= INSTEAD OF",
   109089  /* 273 */ "trigger_time ::=",
   109090  /* 274 */ "trigger_event ::= DELETE|INSERT",
   109091  /* 275 */ "trigger_event ::= UPDATE",
   109092  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
   109093  /* 277 */ "foreach_clause ::=",
   109094  /* 278 */ "foreach_clause ::= FOR EACH ROW",
   109095  /* 279 */ "when_clause ::=",
   109096  /* 280 */ "when_clause ::= WHEN expr",
   109097  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   109098  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   109099  /* 283 */ "trnm ::= nm",
   109100  /* 284 */ "trnm ::= nm DOT nm",
   109101  /* 285 */ "tridxby ::=",
   109102  /* 286 */ "tridxby ::= INDEXED BY nm",
   109103  /* 287 */ "tridxby ::= NOT INDEXED",
   109104  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   109105  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
   109106  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   109107  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   109108  /* 292 */ "trigger_cmd ::= select",
   109109  /* 293 */ "expr ::= RAISE LP IGNORE RP",
   109110  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   109111  /* 295 */ "raisetype ::= ROLLBACK",
   109112  /* 296 */ "raisetype ::= ABORT",
   109113  /* 297 */ "raisetype ::= FAIL",
   109114  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
   109115  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   109116  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
   109117  /* 301 */ "key_opt ::=",
   109118  /* 302 */ "key_opt ::= KEY expr",
   109119  /* 303 */ "database_kw_opt ::= DATABASE",
   109120  /* 304 */ "database_kw_opt ::=",
   109121  /* 305 */ "cmd ::= REINDEX",
   109122  /* 306 */ "cmd ::= REINDEX nm dbnm",
   109123  /* 307 */ "cmd ::= ANALYZE",
   109124  /* 308 */ "cmd ::= ANALYZE nm dbnm",
   109125  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   109126  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   109127  /* 311 */ "add_column_fullname ::= fullname",
   109128  /* 312 */ "kwcolumn_opt ::=",
   109129  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
   109130  /* 314 */ "cmd ::= create_vtab",
   109131  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
   109132  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
   109133  /* 317 */ "vtabarglist ::= vtabarg",
   109134  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   109135  /* 319 */ "vtabarg ::=",
   109136  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
   109137  /* 321 */ "vtabargtoken ::= ANY",
   109138  /* 322 */ "vtabargtoken ::= lp anylist RP",
   109139  /* 323 */ "lp ::= LP",
   109140  /* 324 */ "anylist ::=",
   109141  /* 325 */ "anylist ::= anylist LP anylist RP",
   109142  /* 326 */ "anylist ::= anylist ANY",
   109143 };
   109144 #endif /* NDEBUG */
   109145 
   109146 
   109147 #if YYSTACKDEPTH<=0
   109148 /*
   109149 ** Try to increase the size of the parser stack.
   109150 */
   109151 static void yyGrowStack(yyParser *p){
   109152   int newSize;
   109153   yyStackEntry *pNew;
   109154 
   109155   newSize = p->yystksz*2 + 100;
   109156   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   109157   if( pNew ){
   109158     p->yystack = pNew;
   109159     p->yystksz = newSize;
   109160 #ifndef NDEBUG
   109161     if( yyTraceFILE ){
   109162       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   109163               yyTracePrompt, p->yystksz);
   109164     }
   109165 #endif
   109166   }
   109167 }
   109168 #endif
   109169 
   109170 /*
   109171 ** This function allocates a new parser.
   109172 ** The only argument is a pointer to a function which works like
   109173 ** malloc.
   109174 **
   109175 ** Inputs:
   109176 ** A pointer to the function used to allocate memory.
   109177 **
   109178 ** Outputs:
   109179 ** A pointer to a parser.  This pointer is used in subsequent calls
   109180 ** to sqlite3Parser and sqlite3ParserFree.
   109181 */
   109182 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   109183   yyParser *pParser;
   109184   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   109185   if( pParser ){
   109186     pParser->yyidx = -1;
   109187 #ifdef YYTRACKMAXSTACKDEPTH
   109188     pParser->yyidxMax = 0;
   109189 #endif
   109190 #if YYSTACKDEPTH<=0
   109191     pParser->yystack = NULL;
   109192     pParser->yystksz = 0;
   109193     yyGrowStack(pParser);
   109194 #endif
   109195   }
   109196   return pParser;
   109197 }
   109198 
   109199 /* The following function deletes the value associated with a
   109200 ** symbol.  The symbol can be either a terminal or nonterminal.
   109201 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   109202 ** the value.
   109203 */
   109204 static void yy_destructor(
   109205   yyParser *yypParser,    /* The parser */
   109206   YYCODETYPE yymajor,     /* Type code for object to destroy */
   109207   YYMINORTYPE *yypminor   /* The object to be destroyed */
   109208 ){
   109209   sqlite3ParserARG_FETCH;
   109210   switch( yymajor ){
   109211     /* Here is inserted the actions which take place when a
   109212     ** terminal or non-terminal is destroyed.  This can happen
   109213     ** when the symbol is popped from the stack during a
   109214     ** reduce or during error processing or when a parser is
   109215     ** being destroyed before it is finished parsing.
   109216     **
   109217     ** Note: during a reduce, the only symbols destroyed are those
   109218     ** which appear on the RHS of the rule, but which are not used
   109219     ** inside the C code.
   109220     */
   109221     case 160: /* select */
   109222     case 194: /* oneselect */
   109223 {
   109224 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
   109225 }
   109226       break;
   109227     case 174: /* term */
   109228     case 175: /* expr */
   109229 {
   109230 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
   109231 }
   109232       break;
   109233     case 179: /* idxlist_opt */
   109234     case 187: /* idxlist */
   109235     case 197: /* selcollist */
   109236     case 200: /* groupby_opt */
   109237     case 202: /* orderby_opt */
   109238     case 204: /* sclp */
   109239     case 214: /* sortlist */
   109240     case 215: /* nexprlist */
   109241     case 216: /* setlist */
   109242     case 220: /* exprlist */
   109243     case 225: /* case_exprlist */
   109244 {
   109245 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
   109246 }
   109247       break;
   109248     case 193: /* fullname */
   109249     case 198: /* from */
   109250     case 206: /* seltablist */
   109251     case 207: /* stl_prefix */
   109252 {
   109253 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
   109254 }
   109255       break;
   109256     case 199: /* where_opt */
   109257     case 201: /* having_opt */
   109258     case 210: /* on_opt */
   109259     case 224: /* case_operand */
   109260     case 226: /* case_else */
   109261     case 236: /* when_clause */
   109262     case 241: /* key_opt */
   109263 {
   109264 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
   109265 }
   109266       break;
   109267     case 211: /* using_opt */
   109268     case 213: /* inscollist */
   109269     case 218: /* inscollist_opt */
   109270 {
   109271 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
   109272 }
   109273       break;
   109274     case 219: /* valuelist */
   109275 {
   109276 
   109277   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
   109278   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
   109279 
   109280 }
   109281       break;
   109282     case 232: /* trigger_cmd_list */
   109283     case 237: /* trigger_cmd */
   109284 {
   109285 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
   109286 }
   109287       break;
   109288     case 234: /* trigger_event */
   109289 {
   109290 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
   109291 }
   109292       break;
   109293     default:  break;   /* If no destructor action specified: do nothing */
   109294   }
   109295 }
   109296 
   109297 /*
   109298 ** Pop the parser's stack once.
   109299 **
   109300 ** If there is a destructor routine associated with the token which
   109301 ** is popped from the stack, then call it.
   109302 **
   109303 ** Return the major token number for the symbol popped.
   109304 */
   109305 static int yy_pop_parser_stack(yyParser *pParser){
   109306   YYCODETYPE yymajor;
   109307   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   109308 
   109309   /* There is no mechanism by which the parser stack can be popped below
   109310   ** empty in SQLite.  */
   109311   if( NEVER(pParser->yyidx<0) ) return 0;
   109312 #ifndef NDEBUG
   109313   if( yyTraceFILE && pParser->yyidx>=0 ){
   109314     fprintf(yyTraceFILE,"%sPopping %s\n",
   109315       yyTracePrompt,
   109316       yyTokenName[yytos->major]);
   109317   }
   109318 #endif
   109319   yymajor = yytos->major;
   109320   yy_destructor(pParser, yymajor, &yytos->minor);
   109321   pParser->yyidx--;
   109322   return yymajor;
   109323 }
   109324 
   109325 /*
   109326 ** Deallocate and destroy a parser.  Destructors are all called for
   109327 ** all stack elements before shutting the parser down.
   109328 **
   109329 ** Inputs:
   109330 ** <ul>
   109331 ** <li>  A pointer to the parser.  This should be a pointer
   109332 **       obtained from sqlite3ParserAlloc.
   109333 ** <li>  A pointer to a function used to reclaim memory obtained
   109334 **       from malloc.
   109335 ** </ul>
   109336 */
   109337 SQLITE_PRIVATE void sqlite3ParserFree(
   109338   void *p,                    /* The parser to be deleted */
   109339   void (*freeProc)(void*)     /* Function used to reclaim memory */
   109340 ){
   109341   yyParser *pParser = (yyParser*)p;
   109342   /* In SQLite, we never try to destroy a parser that was not successfully
   109343   ** created in the first place. */
   109344   if( NEVER(pParser==0) ) return;
   109345   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   109346 #if YYSTACKDEPTH<=0
   109347   free(pParser->yystack);
   109348 #endif
   109349   (*freeProc)((void*)pParser);
   109350 }
   109351 
   109352 /*
   109353 ** Return the peak depth of the stack for a parser.
   109354 */
   109355 #ifdef YYTRACKMAXSTACKDEPTH
   109356 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   109357   yyParser *pParser = (yyParser*)p;
   109358   return pParser->yyidxMax;
   109359 }
   109360 #endif
   109361 
   109362 /*
   109363 ** Find the appropriate action for a parser given the terminal
   109364 ** look-ahead token iLookAhead.
   109365 **
   109366 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   109367 ** independent of the look-ahead.  If it is, return the action, otherwise
   109368 ** return YY_NO_ACTION.
   109369 */
   109370 static int yy_find_shift_action(
   109371   yyParser *pParser,        /* The parser */
   109372   YYCODETYPE iLookAhead     /* The look-ahead token */
   109373 ){
   109374   int i;
   109375   int stateno = pParser->yystack[pParser->yyidx].stateno;
   109376 
   109377   if( stateno>YY_SHIFT_COUNT
   109378    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   109379     return yy_default[stateno];
   109380   }
   109381   assert( iLookAhead!=YYNOCODE );
   109382   i += iLookAhead;
   109383   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   109384     if( iLookAhead>0 ){
   109385 #ifdef YYFALLBACK
   109386       YYCODETYPE iFallback;            /* Fallback token */
   109387       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   109388              && (iFallback = yyFallback[iLookAhead])!=0 ){
   109389 #ifndef NDEBUG
   109390         if( yyTraceFILE ){
   109391           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   109392              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   109393         }
   109394 #endif
   109395         return yy_find_shift_action(pParser, iFallback);
   109396       }
   109397 #endif
   109398 #ifdef YYWILDCARD
   109399       {
   109400         int j = i - iLookAhead + YYWILDCARD;
   109401         if(
   109402 #if YY_SHIFT_MIN+YYWILDCARD<0
   109403           j>=0 &&
   109404 #endif
   109405 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   109406           j<YY_ACTTAB_COUNT &&
   109407 #endif
   109408           yy_lookahead[j]==YYWILDCARD
   109409         ){
   109410 #ifndef NDEBUG
   109411           if( yyTraceFILE ){
   109412             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   109413                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   109414           }
   109415 #endif /* NDEBUG */
   109416           return yy_action[j];
   109417         }
   109418       }
   109419 #endif /* YYWILDCARD */
   109420     }
   109421     return yy_default[stateno];
   109422   }else{
   109423     return yy_action[i];
   109424   }
   109425 }
   109426 
   109427 /*
   109428 ** Find the appropriate action for a parser given the non-terminal
   109429 ** look-ahead token iLookAhead.
   109430 **
   109431 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   109432 ** independent of the look-ahead.  If it is, return the action, otherwise
   109433 ** return YY_NO_ACTION.
   109434 */
   109435 static int yy_find_reduce_action(
   109436   int stateno,              /* Current state number */
   109437   YYCODETYPE iLookAhead     /* The look-ahead token */
   109438 ){
   109439   int i;
   109440 #ifdef YYERRORSYMBOL
   109441   if( stateno>YY_REDUCE_COUNT ){
   109442     return yy_default[stateno];
   109443   }
   109444 #else
   109445   assert( stateno<=YY_REDUCE_COUNT );
   109446 #endif
   109447   i = yy_reduce_ofst[stateno];
   109448   assert( i!=YY_REDUCE_USE_DFLT );
   109449   assert( iLookAhead!=YYNOCODE );
   109450   i += iLookAhead;
   109451 #ifdef YYERRORSYMBOL
   109452   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   109453     return yy_default[stateno];
   109454   }
   109455 #else
   109456   assert( i>=0 && i<YY_ACTTAB_COUNT );
   109457   assert( yy_lookahead[i]==iLookAhead );
   109458 #endif
   109459   return yy_action[i];
   109460 }
   109461 
   109462 /*
   109463 ** The following routine is called if the stack overflows.
   109464 */
   109465 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   109466    sqlite3ParserARG_FETCH;
   109467    yypParser->yyidx--;
   109468 #ifndef NDEBUG
   109469    if( yyTraceFILE ){
   109470      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   109471    }
   109472 #endif
   109473    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   109474    /* Here code is inserted which will execute if the parser
   109475    ** stack every overflows */
   109476 
   109477   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   109478   sqlite3ErrorMsg(pParse, "parser stack overflow");
   109479    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   109480 }
   109481 
   109482 /*
   109483 ** Perform a shift action.
   109484 */
   109485 static void yy_shift(
   109486   yyParser *yypParser,          /* The parser to be shifted */
   109487   int yyNewState,               /* The new state to shift in */
   109488   int yyMajor,                  /* The major token to shift in */
   109489   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   109490 ){
   109491   yyStackEntry *yytos;
   109492   yypParser->yyidx++;
   109493 #ifdef YYTRACKMAXSTACKDEPTH
   109494   if( yypParser->yyidx>yypParser->yyidxMax ){
   109495     yypParser->yyidxMax = yypParser->yyidx;
   109496   }
   109497 #endif
   109498 #if YYSTACKDEPTH>0
   109499   if( yypParser->yyidx>=YYSTACKDEPTH ){
   109500     yyStackOverflow(yypParser, yypMinor);
   109501     return;
   109502   }
   109503 #else
   109504   if( yypParser->yyidx>=yypParser->yystksz ){
   109505     yyGrowStack(yypParser);
   109506     if( yypParser->yyidx>=yypParser->yystksz ){
   109507       yyStackOverflow(yypParser, yypMinor);
   109508       return;
   109509     }
   109510   }
   109511 #endif
   109512   yytos = &yypParser->yystack[yypParser->yyidx];
   109513   yytos->stateno = (YYACTIONTYPE)yyNewState;
   109514   yytos->major = (YYCODETYPE)yyMajor;
   109515   yytos->minor = *yypMinor;
   109516 #ifndef NDEBUG
   109517   if( yyTraceFILE && yypParser->yyidx>0 ){
   109518     int i;
   109519     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   109520     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   109521     for(i=1; i<=yypParser->yyidx; i++)
   109522       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   109523     fprintf(yyTraceFILE,"\n");
   109524   }
   109525 #endif
   109526 }
   109527 
   109528 /* The following table contains information about every rule that
   109529 ** is used during the reduce.
   109530 */
   109531 static const struct {
   109532   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   109533   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   109534 } yyRuleInfo[] = {
   109535   { 142, 1 },
   109536   { 143, 2 },
   109537   { 143, 1 },
   109538   { 144, 1 },
   109539   { 144, 3 },
   109540   { 145, 0 },
   109541   { 145, 1 },
   109542   { 145, 3 },
   109543   { 146, 1 },
   109544   { 147, 3 },
   109545   { 149, 0 },
   109546   { 149, 1 },
   109547   { 149, 2 },
   109548   { 148, 0 },
   109549   { 148, 1 },
   109550   { 148, 1 },
   109551   { 148, 1 },
   109552   { 147, 2 },
   109553   { 147, 2 },
   109554   { 147, 2 },
   109555   { 151, 1 },
   109556   { 151, 0 },
   109557   { 147, 2 },
   109558   { 147, 3 },
   109559   { 147, 5 },
   109560   { 147, 2 },
   109561   { 152, 6 },
   109562   { 154, 1 },
   109563   { 156, 0 },
   109564   { 156, 3 },
   109565   { 155, 1 },
   109566   { 155, 0 },
   109567   { 153, 4 },
   109568   { 153, 2 },
   109569   { 158, 3 },
   109570   { 158, 1 },
   109571   { 161, 3 },
   109572   { 162, 1 },
   109573   { 165, 1 },
   109574   { 165, 1 },
   109575   { 166, 1 },
   109576   { 150, 1 },
   109577   { 150, 1 },
   109578   { 150, 1 },
   109579   { 163, 0 },
   109580   { 163, 1 },
   109581   { 167, 1 },
   109582   { 167, 4 },
   109583   { 167, 6 },
   109584   { 168, 1 },
   109585   { 168, 2 },
   109586   { 169, 1 },
   109587   { 169, 1 },
   109588   { 164, 2 },
   109589   { 164, 0 },
   109590   { 172, 3 },
   109591   { 172, 1 },
   109592   { 173, 2 },
   109593   { 173, 4 },
   109594   { 173, 3 },
   109595   { 173, 3 },
   109596   { 173, 2 },
   109597   { 173, 2 },
   109598   { 173, 3 },
   109599   { 173, 5 },
   109600   { 173, 2 },
   109601   { 173, 4 },
   109602   { 173, 4 },
   109603   { 173, 1 },
   109604   { 173, 2 },
   109605   { 178, 0 },
   109606   { 178, 1 },
   109607   { 180, 0 },
   109608   { 180, 2 },
   109609   { 182, 2 },
   109610   { 182, 3 },
   109611   { 182, 3 },
   109612   { 182, 3 },
   109613   { 183, 2 },
   109614   { 183, 2 },
   109615   { 183, 1 },
   109616   { 183, 1 },
   109617   { 183, 2 },
   109618   { 181, 3 },
   109619   { 181, 2 },
   109620   { 184, 0 },
   109621   { 184, 2 },
   109622   { 184, 2 },
   109623   { 159, 0 },
   109624   { 159, 2 },
   109625   { 185, 3 },
   109626   { 185, 2 },
   109627   { 185, 1 },
   109628   { 186, 2 },
   109629   { 186, 7 },
   109630   { 186, 5 },
   109631   { 186, 5 },
   109632   { 186, 10 },
   109633   { 188, 0 },
   109634   { 188, 1 },
   109635   { 176, 0 },
   109636   { 176, 3 },
   109637   { 189, 0 },
   109638   { 189, 2 },
   109639   { 190, 1 },
   109640   { 190, 1 },
   109641   { 190, 1 },
   109642   { 147, 4 },
   109643   { 192, 2 },
   109644   { 192, 0 },
   109645   { 147, 8 },
   109646   { 147, 4 },
   109647   { 147, 1 },
   109648   { 160, 1 },
   109649   { 160, 3 },
   109650   { 195, 1 },
   109651   { 195, 2 },
   109652   { 195, 1 },
   109653   { 194, 9 },
   109654   { 196, 1 },
   109655   { 196, 1 },
   109656   { 196, 0 },
   109657   { 204, 2 },
   109658   { 204, 0 },
   109659   { 197, 3 },
   109660   { 197, 2 },
   109661   { 197, 4 },
   109662   { 205, 2 },
   109663   { 205, 1 },
   109664   { 205, 0 },
   109665   { 198, 0 },
   109666   { 198, 2 },
   109667   { 207, 2 },
   109668   { 207, 0 },
   109669   { 206, 7 },
   109670   { 206, 7 },
   109671   { 206, 7 },
   109672   { 157, 0 },
   109673   { 157, 2 },
   109674   { 193, 2 },
   109675   { 208, 1 },
   109676   { 208, 2 },
   109677   { 208, 3 },
   109678   { 208, 4 },
   109679   { 210, 2 },
   109680   { 210, 0 },
   109681   { 209, 0 },
   109682   { 209, 3 },
   109683   { 209, 2 },
   109684   { 211, 4 },
   109685   { 211, 0 },
   109686   { 202, 0 },
   109687   { 202, 3 },
   109688   { 214, 4 },
   109689   { 214, 2 },
   109690   { 177, 1 },
   109691   { 177, 1 },
   109692   { 177, 0 },
   109693   { 200, 0 },
   109694   { 200, 3 },
   109695   { 201, 0 },
   109696   { 201, 2 },
   109697   { 203, 0 },
   109698   { 203, 2 },
   109699   { 203, 4 },
   109700   { 203, 4 },
   109701   { 147, 5 },
   109702   { 199, 0 },
   109703   { 199, 2 },
   109704   { 147, 7 },
   109705   { 216, 5 },
   109706   { 216, 3 },
   109707   { 147, 5 },
   109708   { 147, 5 },
   109709   { 147, 6 },
   109710   { 217, 2 },
   109711   { 217, 1 },
   109712   { 219, 4 },
   109713   { 219, 5 },
   109714   { 218, 0 },
   109715   { 218, 3 },
   109716   { 213, 3 },
   109717   { 213, 1 },
   109718   { 175, 1 },
   109719   { 175, 3 },
   109720   { 174, 1 },
   109721   { 175, 1 },
   109722   { 175, 1 },
   109723   { 175, 3 },
   109724   { 175, 5 },
   109725   { 174, 1 },
   109726   { 174, 1 },
   109727   { 175, 1 },
   109728   { 175, 1 },
   109729   { 175, 3 },
   109730   { 175, 6 },
   109731   { 175, 5 },
   109732   { 175, 4 },
   109733   { 174, 1 },
   109734   { 175, 3 },
   109735   { 175, 3 },
   109736   { 175, 3 },
   109737   { 175, 3 },
   109738   { 175, 3 },
   109739   { 175, 3 },
   109740   { 175, 3 },
   109741   { 175, 3 },
   109742   { 221, 1 },
   109743   { 221, 2 },
   109744   { 221, 1 },
   109745   { 221, 2 },
   109746   { 175, 3 },
   109747   { 175, 5 },
   109748   { 175, 2 },
   109749   { 175, 3 },
   109750   { 175, 3 },
   109751   { 175, 4 },
   109752   { 175, 2 },
   109753   { 175, 2 },
   109754   { 175, 2 },
   109755   { 175, 2 },
   109756   { 222, 1 },
   109757   { 222, 2 },
   109758   { 175, 5 },
   109759   { 223, 1 },
   109760   { 223, 2 },
   109761   { 175, 5 },
   109762   { 175, 3 },
   109763   { 175, 5 },
   109764   { 175, 4 },
   109765   { 175, 4 },
   109766   { 175, 5 },
   109767   { 225, 5 },
   109768   { 225, 4 },
   109769   { 226, 2 },
   109770   { 226, 0 },
   109771   { 224, 1 },
   109772   { 224, 0 },
   109773   { 220, 1 },
   109774   { 220, 0 },
   109775   { 215, 3 },
   109776   { 215, 1 },
   109777   { 147, 11 },
   109778   { 227, 1 },
   109779   { 227, 0 },
   109780   { 179, 0 },
   109781   { 179, 3 },
   109782   { 187, 5 },
   109783   { 187, 3 },
   109784   { 228, 0 },
   109785   { 228, 2 },
   109786   { 147, 4 },
   109787   { 147, 1 },
   109788   { 147, 2 },
   109789   { 147, 3 },
   109790   { 147, 5 },
   109791   { 147, 6 },
   109792   { 147, 5 },
   109793   { 147, 6 },
   109794   { 229, 1 },
   109795   { 229, 1 },
   109796   { 229, 1 },
   109797   { 229, 1 },
   109798   { 229, 1 },
   109799   { 170, 2 },
   109800   { 170, 1 },
   109801   { 171, 2 },
   109802   { 230, 1 },
   109803   { 147, 5 },
   109804   { 231, 11 },
   109805   { 233, 1 },
   109806   { 233, 1 },
   109807   { 233, 2 },
   109808   { 233, 0 },
   109809   { 234, 1 },
   109810   { 234, 1 },
   109811   { 234, 3 },
   109812   { 235, 0 },
   109813   { 235, 3 },
   109814   { 236, 0 },
   109815   { 236, 2 },
   109816   { 232, 3 },
   109817   { 232, 2 },
   109818   { 238, 1 },
   109819   { 238, 3 },
   109820   { 239, 0 },
   109821   { 239, 3 },
   109822   { 239, 2 },
   109823   { 237, 7 },
   109824   { 237, 5 },
   109825   { 237, 5 },
   109826   { 237, 5 },
   109827   { 237, 1 },
   109828   { 175, 4 },
   109829   { 175, 6 },
   109830   { 191, 1 },
   109831   { 191, 1 },
   109832   { 191, 1 },
   109833   { 147, 4 },
   109834   { 147, 6 },
   109835   { 147, 3 },
   109836   { 241, 0 },
   109837   { 241, 2 },
   109838   { 240, 1 },
   109839   { 240, 0 },
   109840   { 147, 1 },
   109841   { 147, 3 },
   109842   { 147, 1 },
   109843   { 147, 3 },
   109844   { 147, 6 },
   109845   { 147, 6 },
   109846   { 242, 1 },
   109847   { 243, 0 },
   109848   { 243, 1 },
   109849   { 147, 1 },
   109850   { 147, 4 },
   109851   { 244, 8 },
   109852   { 245, 1 },
   109853   { 245, 3 },
   109854   { 246, 0 },
   109855   { 246, 2 },
   109856   { 247, 1 },
   109857   { 247, 3 },
   109858   { 248, 1 },
   109859   { 249, 0 },
   109860   { 249, 4 },
   109861   { 249, 2 },
   109862 };
   109863 
   109864 static void yy_accept(yyParser*);  /* Forward Declaration */
   109865 
   109866 /*
   109867 ** Perform a reduce action and the shift that must immediately
   109868 ** follow the reduce.
   109869 */
   109870 static void yy_reduce(
   109871   yyParser *yypParser,         /* The parser */
   109872   int yyruleno                 /* Number of the rule by which to reduce */
   109873 ){
   109874   int yygoto;                     /* The next state */
   109875   int yyact;                      /* The next action */
   109876   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   109877   yyStackEntry *yymsp;            /* The top of the parser's stack */
   109878   int yysize;                     /* Amount to pop the stack */
   109879   sqlite3ParserARG_FETCH;
   109880   yymsp = &yypParser->yystack[yypParser->yyidx];
   109881 #ifndef NDEBUG
   109882   if( yyTraceFILE && yyruleno>=0
   109883         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   109884     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   109885       yyRuleName[yyruleno]);
   109886   }
   109887 #endif /* NDEBUG */
   109888 
   109889   /* Silence complaints from purify about yygotominor being uninitialized
   109890   ** in some cases when it is copied into the stack after the following
   109891   ** switch.  yygotominor is uninitialized when a rule reduces that does
   109892   ** not set the value of its left-hand side nonterminal.  Leaving the
   109893   ** value of the nonterminal uninitialized is utterly harmless as long
   109894   ** as the value is never used.  So really the only thing this code
   109895   ** accomplishes is to quieten purify.
   109896   **
   109897   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   109898   ** without this code, their parser segfaults.  I'm not sure what there
   109899   ** parser is doing to make this happen.  This is the second bug report
   109900   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   109901   ** that it has not been previously stressed...  (SQLite ticket #2172)
   109902   */
   109903   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   109904   yygotominor = yyzerominor;
   109905 
   109906 
   109907   switch( yyruleno ){
   109908   /* Beginning here are the reduction cases.  A typical example
   109909   ** follows:
   109910   **   case 0:
   109911   **  #line <lineno> <grammarfile>
   109912   **     { ... }           // User supplied code
   109913   **  #line <lineno> <thisfile>
   109914   **     break;
   109915   */
   109916       case 5: /* explain ::= */
   109917 { sqlite3BeginParse(pParse, 0); }
   109918         break;
   109919       case 6: /* explain ::= EXPLAIN */
   109920 { sqlite3BeginParse(pParse, 1); }
   109921         break;
   109922       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   109923 { sqlite3BeginParse(pParse, 2); }
   109924         break;
   109925       case 8: /* cmdx ::= cmd */
   109926 { sqlite3FinishCoding(pParse); }
   109927         break;
   109928       case 9: /* cmd ::= BEGIN transtype trans_opt */
   109929 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
   109930         break;
   109931       case 13: /* transtype ::= */
   109932 {yygotominor.yy392 = TK_DEFERRED;}
   109933         break;
   109934       case 14: /* transtype ::= DEFERRED */
   109935       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   109936       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   109937       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   109938       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   109939 {yygotominor.yy392 = yymsp[0].major;}
   109940         break;
   109941       case 17: /* cmd ::= COMMIT trans_opt */
   109942       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   109943 {sqlite3CommitTransaction(pParse);}
   109944         break;
   109945       case 19: /* cmd ::= ROLLBACK trans_opt */
   109946 {sqlite3RollbackTransaction(pParse);}
   109947         break;
   109948       case 22: /* cmd ::= SAVEPOINT nm */
   109949 {
   109950   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   109951 }
   109952         break;
   109953       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   109954 {
   109955   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   109956 }
   109957         break;
   109958       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   109959 {
   109960   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   109961 }
   109962         break;
   109963       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   109964 {
   109965    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
   109966 }
   109967         break;
   109968       case 27: /* createkw ::= CREATE */
   109969 {
   109970   pParse->db->lookaside.bEnabled = 0;
   109971   yygotominor.yy0 = yymsp[0].minor.yy0;
   109972 }
   109973         break;
   109974       case 28: /* ifnotexists ::= */
   109975       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   109976       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
   109977       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
   109978       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
   109979       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
   109980       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
   109981       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
   109982       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
   109983       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
   109984       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
   109985       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
   109986 {yygotominor.yy392 = 0;}
   109987         break;
   109988       case 29: /* ifnotexists ::= IF NOT EXISTS */
   109989       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   109990       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
   109991       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
   109992       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
   109993       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
   109994       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
   109995       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
   109996 {yygotominor.yy392 = 1;}
   109997         break;
   109998       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
   109999 {
   110000   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
   110001 }
   110002         break;
   110003       case 33: /* create_table_args ::= AS select */
   110004 {
   110005   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
   110006   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
   110007 }
   110008         break;
   110009       case 36: /* column ::= columnid type carglist */
   110010 {
   110011   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   110012   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   110013 }
   110014         break;
   110015       case 37: /* columnid ::= nm */
   110016 {
   110017   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   110018   yygotominor.yy0 = yymsp[0].minor.yy0;
   110019 }
   110020         break;
   110021       case 38: /* id ::= ID */
   110022       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
   110023       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
   110024       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
   110025       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
   110026       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
   110027       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
   110028       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
   110029       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
   110030       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
   110031       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
   110032       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
   110033       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
   110034       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
   110035       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
   110036       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
   110037       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
   110038       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
   110039       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
   110040       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
   110041       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
   110042       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
   110043       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
   110044 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   110045         break;
   110046       case 45: /* type ::= typetoken */
   110047 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   110048         break;
   110049       case 47: /* typetoken ::= typename LP signed RP */
   110050 {
   110051   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   110052   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   110053 }
   110054         break;
   110055       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
   110056 {
   110057   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   110058   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   110059 }
   110060         break;
   110061       case 50: /* typename ::= typename ids */
   110062 {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);}
   110063         break;
   110064       case 57: /* ccons ::= DEFAULT term */
   110065       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
   110066 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
   110067         break;
   110068       case 58: /* ccons ::= DEFAULT LP expr RP */
   110069 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
   110070         break;
   110071       case 60: /* ccons ::= DEFAULT MINUS term */
   110072 {
   110073   ExprSpan v;
   110074   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
   110075   v.zStart = yymsp[-1].minor.yy0.z;
   110076   v.zEnd = yymsp[0].minor.yy342.zEnd;
   110077   sqlite3AddDefaultValue(pParse,&v);
   110078 }
   110079         break;
   110080       case 61: /* ccons ::= DEFAULT id */
   110081 {
   110082   ExprSpan v;
   110083   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   110084   sqlite3AddDefaultValue(pParse,&v);
   110085 }
   110086         break;
   110087       case 63: /* ccons ::= NOT NULL onconf */
   110088 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
   110089         break;
   110090       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   110091 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
   110092         break;
   110093       case 65: /* ccons ::= UNIQUE onconf */
   110094 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
   110095         break;
   110096       case 66: /* ccons ::= CHECK LP expr RP */
   110097 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
   110098         break;
   110099       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   110100 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
   110101         break;
   110102       case 68: /* ccons ::= defer_subclause */
   110103 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
   110104         break;
   110105       case 69: /* ccons ::= COLLATE ids */
   110106 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   110107         break;
   110108       case 72: /* refargs ::= */
   110109 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
   110110         break;
   110111       case 73: /* refargs ::= refargs refarg */
   110112 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
   110113         break;
   110114       case 74: /* refarg ::= MATCH nm */
   110115       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
   110116 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
   110117         break;
   110118       case 76: /* refarg ::= ON DELETE refact */
   110119 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
   110120         break;
   110121       case 77: /* refarg ::= ON UPDATE refact */
   110122 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
   110123         break;
   110124       case 78: /* refact ::= SET NULL */
   110125 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
   110126         break;
   110127       case 79: /* refact ::= SET DEFAULT */
   110128 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
   110129         break;
   110130       case 80: /* refact ::= CASCADE */
   110131 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
   110132         break;
   110133       case 81: /* refact ::= RESTRICT */
   110134 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
   110135         break;
   110136       case 82: /* refact ::= NO ACTION */
   110137 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
   110138         break;
   110139       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   110140       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
   110141       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
   110142       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
   110143 {yygotominor.yy392 = yymsp[0].minor.yy392;}
   110144         break;
   110145       case 88: /* conslist_opt ::= */
   110146 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   110147         break;
   110148       case 89: /* conslist_opt ::= COMMA conslist */
   110149 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   110150         break;
   110151       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   110152 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
   110153         break;
   110154       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
   110155 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
   110156         break;
   110157       case 96: /* tcons ::= CHECK LP expr RP onconf */
   110158 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
   110159         break;
   110160       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   110161 {
   110162     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
   110163     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
   110164 }
   110165         break;
   110166       case 100: /* onconf ::= */
   110167 {yygotominor.yy392 = OE_Default;}
   110168         break;
   110169       case 102: /* orconf ::= */
   110170 {yygotominor.yy258 = OE_Default;}
   110171         break;
   110172       case 103: /* orconf ::= OR resolvetype */
   110173 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
   110174         break;
   110175       case 105: /* resolvetype ::= IGNORE */
   110176 {yygotominor.yy392 = OE_Ignore;}
   110177         break;
   110178       case 106: /* resolvetype ::= REPLACE */
   110179 {yygotominor.yy392 = OE_Replace;}
   110180         break;
   110181       case 107: /* cmd ::= DROP TABLE ifexists fullname */
   110182 {
   110183   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
   110184 }
   110185         break;
   110186       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   110187 {
   110188   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
   110189 }
   110190         break;
   110191       case 111: /* cmd ::= DROP VIEW ifexists fullname */
   110192 {
   110193   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
   110194 }
   110195         break;
   110196       case 112: /* cmd ::= select */
   110197 {
   110198   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
   110199   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
   110200   sqlite3ExplainBegin(pParse->pVdbe);
   110201   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
   110202   sqlite3ExplainFinish(pParse->pVdbe);
   110203   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
   110204 }
   110205         break;
   110206       case 113: /* select ::= oneselect */
   110207 {yygotominor.yy159 = yymsp[0].minor.yy159;}
   110208         break;
   110209       case 114: /* select ::= select multiselect_op oneselect */
   110210 {
   110211   if( yymsp[0].minor.yy159 ){
   110212     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
   110213     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
   110214   }else{
   110215     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
   110216   }
   110217   yygotominor.yy159 = yymsp[0].minor.yy159;
   110218 }
   110219         break;
   110220       case 116: /* multiselect_op ::= UNION ALL */
   110221 {yygotominor.yy392 = TK_ALL;}
   110222         break;
   110223       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   110224 {
   110225   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
   110226 }
   110227         break;
   110228       case 122: /* sclp ::= selcollist COMMA */
   110229       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
   110230 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
   110231         break;
   110232       case 123: /* sclp ::= */
   110233       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
   110234       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
   110235       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
   110236       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
   110237 {yygotominor.yy442 = 0;}
   110238         break;
   110239       case 124: /* selcollist ::= sclp expr as */
   110240 {
   110241    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
   110242    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
   110243    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
   110244 }
   110245         break;
   110246       case 125: /* selcollist ::= sclp STAR */
   110247 {
   110248   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   110249   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
   110250 }
   110251         break;
   110252       case 126: /* selcollist ::= sclp nm DOT STAR */
   110253 {
   110254   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   110255   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110256   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   110257   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
   110258 }
   110259         break;
   110260       case 129: /* as ::= */
   110261 {yygotominor.yy0.n = 0;}
   110262         break;
   110263       case 130: /* from ::= */
   110264 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
   110265         break;
   110266       case 131: /* from ::= FROM seltablist */
   110267 {
   110268   yygotominor.yy347 = yymsp[0].minor.yy347;
   110269   sqlite3SrcListShiftJoinType(yygotominor.yy347);
   110270 }
   110271         break;
   110272       case 132: /* stl_prefix ::= seltablist joinop */
   110273 {
   110274    yygotominor.yy347 = yymsp[-1].minor.yy347;
   110275    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
   110276 }
   110277         break;
   110278       case 133: /* stl_prefix ::= */
   110279 {yygotominor.yy347 = 0;}
   110280         break;
   110281       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   110282 {
   110283   yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
   110284   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
   110285 }
   110286         break;
   110287       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   110288 {
   110289     yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
   110290   }
   110291         break;
   110292       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   110293 {
   110294     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
   110295       yygotominor.yy347 = yymsp[-4].minor.yy347;
   110296     }else{
   110297       Select *pSubquery;
   110298       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
   110299       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
   110300       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
   110301     }
   110302   }
   110303         break;
   110304       case 137: /* dbnm ::= */
   110305       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
   110306 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   110307         break;
   110308       case 139: /* fullname ::= nm dbnm */
   110309 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   110310         break;
   110311       case 140: /* joinop ::= COMMA|JOIN */
   110312 { yygotominor.yy392 = JT_INNER; }
   110313         break;
   110314       case 141: /* joinop ::= JOIN_KW JOIN */
   110315 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   110316         break;
   110317       case 142: /* joinop ::= JOIN_KW nm JOIN */
   110318 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   110319         break;
   110320       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
   110321 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   110322         break;
   110323       case 144: /* on_opt ::= ON expr */
   110324       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
   110325       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
   110326       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
   110327       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
   110328 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
   110329         break;
   110330       case 145: /* on_opt ::= */
   110331       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
   110332       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
   110333       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
   110334       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
   110335 {yygotominor.yy122 = 0;}
   110336         break;
   110337       case 148: /* indexed_opt ::= NOT INDEXED */
   110338 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   110339         break;
   110340       case 149: /* using_opt ::= USING LP inscollist RP */
   110341       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
   110342 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
   110343         break;
   110344       case 150: /* using_opt ::= */
   110345       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
   110346 {yygotominor.yy180 = 0;}
   110347         break;
   110348       case 152: /* orderby_opt ::= ORDER BY sortlist */
   110349       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
   110350       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
   110351 {yygotominor.yy442 = yymsp[0].minor.yy442;}
   110352         break;
   110353       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
   110354 {
   110355   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
   110356   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110357 }
   110358         break;
   110359       case 154: /* sortlist ::= expr sortorder */
   110360 {
   110361   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
   110362   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
   110363 }
   110364         break;
   110365       case 155: /* sortorder ::= ASC */
   110366       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
   110367 {yygotominor.yy392 = SQLITE_SO_ASC;}
   110368         break;
   110369       case 156: /* sortorder ::= DESC */
   110370 {yygotominor.yy392 = SQLITE_SO_DESC;}
   110371         break;
   110372       case 162: /* limit_opt ::= */
   110373 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
   110374         break;
   110375       case 163: /* limit_opt ::= LIMIT expr */
   110376 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
   110377         break;
   110378       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
   110379 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
   110380         break;
   110381       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
   110382 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
   110383         break;
   110384       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
   110385 {
   110386   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
   110387   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
   110388 }
   110389         break;
   110390       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
   110391 {
   110392   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
   110393   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
   110394   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
   110395 }
   110396         break;
   110397       case 170: /* setlist ::= setlist COMMA nm EQ expr */
   110398 {
   110399   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
   110400   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110401 }
   110402         break;
   110403       case 171: /* setlist ::= nm EQ expr */
   110404 {
   110405   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
   110406   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110407 }
   110408         break;
   110409       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
   110410 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
   110411         break;
   110412       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
   110413 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
   110414         break;
   110415       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   110416 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
   110417         break;
   110418       case 175: /* insert_cmd ::= INSERT orconf */
   110419 {yygotominor.yy258 = yymsp[0].minor.yy258;}
   110420         break;
   110421       case 176: /* insert_cmd ::= REPLACE */
   110422 {yygotominor.yy258 = OE_Replace;}
   110423         break;
   110424       case 177: /* valuelist ::= VALUES LP nexprlist RP */
   110425 {
   110426   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
   110427   yygotominor.yy487.pSelect = 0;
   110428 }
   110429         break;
   110430       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
   110431 {
   110432   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
   110433   if( yymsp[-4].minor.yy487.pList ){
   110434     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
   110435     yymsp[-4].minor.yy487.pList = 0;
   110436   }
   110437   yygotominor.yy487.pList = 0;
   110438   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
   110439     sqlite3SelectDelete(pParse->db, pRight);
   110440     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
   110441     yygotominor.yy487.pSelect = 0;
   110442   }else{
   110443     pRight->op = TK_ALL;
   110444     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
   110445     pRight->selFlags |= SF_Values;
   110446     pRight->pPrior->selFlags |= SF_Values;
   110447     yygotominor.yy487.pSelect = pRight;
   110448   }
   110449 }
   110450         break;
   110451       case 181: /* inscollist ::= inscollist COMMA nm */
   110452 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
   110453         break;
   110454       case 182: /* inscollist ::= nm */
   110455 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   110456         break;
   110457       case 183: /* expr ::= term */
   110458 {yygotominor.yy342 = yymsp[0].minor.yy342;}
   110459         break;
   110460       case 184: /* expr ::= LP expr RP */
   110461 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   110462         break;
   110463       case 185: /* term ::= NULL */
   110464       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
   110465       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
   110466 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   110467         break;
   110468       case 186: /* expr ::= id */
   110469       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
   110470 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
   110471         break;
   110472       case 188: /* expr ::= nm DOT nm */
   110473 {
   110474   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110475   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   110476   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   110477   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   110478 }
   110479         break;
   110480       case 189: /* expr ::= nm DOT nm DOT nm */
   110481 {
   110482   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   110483   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110484   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   110485   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   110486   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   110487   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   110488 }
   110489         break;
   110490       case 192: /* expr ::= REGISTER */
   110491 {
   110492   /* When doing a nested parse, one can include terms in an expression
   110493   ** that look like this:   #1 #2 ...  These terms refer to registers
   110494   ** in the virtual machine.  #N is the N-th register. */
   110495   if( pParse->nested==0 ){
   110496     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   110497     yygotominor.yy342.pExpr = 0;
   110498   }else{
   110499     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   110500     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
   110501   }
   110502   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110503 }
   110504         break;
   110505       case 193: /* expr ::= VARIABLE */
   110506 {
   110507   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   110508   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
   110509   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110510 }
   110511         break;
   110512       case 194: /* expr ::= expr COLLATE ids */
   110513 {
   110514   yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
   110515   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
   110516   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110517 }
   110518         break;
   110519       case 195: /* expr ::= CAST LP expr AS typetoken RP */
   110520 {
   110521   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
   110522   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   110523 }
   110524         break;
   110525       case 196: /* expr ::= ID LP distinct exprlist RP */
   110526 {
   110527   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   110528     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   110529   }
   110530   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
   110531   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   110532   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
   110533     yygotominor.yy342.pExpr->flags |= EP_Distinct;
   110534   }
   110535 }
   110536         break;
   110537       case 197: /* expr ::= ID LP STAR RP */
   110538 {
   110539   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   110540   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   110541 }
   110542         break;
   110543       case 198: /* term ::= CTIME_KW */
   110544 {
   110545   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
   110546   ** treated as functions that return constants */
   110547   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
   110548   if( yygotominor.yy342.pExpr ){
   110549     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
   110550   }
   110551   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110552 }
   110553         break;
   110554       case 199: /* expr ::= expr AND expr */
   110555       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
   110556       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
   110557       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
   110558       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
   110559       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
   110560       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
   110561       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
   110562 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
   110563         break;
   110564       case 207: /* likeop ::= LIKE_KW */
   110565       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
   110566 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
   110567         break;
   110568       case 208: /* likeop ::= NOT LIKE_KW */
   110569       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
   110570 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
   110571         break;
   110572       case 211: /* expr ::= expr likeop expr */
   110573 {
   110574   ExprList *pList;
   110575   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
   110576   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
   110577   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
   110578   if( yymsp[-1].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110579   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
   110580   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110581   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
   110582 }
   110583         break;
   110584       case 212: /* expr ::= expr likeop expr ESCAPE expr */
   110585 {
   110586   ExprList *pList;
   110587   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110588   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
   110589   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
   110590   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
   110591   if( yymsp[-3].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110592   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110593   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110594   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
   110595 }
   110596         break;
   110597       case 213: /* expr ::= expr ISNULL|NOTNULL */
   110598 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
   110599         break;
   110600       case 214: /* expr ::= expr NOT NULL */
   110601 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
   110602         break;
   110603       case 215: /* expr ::= expr IS expr */
   110604 {
   110605   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
   110606   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
   110607 }
   110608         break;
   110609       case 216: /* expr ::= expr IS NOT expr */
   110610 {
   110611   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
   110612   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
   110613 }
   110614         break;
   110615       case 217: /* expr ::= NOT expr */
   110616       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
   110617 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110618         break;
   110619       case 219: /* expr ::= MINUS expr */
   110620 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110621         break;
   110622       case 220: /* expr ::= PLUS expr */
   110623 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110624         break;
   110625       case 223: /* expr ::= expr between_op expr AND expr */
   110626 {
   110627   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110628   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
   110629   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110630   if( yygotominor.yy342.pExpr ){
   110631     yygotominor.yy342.pExpr->x.pList = pList;
   110632   }else{
   110633     sqlite3ExprListDelete(pParse->db, pList);
   110634   }
   110635   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110636   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110637   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110638 }
   110639         break;
   110640       case 226: /* expr ::= expr in_op LP exprlist RP */
   110641 {
   110642     if( yymsp[-1].minor.yy442==0 ){
   110643       /* Expressions of the form
   110644       **
   110645       **      expr1 IN ()
   110646       **      expr1 NOT IN ()
   110647       **
   110648       ** simplify to constants 0 (false) and 1 (true), respectively,
   110649       ** regardless of the value of expr1.
   110650       */
   110651       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
   110652       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
   110653     }else{
   110654       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110655       if( yygotominor.yy342.pExpr ){
   110656         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
   110657         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110658       }else{
   110659         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
   110660       }
   110661       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110662     }
   110663     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110664     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110665   }
   110666         break;
   110667       case 227: /* expr ::= LP select RP */
   110668 {
   110669     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   110670     if( yygotominor.yy342.pExpr ){
   110671       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
   110672       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110673       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110674     }else{
   110675       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110676     }
   110677     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
   110678     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110679   }
   110680         break;
   110681       case 228: /* expr ::= expr in_op LP select RP */
   110682 {
   110683     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110684     if( yygotominor.yy342.pExpr ){
   110685       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
   110686       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110687       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110688     }else{
   110689       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110690     }
   110691     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110692     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110693     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110694   }
   110695         break;
   110696       case 229: /* expr ::= expr in_op nm dbnm */
   110697 {
   110698     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   110699     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
   110700     if( yygotominor.yy342.pExpr ){
   110701       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   110702       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110703       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110704     }else{
   110705       sqlite3SrcListDelete(pParse->db, pSrc);
   110706     }
   110707     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110708     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
   110709     yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
   110710   }
   110711         break;
   110712       case 230: /* expr ::= EXISTS LP select RP */
   110713 {
   110714     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   110715     if( p ){
   110716       p->x.pSelect = yymsp[-1].minor.yy159;
   110717       ExprSetProperty(p, EP_xIsSelect);
   110718       sqlite3ExprSetHeight(pParse, p);
   110719     }else{
   110720       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110721     }
   110722     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
   110723     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110724   }
   110725         break;
   110726       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
   110727 {
   110728   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
   110729   if( yygotominor.yy342.pExpr ){
   110730     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
   110731     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110732   }else{
   110733     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
   110734   }
   110735   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
   110736   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110737 }
   110738         break;
   110739       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   110740 {
   110741   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
   110742   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
   110743 }
   110744         break;
   110745       case 233: /* case_exprlist ::= WHEN expr THEN expr */
   110746 {
   110747   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110748   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
   110749 }
   110750         break;
   110751       case 240: /* nexprlist ::= nexprlist COMMA expr */
   110752 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
   110753         break;
   110754       case 241: /* nexprlist ::= expr */
   110755 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
   110756         break;
   110757       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
   110758 {
   110759   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
   110760                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
   110761                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
   110762 }
   110763         break;
   110764       case 243: /* uniqueflag ::= UNIQUE */
   110765       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
   110766 {yygotominor.yy392 = OE_Abort;}
   110767         break;
   110768       case 244: /* uniqueflag ::= */
   110769 {yygotominor.yy392 = OE_None;}
   110770         break;
   110771       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
   110772 {
   110773   Expr *p = 0;
   110774   if( yymsp[-1].minor.yy0.n>0 ){
   110775     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
   110776     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   110777   }
   110778   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
   110779   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
   110780   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
   110781   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110782 }
   110783         break;
   110784       case 248: /* idxlist ::= nm collate sortorder */
   110785 {
   110786   Expr *p = 0;
   110787   if( yymsp[-1].minor.yy0.n>0 ){
   110788     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
   110789     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   110790   }
   110791   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
   110792   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110793   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
   110794   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110795 }
   110796         break;
   110797       case 249: /* collate ::= */
   110798 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   110799         break;
   110800       case 251: /* cmd ::= DROP INDEX ifexists fullname */
   110801 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
   110802         break;
   110803       case 252: /* cmd ::= VACUUM */
   110804       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
   110805 {sqlite3Vacuum(pParse);}
   110806         break;
   110807       case 254: /* cmd ::= PRAGMA nm dbnm */
   110808 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   110809         break;
   110810       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   110811 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   110812         break;
   110813       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   110814 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   110815         break;
   110816       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   110817 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   110818         break;
   110819       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   110820 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   110821         break;
   110822       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   110823 {
   110824   Token all;
   110825   all.z = yymsp[-3].minor.yy0.z;
   110826   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   110827   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
   110828 }
   110829         break;
   110830       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   110831 {
   110832   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
   110833   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   110834 }
   110835         break;
   110836       case 270: /* trigger_time ::= BEFORE */
   110837       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
   110838 { yygotominor.yy392 = TK_BEFORE; }
   110839         break;
   110840       case 271: /* trigger_time ::= AFTER */
   110841 { yygotominor.yy392 = TK_AFTER;  }
   110842         break;
   110843       case 272: /* trigger_time ::= INSTEAD OF */
   110844 { yygotominor.yy392 = TK_INSTEAD;}
   110845         break;
   110846       case 274: /* trigger_event ::= DELETE|INSERT */
   110847       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
   110848 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
   110849         break;
   110850       case 276: /* trigger_event ::= UPDATE OF inscollist */
   110851 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
   110852         break;
   110853       case 279: /* when_clause ::= */
   110854       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
   110855 { yygotominor.yy122 = 0; }
   110856         break;
   110857       case 280: /* when_clause ::= WHEN expr */
   110858       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
   110859 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
   110860         break;
   110861       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   110862 {
   110863   assert( yymsp[-2].minor.yy327!=0 );
   110864   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
   110865   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
   110866   yygotominor.yy327 = yymsp[-2].minor.yy327;
   110867 }
   110868         break;
   110869       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
   110870 {
   110871   assert( yymsp[-1].minor.yy327!=0 );
   110872   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
   110873   yygotominor.yy327 = yymsp[-1].minor.yy327;
   110874 }
   110875         break;
   110876       case 284: /* trnm ::= nm DOT nm */
   110877 {
   110878   yygotominor.yy0 = yymsp[0].minor.yy0;
   110879   sqlite3ErrorMsg(pParse,
   110880         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   110881         "statements within triggers");
   110882 }
   110883         break;
   110884       case 286: /* tridxby ::= INDEXED BY nm */
   110885 {
   110886   sqlite3ErrorMsg(pParse,
   110887         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   110888         "within triggers");
   110889 }
   110890         break;
   110891       case 287: /* tridxby ::= NOT INDEXED */
   110892 {
   110893   sqlite3ErrorMsg(pParse,
   110894         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   110895         "within triggers");
   110896 }
   110897         break;
   110898       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   110899 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
   110900         break;
   110901       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
   110902 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
   110903         break;
   110904       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   110905 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
   110906         break;
   110907       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   110908 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
   110909         break;
   110910       case 292: /* trigger_cmd ::= select */
   110911 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
   110912         break;
   110913       case 293: /* expr ::= RAISE LP IGNORE RP */
   110914 {
   110915   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   110916   if( yygotominor.yy342.pExpr ){
   110917     yygotominor.yy342.pExpr->affinity = OE_Ignore;
   110918   }
   110919   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
   110920   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110921 }
   110922         break;
   110923       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
   110924 {
   110925   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   110926   if( yygotominor.yy342.pExpr ) {
   110927     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
   110928   }
   110929   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
   110930   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110931 }
   110932         break;
   110933       case 295: /* raisetype ::= ROLLBACK */
   110934 {yygotominor.yy392 = OE_Rollback;}
   110935         break;
   110936       case 297: /* raisetype ::= FAIL */
   110937 {yygotominor.yy392 = OE_Fail;}
   110938         break;
   110939       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
   110940 {
   110941   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
   110942 }
   110943         break;
   110944       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   110945 {
   110946   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
   110947 }
   110948         break;
   110949       case 300: /* cmd ::= DETACH database_kw_opt expr */
   110950 {
   110951   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
   110952 }
   110953         break;
   110954       case 305: /* cmd ::= REINDEX */
   110955 {sqlite3Reindex(pParse, 0, 0);}
   110956         break;
   110957       case 306: /* cmd ::= REINDEX nm dbnm */
   110958 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   110959         break;
   110960       case 307: /* cmd ::= ANALYZE */
   110961 {sqlite3Analyze(pParse, 0, 0);}
   110962         break;
   110963       case 308: /* cmd ::= ANALYZE nm dbnm */
   110964 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   110965         break;
   110966       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   110967 {
   110968   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
   110969 }
   110970         break;
   110971       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   110972 {
   110973   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   110974 }
   110975         break;
   110976       case 311: /* add_column_fullname ::= fullname */
   110977 {
   110978   pParse->db->lookaside.bEnabled = 0;
   110979   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
   110980 }
   110981         break;
   110982       case 314: /* cmd ::= create_vtab */
   110983 {sqlite3VtabFinishParse(pParse,0);}
   110984         break;
   110985       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
   110986 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   110987         break;
   110988       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   110989 {
   110990     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
   110991 }
   110992         break;
   110993       case 319: /* vtabarg ::= */
   110994 {sqlite3VtabArgInit(pParse);}
   110995         break;
   110996       case 321: /* vtabargtoken ::= ANY */
   110997       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
   110998       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
   110999 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   111000         break;
   111001       default:
   111002       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   111003       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   111004       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   111005       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   111006       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   111007       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   111008       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   111009       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   111010       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   111011       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   111012       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   111013       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
   111014       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
   111015       /* (44) type ::= */ yytestcase(yyruleno==44);
   111016       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
   111017       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
   111018       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
   111019       /* (54) carglist ::= */ yytestcase(yyruleno==54);
   111020       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
   111021       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
   111022       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
   111023       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
   111024       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
   111025       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
   111026       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
   111027       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
   111028       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
   111029       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
   111030       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
   111031       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
   111032       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
   111033       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
   111034       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
   111035       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
   111036       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
   111037       /* (324) anylist ::= */ yytestcase(yyruleno==324);
   111038       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
   111039       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
   111040         break;
   111041   };
   111042   yygoto = yyRuleInfo[yyruleno].lhs;
   111043   yysize = yyRuleInfo[yyruleno].nrhs;
   111044   yypParser->yyidx -= yysize;
   111045   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   111046   if( yyact < YYNSTATE ){
   111047 #ifdef NDEBUG
   111048     /* If we are not debugging and the reduce action popped at least
   111049     ** one element off the stack, then we can push the new element back
   111050     ** onto the stack here, and skip the stack overflow test in yy_shift().
   111051     ** That gives a significant speed improvement. */
   111052     if( yysize ){
   111053       yypParser->yyidx++;
   111054       yymsp -= yysize-1;
   111055       yymsp->stateno = (YYACTIONTYPE)yyact;
   111056       yymsp->major = (YYCODETYPE)yygoto;
   111057       yymsp->minor = yygotominor;
   111058     }else
   111059 #endif
   111060     {
   111061       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   111062     }
   111063   }else{
   111064     assert( yyact == YYNSTATE + YYNRULE + 1 );
   111065     yy_accept(yypParser);
   111066   }
   111067 }
   111068 
   111069 /*
   111070 ** The following code executes when the parse fails
   111071 */
   111072 #ifndef YYNOERRORRECOVERY
   111073 static void yy_parse_failed(
   111074   yyParser *yypParser           /* The parser */
   111075 ){
   111076   sqlite3ParserARG_FETCH;
   111077 #ifndef NDEBUG
   111078   if( yyTraceFILE ){
   111079     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   111080   }
   111081 #endif
   111082   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   111083   /* Here code is inserted which will be executed whenever the
   111084   ** parser fails */
   111085   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111086 }
   111087 #endif /* YYNOERRORRECOVERY */
   111088 
   111089 /*
   111090 ** The following code executes when a syntax error first occurs.
   111091 */
   111092 static void yy_syntax_error(
   111093   yyParser *yypParser,           /* The parser */
   111094   int yymajor,                   /* The major type of the error token */
   111095   YYMINORTYPE yyminor            /* The minor type of the error token */
   111096 ){
   111097   sqlite3ParserARG_FETCH;
   111098 #define TOKEN (yyminor.yy0)
   111099 
   111100   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   111101   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   111102   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   111103   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111104 }
   111105 
   111106 /*
   111107 ** The following is executed when the parser accepts
   111108 */
   111109 static void yy_accept(
   111110   yyParser *yypParser           /* The parser */
   111111 ){
   111112   sqlite3ParserARG_FETCH;
   111113 #ifndef NDEBUG
   111114   if( yyTraceFILE ){
   111115     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   111116   }
   111117 #endif
   111118   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   111119   /* Here code is inserted which will be executed whenever the
   111120   ** parser accepts */
   111121   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111122 }
   111123 
   111124 /* The main parser program.
   111125 ** The first argument is a pointer to a structure obtained from
   111126 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   111127 ** The second argument is the major token number.  The third is
   111128 ** the minor token.  The fourth optional argument is whatever the
   111129 ** user wants (and specified in the grammar) and is available for
   111130 ** use by the action routines.
   111131 **
   111132 ** Inputs:
   111133 ** <ul>
   111134 ** <li> A pointer to the parser (an opaque structure.)
   111135 ** <li> The major token number.
   111136 ** <li> The minor token number.
   111137 ** <li> An option argument of a grammar-specified type.
   111138 ** </ul>
   111139 **
   111140 ** Outputs:
   111141 ** None.
   111142 */
   111143 SQLITE_PRIVATE void sqlite3Parser(
   111144   void *yyp,                   /* The parser */
   111145   int yymajor,                 /* The major token code number */
   111146   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   111147   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   111148 ){
   111149   YYMINORTYPE yyminorunion;
   111150   int yyact;            /* The parser action. */
   111151 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   111152   int yyendofinput;     /* True if we are at the end of input */
   111153 #endif
   111154 #ifdef YYERRORSYMBOL
   111155   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   111156 #endif
   111157   yyParser *yypParser;  /* The parser */
   111158 
   111159   /* (re)initialize the parser, if necessary */
   111160   yypParser = (yyParser*)yyp;
   111161   if( yypParser->yyidx<0 ){
   111162 #if YYSTACKDEPTH<=0
   111163     if( yypParser->yystksz <=0 ){
   111164       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   111165       yyminorunion = yyzerominor;
   111166       yyStackOverflow(yypParser, &yyminorunion);
   111167       return;
   111168     }
   111169 #endif
   111170     yypParser->yyidx = 0;
   111171     yypParser->yyerrcnt = -1;
   111172     yypParser->yystack[0].stateno = 0;
   111173     yypParser->yystack[0].major = 0;
   111174   }
   111175   yyminorunion.yy0 = yyminor;
   111176 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   111177   yyendofinput = (yymajor==0);
   111178 #endif
   111179   sqlite3ParserARG_STORE;
   111180 
   111181 #ifndef NDEBUG
   111182   if( yyTraceFILE ){
   111183     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   111184   }
   111185 #endif
   111186 
   111187   do{
   111188     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   111189     if( yyact<YYNSTATE ){
   111190       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   111191       yypParser->yyerrcnt--;
   111192       yymajor = YYNOCODE;
   111193     }else if( yyact < YYNSTATE + YYNRULE ){
   111194       yy_reduce(yypParser,yyact-YYNSTATE);
   111195     }else{
   111196       assert( yyact == YY_ERROR_ACTION );
   111197 #ifdef YYERRORSYMBOL
   111198       int yymx;
   111199 #endif
   111200 #ifndef NDEBUG
   111201       if( yyTraceFILE ){
   111202         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   111203       }
   111204 #endif
   111205 #ifdef YYERRORSYMBOL
   111206       /* A syntax error has occurred.
   111207       ** The response to an error depends upon whether or not the
   111208       ** grammar defines an error token "ERROR".
   111209       **
   111210       ** This is what we do if the grammar does define ERROR:
   111211       **
   111212       **  * Call the %syntax_error function.
   111213       **
   111214       **  * Begin popping the stack until we enter a state where
   111215       **    it is legal to shift the error symbol, then shift
   111216       **    the error symbol.
   111217       **
   111218       **  * Set the error count to three.
   111219       **
   111220       **  * Begin accepting and shifting new tokens.  No new error
   111221       **    processing will occur until three tokens have been
   111222       **    shifted successfully.
   111223       **
   111224       */
   111225       if( yypParser->yyerrcnt<0 ){
   111226         yy_syntax_error(yypParser,yymajor,yyminorunion);
   111227       }
   111228       yymx = yypParser->yystack[yypParser->yyidx].major;
   111229       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   111230 #ifndef NDEBUG
   111231         if( yyTraceFILE ){
   111232           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   111233              yyTracePrompt,yyTokenName[yymajor]);
   111234         }
   111235 #endif
   111236         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   111237         yymajor = YYNOCODE;
   111238       }else{
   111239          while(
   111240           yypParser->yyidx >= 0 &&
   111241           yymx != YYERRORSYMBOL &&
   111242           (yyact = yy_find_reduce_action(
   111243                         yypParser->yystack[yypParser->yyidx].stateno,
   111244                         YYERRORSYMBOL)) >= YYNSTATE
   111245         ){
   111246           yy_pop_parser_stack(yypParser);
   111247         }
   111248         if( yypParser->yyidx < 0 || yymajor==0 ){
   111249           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111250           yy_parse_failed(yypParser);
   111251           yymajor = YYNOCODE;
   111252         }else if( yymx!=YYERRORSYMBOL ){
   111253           YYMINORTYPE u2;
   111254           u2.YYERRSYMDT = 0;
   111255           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   111256         }
   111257       }
   111258       yypParser->yyerrcnt = 3;
   111259       yyerrorhit = 1;
   111260 #elif defined(YYNOERRORRECOVERY)
   111261       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   111262       ** do any kind of error recovery.  Instead, simply invoke the syntax
   111263       ** error routine and continue going as if nothing had happened.
   111264       **
   111265       ** Applications can set this macro (for example inside %include) if
   111266       ** they intend to abandon the parse upon the first syntax error seen.
   111267       */
   111268       yy_syntax_error(yypParser,yymajor,yyminorunion);
   111269       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111270       yymajor = YYNOCODE;
   111271 
   111272 #else  /* YYERRORSYMBOL is not defined */
   111273       /* This is what we do if the grammar does not define ERROR:
   111274       **
   111275       **  * Report an error message, and throw away the input token.
   111276       **
   111277       **  * If the input token is $, then fail the parse.
   111278       **
   111279       ** As before, subsequent error messages are suppressed until
   111280       ** three input tokens have been successfully shifted.
   111281       */
   111282       if( yypParser->yyerrcnt<=0 ){
   111283         yy_syntax_error(yypParser,yymajor,yyminorunion);
   111284       }
   111285       yypParser->yyerrcnt = 3;
   111286       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111287       if( yyendofinput ){
   111288         yy_parse_failed(yypParser);
   111289       }
   111290       yymajor = YYNOCODE;
   111291 #endif
   111292     }
   111293   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   111294   return;
   111295 }
   111296 
   111297 /************** End of parse.c ***********************************************/
   111298 /************** Begin file tokenize.c ****************************************/
   111299 /*
   111300 ** 2001 September 15
   111301 **
   111302 ** The author disclaims copyright to this source code.  In place of
   111303 ** a legal notice, here is a blessing:
   111304 **
   111305 **    May you do good and not evil.
   111306 **    May you find forgiveness for yourself and forgive others.
   111307 **    May you share freely, never taking more than you give.
   111308 **
   111309 *************************************************************************
   111310 ** An tokenizer for SQL
   111311 **
   111312 ** This file contains C code that splits an SQL input string up into
   111313 ** individual tokens and sends those tokens one-by-one over to the
   111314 ** parser for analysis.
   111315 */
   111316 /* #include <stdlib.h> */
   111317 
   111318 /*
   111319 ** The charMap() macro maps alphabetic characters into their
   111320 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   111321 ** an upper-to-lower case map.  On EBCDIC machines we also need
   111322 ** to adjust the encoding.  Only alphabetic characters and underscores
   111323 ** need to be translated.
   111324 */
   111325 #ifdef SQLITE_ASCII
   111326 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   111327 #endif
   111328 #ifdef SQLITE_EBCDIC
   111329 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   111330 const unsigned char ebcdicToAscii[] = {
   111331 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   111332    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   111333    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   111334    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   111335    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   111336    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   111337    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   111338    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   111339    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   111340    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   111341    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   111342    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   111343    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   111344    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   111345    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   111346    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   111347    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   111348 };
   111349 #endif
   111350 
   111351 /*
   111352 ** The sqlite3KeywordCode function looks up an identifier to determine if
   111353 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   111354 ** returned.  If the input is not a keyword, TK_ID is returned.
   111355 **
   111356 ** The implementation of this routine was generated by a program,
   111357 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   111358 ** The output of the mkkeywordhash.c program is written into a file
   111359 ** named keywordhash.h and then included into this source file by
   111360 ** the #include below.
   111361 */
   111362 /************** Include keywordhash.h in the middle of tokenize.c ************/
   111363 /************** Begin file keywordhash.h *************************************/
   111364 /***** This file contains automatically generated code ******
   111365 **
   111366 ** The code in this file has been automatically generated by
   111367 **
   111368 **   sqlite/tool/mkkeywordhash.c
   111369 **
   111370 ** The code in this file implements a function that determines whether
   111371 ** or not a given identifier is really an SQL keyword.  The same thing
   111372 ** might be implemented more directly using a hand-written hash table.
   111373 ** But by using this automatically generated code, the size of the code
   111374 ** is substantially reduced.  This is important for embedded applications
   111375 ** on platforms with limited memory.
   111376 */
   111377 /* Hash score: 175 */
   111378 static int keywordCode(const char *z, int n){
   111379   /* zText[] encodes 811 bytes of keywords in 541 bytes */
   111380   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   111381   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   111382   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   111383   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
   111384   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
   111385   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
   111386   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
   111387   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
   111388   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
   111389   /*   INITIALLY                                                          */
   111390   static const char zText[540] = {
   111391     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   111392     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   111393     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   111394     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   111395     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   111396     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   111397     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   111398     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   111399     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   111400     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   111401     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
   111402     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
   111403     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
   111404     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
   111405     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
   111406     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
   111407     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
   111408     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
   111409     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
   111410     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
   111411     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
   111412     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
   111413     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
   111414     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
   111415     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
   111416     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
   111417     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
   111418     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
   111419     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
   111420     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
   111421   };
   111422   static const unsigned char aHash[127] = {
   111423       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
   111424       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
   111425      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
   111426        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
   111427        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
   111428       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
   111429       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
   111430       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
   111431       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
   111432       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
   111433   };
   111434   static const unsigned char aNext[121] = {
   111435        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   111436        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   111437        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   111438        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
   111439        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
   111440       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
   111441       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
   111442        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
   111443      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
   111444       35,  64,   0,   0,
   111445   };
   111446   static const unsigned char aLen[121] = {
   111447        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   111448        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   111449       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   111450        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
   111451        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
   111452        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
   111453        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
   111454        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
   111455        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
   111456        6,   4,   9,   3,
   111457   };
   111458   static const unsigned short int aOffset[121] = {
   111459        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   111460       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   111461       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   111462      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
   111463      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
   111464      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
   111465      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
   111466      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
   111467      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
   111468      521, 527, 531, 536,
   111469   };
   111470   static const unsigned char aCode[121] = {
   111471     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   111472     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   111473     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   111474     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   111475     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   111476     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   111477     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   111478     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   111479     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   111480     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
   111481     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
   111482     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
   111483     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
   111484     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
   111485     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
   111486     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
   111487     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
   111488     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
   111489     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
   111490     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
   111491     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
   111492     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
   111493     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
   111494     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
   111495     TK_ALL,
   111496   };
   111497   int h, i;
   111498   if( n<2 ) return TK_ID;
   111499   h = ((charMap(z[0])*4) ^
   111500       (charMap(z[n-1])*3) ^
   111501       n) % 127;
   111502   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   111503     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   111504       testcase( i==0 ); /* REINDEX */
   111505       testcase( i==1 ); /* INDEXED */
   111506       testcase( i==2 ); /* INDEX */
   111507       testcase( i==3 ); /* DESC */
   111508       testcase( i==4 ); /* ESCAPE */
   111509       testcase( i==5 ); /* EACH */
   111510       testcase( i==6 ); /* CHECK */
   111511       testcase( i==7 ); /* KEY */
   111512       testcase( i==8 ); /* BEFORE */
   111513       testcase( i==9 ); /* FOREIGN */
   111514       testcase( i==10 ); /* FOR */
   111515       testcase( i==11 ); /* IGNORE */
   111516       testcase( i==12 ); /* REGEXP */
   111517       testcase( i==13 ); /* EXPLAIN */
   111518       testcase( i==14 ); /* INSTEAD */
   111519       testcase( i==15 ); /* ADD */
   111520       testcase( i==16 ); /* DATABASE */
   111521       testcase( i==17 ); /* AS */
   111522       testcase( i==18 ); /* SELECT */
   111523       testcase( i==19 ); /* TABLE */
   111524       testcase( i==20 ); /* LEFT */
   111525       testcase( i==21 ); /* THEN */
   111526       testcase( i==22 ); /* END */
   111527       testcase( i==23 ); /* DEFERRABLE */
   111528       testcase( i==24 ); /* ELSE */
   111529       testcase( i==25 ); /* EXCEPT */
   111530       testcase( i==26 ); /* TRANSACTION */
   111531       testcase( i==27 ); /* ACTION */
   111532       testcase( i==28 ); /* ON */
   111533       testcase( i==29 ); /* NATURAL */
   111534       testcase( i==30 ); /* ALTER */
   111535       testcase( i==31 ); /* RAISE */
   111536       testcase( i==32 ); /* EXCLUSIVE */
   111537       testcase( i==33 ); /* EXISTS */
   111538       testcase( i==34 ); /* SAVEPOINT */
   111539       testcase( i==35 ); /* INTERSECT */
   111540       testcase( i==36 ); /* TRIGGER */
   111541       testcase( i==37 ); /* REFERENCES */
   111542       testcase( i==38 ); /* CONSTRAINT */
   111543       testcase( i==39 ); /* INTO */
   111544       testcase( i==40 ); /* OFFSET */
   111545       testcase( i==41 ); /* OF */
   111546       testcase( i==42 ); /* SET */
   111547       testcase( i==43 ); /* TEMPORARY */
   111548       testcase( i==44 ); /* TEMP */
   111549       testcase( i==45 ); /* OR */
   111550       testcase( i==46 ); /* UNIQUE */
   111551       testcase( i==47 ); /* QUERY */
   111552       testcase( i==48 ); /* ATTACH */
   111553       testcase( i==49 ); /* HAVING */
   111554       testcase( i==50 ); /* GROUP */
   111555       testcase( i==51 ); /* UPDATE */
   111556       testcase( i==52 ); /* BEGIN */
   111557       testcase( i==53 ); /* INNER */
   111558       testcase( i==54 ); /* RELEASE */
   111559       testcase( i==55 ); /* BETWEEN */
   111560       testcase( i==56 ); /* NOTNULL */
   111561       testcase( i==57 ); /* NOT */
   111562       testcase( i==58 ); /* NO */
   111563       testcase( i==59 ); /* NULL */
   111564       testcase( i==60 ); /* LIKE */
   111565       testcase( i==61 ); /* CASCADE */
   111566       testcase( i==62 ); /* ASC */
   111567       testcase( i==63 ); /* DELETE */
   111568       testcase( i==64 ); /* CASE */
   111569       testcase( i==65 ); /* COLLATE */
   111570       testcase( i==66 ); /* CREATE */
   111571       testcase( i==67 ); /* CURRENT_DATE */
   111572       testcase( i==68 ); /* DETACH */
   111573       testcase( i==69 ); /* IMMEDIATE */
   111574       testcase( i==70 ); /* JOIN */
   111575       testcase( i==71 ); /* INSERT */
   111576       testcase( i==72 ); /* MATCH */
   111577       testcase( i==73 ); /* PLAN */
   111578       testcase( i==74 ); /* ANALYZE */
   111579       testcase( i==75 ); /* PRAGMA */
   111580       testcase( i==76 ); /* ABORT */
   111581       testcase( i==77 ); /* VALUES */
   111582       testcase( i==78 ); /* VIRTUAL */
   111583       testcase( i==79 ); /* LIMIT */
   111584       testcase( i==80 ); /* WHEN */
   111585       testcase( i==81 ); /* WHERE */
   111586       testcase( i==82 ); /* RENAME */
   111587       testcase( i==83 ); /* AFTER */
   111588       testcase( i==84 ); /* REPLACE */
   111589       testcase( i==85 ); /* AND */
   111590       testcase( i==86 ); /* DEFAULT */
   111591       testcase( i==87 ); /* AUTOINCREMENT */
   111592       testcase( i==88 ); /* TO */
   111593       testcase( i==89 ); /* IN */
   111594       testcase( i==90 ); /* CAST */
   111595       testcase( i==91 ); /* COLUMN */
   111596       testcase( i==92 ); /* COMMIT */
   111597       testcase( i==93 ); /* CONFLICT */
   111598       testcase( i==94 ); /* CROSS */
   111599       testcase( i==95 ); /* CURRENT_TIMESTAMP */
   111600       testcase( i==96 ); /* CURRENT_TIME */
   111601       testcase( i==97 ); /* PRIMARY */
   111602       testcase( i==98 ); /* DEFERRED */
   111603       testcase( i==99 ); /* DISTINCT */
   111604       testcase( i==100 ); /* IS */
   111605       testcase( i==101 ); /* DROP */
   111606       testcase( i==102 ); /* FAIL */
   111607       testcase( i==103 ); /* FROM */
   111608       testcase( i==104 ); /* FULL */
   111609       testcase( i==105 ); /* GLOB */
   111610       testcase( i==106 ); /* BY */
   111611       testcase( i==107 ); /* IF */
   111612       testcase( i==108 ); /* ISNULL */
   111613       testcase( i==109 ); /* ORDER */
   111614       testcase( i==110 ); /* RESTRICT */
   111615       testcase( i==111 ); /* OUTER */
   111616       testcase( i==112 ); /* RIGHT */
   111617       testcase( i==113 ); /* ROLLBACK */
   111618       testcase( i==114 ); /* ROW */
   111619       testcase( i==115 ); /* UNION */
   111620       testcase( i==116 ); /* USING */
   111621       testcase( i==117 ); /* VACUUM */
   111622       testcase( i==118 ); /* VIEW */
   111623       testcase( i==119 ); /* INITIALLY */
   111624       testcase( i==120 ); /* ALL */
   111625       return aCode[i];
   111626     }
   111627   }
   111628   return TK_ID;
   111629 }
   111630 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   111631   return keywordCode((char*)z, n);
   111632 }
   111633 #define SQLITE_N_KEYWORD 121
   111634 
   111635 /************** End of keywordhash.h *****************************************/
   111636 /************** Continuing where we left off in tokenize.c *******************/
   111637 
   111638 
   111639 /*
   111640 ** If X is a character that can be used in an identifier then
   111641 ** IdChar(X) will be true.  Otherwise it is false.
   111642 **
   111643 ** For ASCII, any character with the high-order bit set is
   111644 ** allowed in an identifier.  For 7-bit characters,
   111645 ** sqlite3IsIdChar[X] must be 1.
   111646 **
   111647 ** For EBCDIC, the rules are more complex but have the same
   111648 ** end result.
   111649 **
   111650 ** Ticket #1066.  the SQL standard does not allow '$' in the
   111651 ** middle of identfiers.  But many SQL implementations do.
   111652 ** SQLite will allow '$' in identifiers for compatibility.
   111653 ** But the feature is undocumented.
   111654 */
   111655 #ifdef SQLITE_ASCII
   111656 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   111657 #endif
   111658 #ifdef SQLITE_EBCDIC
   111659 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   111660 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   111661     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   111662     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   111663     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   111664     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   111665     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   111666     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   111667     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   111668     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   111669     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   111670     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   111671     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   111672     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   111673 };
   111674 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   111675 #endif
   111676 
   111677 
   111678 /*
   111679 ** Return the length of the token that begins at z[0].
   111680 ** Store the token type in *tokenType before returning.
   111681 */
   111682 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   111683   int i, c;
   111684   switch( *z ){
   111685     case ' ': case '\t': case '\n': case '\f': case '\r': {
   111686       testcase( z[0]==' ' );
   111687       testcase( z[0]=='\t' );
   111688       testcase( z[0]=='\n' );
   111689       testcase( z[0]=='\f' );
   111690       testcase( z[0]=='\r' );
   111691       for(i=1; sqlite3Isspace(z[i]); i++){}
   111692       *tokenType = TK_SPACE;
   111693       return i;
   111694     }
   111695     case '-': {
   111696       if( z[1]=='-' ){
   111697         /* IMP: R-50417-27976 -- syntax diagram for comments */
   111698         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   111699         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   111700         return i;
   111701       }
   111702       *tokenType = TK_MINUS;
   111703       return 1;
   111704     }
   111705     case '(': {
   111706       *tokenType = TK_LP;
   111707       return 1;
   111708     }
   111709     case ')': {
   111710       *tokenType = TK_RP;
   111711       return 1;
   111712     }
   111713     case ';': {
   111714       *tokenType = TK_SEMI;
   111715       return 1;
   111716     }
   111717     case '+': {
   111718       *tokenType = TK_PLUS;
   111719       return 1;
   111720     }
   111721     case '*': {
   111722       *tokenType = TK_STAR;
   111723       return 1;
   111724     }
   111725     case '/': {
   111726       if( z[1]!='*' || z[2]==0 ){
   111727         *tokenType = TK_SLASH;
   111728         return 1;
   111729       }
   111730       /* IMP: R-50417-27976 -- syntax diagram for comments */
   111731       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   111732       if( c ) i++;
   111733       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   111734       return i;
   111735     }
   111736     case '%': {
   111737       *tokenType = TK_REM;
   111738       return 1;
   111739     }
   111740     case '=': {
   111741       *tokenType = TK_EQ;
   111742       return 1 + (z[1]=='=');
   111743     }
   111744     case '<': {
   111745       if( (c=z[1])=='=' ){
   111746         *tokenType = TK_LE;
   111747         return 2;
   111748       }else if( c=='>' ){
   111749         *tokenType = TK_NE;
   111750         return 2;
   111751       }else if( c=='<' ){
   111752         *tokenType = TK_LSHIFT;
   111753         return 2;
   111754       }else{
   111755         *tokenType = TK_LT;
   111756         return 1;
   111757       }
   111758     }
   111759     case '>': {
   111760       if( (c=z[1])=='=' ){
   111761         *tokenType = TK_GE;
   111762         return 2;
   111763       }else if( c=='>' ){
   111764         *tokenType = TK_RSHIFT;
   111765         return 2;
   111766       }else{
   111767         *tokenType = TK_GT;
   111768         return 1;
   111769       }
   111770     }
   111771     case '!': {
   111772       if( z[1]!='=' ){
   111773         *tokenType = TK_ILLEGAL;
   111774         return 2;
   111775       }else{
   111776         *tokenType = TK_NE;
   111777         return 2;
   111778       }
   111779     }
   111780     case '|': {
   111781       if( z[1]!='|' ){
   111782         *tokenType = TK_BITOR;
   111783         return 1;
   111784       }else{
   111785         *tokenType = TK_CONCAT;
   111786         return 2;
   111787       }
   111788     }
   111789     case ',': {
   111790       *tokenType = TK_COMMA;
   111791       return 1;
   111792     }
   111793     case '&': {
   111794       *tokenType = TK_BITAND;
   111795       return 1;
   111796     }
   111797     case '~': {
   111798       *tokenType = TK_BITNOT;
   111799       return 1;
   111800     }
   111801     case '`':
   111802     case '\'':
   111803     case '"': {
   111804       int delim = z[0];
   111805       testcase( delim=='`' );
   111806       testcase( delim=='\'' );
   111807       testcase( delim=='"' );
   111808       for(i=1; (c=z[i])!=0; i++){
   111809         if( c==delim ){
   111810           if( z[i+1]==delim ){
   111811             i++;
   111812           }else{
   111813             break;
   111814           }
   111815         }
   111816       }
   111817       if( c=='\'' ){
   111818         *tokenType = TK_STRING;
   111819         return i+1;
   111820       }else if( c!=0 ){
   111821         *tokenType = TK_ID;
   111822         return i+1;
   111823       }else{
   111824         *tokenType = TK_ILLEGAL;
   111825         return i;
   111826       }
   111827     }
   111828     case '.': {
   111829 #ifndef SQLITE_OMIT_FLOATING_POINT
   111830       if( !sqlite3Isdigit(z[1]) )
   111831 #endif
   111832       {
   111833         *tokenType = TK_DOT;
   111834         return 1;
   111835       }
   111836       /* If the next character is a digit, this is a floating point
   111837       ** number that begins with ".".  Fall thru into the next case */
   111838     }
   111839     case '0': case '1': case '2': case '3': case '4':
   111840     case '5': case '6': case '7': case '8': case '9': {
   111841       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   111842       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   111843       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   111844       testcase( z[0]=='9' );
   111845       *tokenType = TK_INTEGER;
   111846       for(i=0; sqlite3Isdigit(z[i]); i++){}
   111847 #ifndef SQLITE_OMIT_FLOATING_POINT
   111848       if( z[i]=='.' ){
   111849         i++;
   111850         while( sqlite3Isdigit(z[i]) ){ i++; }
   111851         *tokenType = TK_FLOAT;
   111852       }
   111853       if( (z[i]=='e' || z[i]=='E') &&
   111854            ( sqlite3Isdigit(z[i+1])
   111855             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   111856            )
   111857       ){
   111858         i += 2;
   111859         while( sqlite3Isdigit(z[i]) ){ i++; }
   111860         *tokenType = TK_FLOAT;
   111861       }
   111862 #endif
   111863       while( IdChar(z[i]) ){
   111864         *tokenType = TK_ILLEGAL;
   111865         i++;
   111866       }
   111867       return i;
   111868     }
   111869     case '[': {
   111870       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   111871       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   111872       return i;
   111873     }
   111874     case '?': {
   111875       *tokenType = TK_VARIABLE;
   111876       for(i=1; sqlite3Isdigit(z[i]); i++){}
   111877       return i;
   111878     }
   111879     case '#': {
   111880       for(i=1; sqlite3Isdigit(z[i]); i++){}
   111881       if( i>1 ){
   111882         /* Parameters of the form #NNN (where NNN is a number) are used
   111883         ** internally by sqlite3NestedParse.  */
   111884         *tokenType = TK_REGISTER;
   111885         return i;
   111886       }
   111887       /* Fall through into the next case if the '#' is not followed by
   111888       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
   111889     }
   111890 #ifndef SQLITE_OMIT_TCL_VARIABLE
   111891     case '$':
   111892 #endif
   111893     case '@':  /* For compatibility with MS SQL Server */
   111894     case ':': {
   111895       int n = 0;
   111896       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
   111897       *tokenType = TK_VARIABLE;
   111898       for(i=1; (c=z[i])!=0; i++){
   111899         if( IdChar(c) ){
   111900           n++;
   111901 #ifndef SQLITE_OMIT_TCL_VARIABLE
   111902         }else if( c=='(' && n>0 ){
   111903           do{
   111904             i++;
   111905           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   111906           if( c==')' ){
   111907             i++;
   111908           }else{
   111909             *tokenType = TK_ILLEGAL;
   111910           }
   111911           break;
   111912         }else if( c==':' && z[i+1]==':' ){
   111913           i++;
   111914 #endif
   111915         }else{
   111916           break;
   111917         }
   111918       }
   111919       if( n==0 ) *tokenType = TK_ILLEGAL;
   111920       return i;
   111921     }
   111922 #ifndef SQLITE_OMIT_BLOB_LITERAL
   111923     case 'x': case 'X': {
   111924       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   111925       if( z[1]=='\'' ){
   111926         *tokenType = TK_BLOB;
   111927         for(i=2; sqlite3Isxdigit(z[i]); i++){}
   111928         if( z[i]!='\'' || i%2 ){
   111929           *tokenType = TK_ILLEGAL;
   111930           while( z[i] && z[i]!='\'' ){ i++; }
   111931         }
   111932         if( z[i] ) i++;
   111933         return i;
   111934       }
   111935       /* Otherwise fall through to the next case */
   111936     }
   111937 #endif
   111938     default: {
   111939       if( !IdChar(*z) ){
   111940         break;
   111941       }
   111942       for(i=1; IdChar(z[i]); i++){}
   111943       *tokenType = keywordCode((char*)z, i);
   111944       return i;
   111945     }
   111946   }
   111947   *tokenType = TK_ILLEGAL;
   111948   return 1;
   111949 }
   111950 
   111951 /*
   111952 ** Run the parser on the given SQL string.  The parser structure is
   111953 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   111954 ** then an and attempt is made to write an error message into
   111955 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   111956 ** error message.
   111957 */
   111958 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   111959   int nErr = 0;                   /* Number of errors encountered */
   111960   int i;                          /* Loop counter */
   111961   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   111962   int tokenType;                  /* type of the next token */
   111963   int lastTokenParsed = -1;       /* type of the previous token */
   111964   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   111965   sqlite3 *db = pParse->db;       /* The database connection */
   111966   int mxSqlLen;                   /* Max length of an SQL string */
   111967 
   111968 
   111969   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   111970   if( db->activeVdbeCnt==0 ){
   111971     db->u1.isInterrupted = 0;
   111972   }
   111973   pParse->rc = SQLITE_OK;
   111974   pParse->zTail = zSql;
   111975   i = 0;
   111976   assert( pzErrMsg!=0 );
   111977   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   111978   if( pEngine==0 ){
   111979     db->mallocFailed = 1;
   111980     return SQLITE_NOMEM;
   111981   }
   111982   assert( pParse->pNewTable==0 );
   111983   assert( pParse->pNewTrigger==0 );
   111984   assert( pParse->nVar==0 );
   111985   assert( pParse->nzVar==0 );
   111986   assert( pParse->azVar==0 );
   111987   enableLookaside = db->lookaside.bEnabled;
   111988   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   111989   while( !db->mallocFailed && zSql[i]!=0 ){
   111990     assert( i>=0 );
   111991     pParse->sLastToken.z = &zSql[i];
   111992     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   111993     i += pParse->sLastToken.n;
   111994     if( i>mxSqlLen ){
   111995       pParse->rc = SQLITE_TOOBIG;
   111996       break;
   111997     }
   111998     switch( tokenType ){
   111999       case TK_SPACE: {
   112000         if( db->u1.isInterrupted ){
   112001           sqlite3ErrorMsg(pParse, "interrupt");
   112002           pParse->rc = SQLITE_INTERRUPT;
   112003           goto abort_parse;
   112004         }
   112005         break;
   112006       }
   112007       case TK_ILLEGAL: {
   112008         sqlite3DbFree(db, *pzErrMsg);
   112009         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   112010                         &pParse->sLastToken);
   112011         nErr++;
   112012         goto abort_parse;
   112013       }
   112014       case TK_SEMI: {
   112015         pParse->zTail = &zSql[i];
   112016         /* Fall thru into the default case */
   112017       }
   112018       default: {
   112019         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   112020         lastTokenParsed = tokenType;
   112021         if( pParse->rc!=SQLITE_OK ){
   112022           goto abort_parse;
   112023         }
   112024         break;
   112025       }
   112026     }
   112027   }
   112028 abort_parse:
   112029   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   112030     if( lastTokenParsed!=TK_SEMI ){
   112031       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   112032       pParse->zTail = &zSql[i];
   112033     }
   112034     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   112035   }
   112036 #ifdef YYTRACKMAXSTACKDEPTH
   112037   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   112038       sqlite3ParserStackPeak(pEngine)
   112039   );
   112040 #endif /* YYDEBUG */
   112041   sqlite3ParserFree(pEngine, sqlite3_free);
   112042   db->lookaside.bEnabled = enableLookaside;
   112043   if( db->mallocFailed ){
   112044     pParse->rc = SQLITE_NOMEM;
   112045   }
   112046   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   112047     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   112048   }
   112049   assert( pzErrMsg!=0 );
   112050   if( pParse->zErrMsg ){
   112051     *pzErrMsg = pParse->zErrMsg;
   112052     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   112053     pParse->zErrMsg = 0;
   112054     nErr++;
   112055   }
   112056   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   112057     sqlite3VdbeDelete(pParse->pVdbe);
   112058     pParse->pVdbe = 0;
   112059   }
   112060 #ifndef SQLITE_OMIT_SHARED_CACHE
   112061   if( pParse->nested==0 ){
   112062     sqlite3DbFree(db, pParse->aTableLock);
   112063     pParse->aTableLock = 0;
   112064     pParse->nTableLock = 0;
   112065   }
   112066 #endif
   112067 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112068   sqlite3_free(pParse->apVtabLock);
   112069 #endif
   112070 
   112071   if( !IN_DECLARE_VTAB ){
   112072     /* If the pParse->declareVtab flag is set, do not delete any table
   112073     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   112074     ** will take responsibility for freeing the Table structure.
   112075     */
   112076     sqlite3DeleteTable(db, pParse->pNewTable);
   112077   }
   112078 
   112079   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   112080   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
   112081   sqlite3DbFree(db, pParse->azVar);
   112082   sqlite3DbFree(db, pParse->aAlias);
   112083   while( pParse->pAinc ){
   112084     AutoincInfo *p = pParse->pAinc;
   112085     pParse->pAinc = p->pNext;
   112086     sqlite3DbFree(db, p);
   112087   }
   112088   while( pParse->pZombieTab ){
   112089     Table *p = pParse->pZombieTab;
   112090     pParse->pZombieTab = p->pNextZombie;
   112091     sqlite3DeleteTable(db, p);
   112092   }
   112093   if( nErr>0 && pParse->rc==SQLITE_OK ){
   112094     pParse->rc = SQLITE_ERROR;
   112095   }
   112096   return nErr;
   112097 }
   112098 
   112099 /************** End of tokenize.c ********************************************/
   112100 /************** Begin file complete.c ****************************************/
   112101 /*
   112102 ** 2001 September 15
   112103 **
   112104 ** The author disclaims copyright to this source code.  In place of
   112105 ** a legal notice, here is a blessing:
   112106 **
   112107 **    May you do good and not evil.
   112108 **    May you find forgiveness for yourself and forgive others.
   112109 **    May you share freely, never taking more than you give.
   112110 **
   112111 *************************************************************************
   112112 ** An tokenizer for SQL
   112113 **
   112114 ** This file contains C code that implements the sqlite3_complete() API.
   112115 ** This code used to be part of the tokenizer.c source file.  But by
   112116 ** separating it out, the code will be automatically omitted from
   112117 ** static links that do not use it.
   112118 */
   112119 #ifndef SQLITE_OMIT_COMPLETE
   112120 
   112121 /*
   112122 ** This is defined in tokenize.c.  We just have to import the definition.
   112123 */
   112124 #ifndef SQLITE_AMALGAMATION
   112125 #ifdef SQLITE_ASCII
   112126 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   112127 #endif
   112128 #ifdef SQLITE_EBCDIC
   112129 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   112130 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   112131 #endif
   112132 #endif /* SQLITE_AMALGAMATION */
   112133 
   112134 
   112135 /*
   112136 ** Token types used by the sqlite3_complete() routine.  See the header
   112137 ** comments on that procedure for additional information.
   112138 */
   112139 #define tkSEMI    0
   112140 #define tkWS      1
   112141 #define tkOTHER   2
   112142 #ifndef SQLITE_OMIT_TRIGGER
   112143 #define tkEXPLAIN 3
   112144 #define tkCREATE  4
   112145 #define tkTEMP    5
   112146 #define tkTRIGGER 6
   112147 #define tkEND     7
   112148 #endif
   112149 
   112150 /*
   112151 ** Return TRUE if the given SQL string ends in a semicolon.
   112152 **
   112153 ** Special handling is require for CREATE TRIGGER statements.
   112154 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   112155 ** must end with ";END;".
   112156 **
   112157 ** This implementation uses a state machine with 8 states:
   112158 **
   112159 **   (0) INVALID   We have not yet seen a non-whitespace character.
   112160 **
   112161 **   (1) START     At the beginning or end of an SQL statement.  This routine
   112162 **                 returns 1 if it ends in the START state and 0 if it ends
   112163 **                 in any other state.
   112164 **
   112165 **   (2) NORMAL    We are in the middle of statement which ends with a single
   112166 **                 semicolon.
   112167 **
   112168 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   112169 **                 a statement.
   112170 **
   112171 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   112172 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   112173 **                 TEMP or TEMPORARY
   112174 **
   112175 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   112176 **                 ended by a semicolon, the keyword END, and another semicolon.
   112177 **
   112178 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   112179 **                 the end of a trigger definition.
   112180 **
   112181 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   112182 **                 of a trigger difinition.
   112183 **
   112184 ** Transitions between states above are determined by tokens extracted
   112185 ** from the input.  The following tokens are significant:
   112186 **
   112187 **   (0) tkSEMI      A semicolon.
   112188 **   (1) tkWS        Whitespace.
   112189 **   (2) tkOTHER     Any other SQL token.
   112190 **   (3) tkEXPLAIN   The "explain" keyword.
   112191 **   (4) tkCREATE    The "create" keyword.
   112192 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   112193 **   (6) tkTRIGGER   The "trigger" keyword.
   112194 **   (7) tkEND       The "end" keyword.
   112195 **
   112196 ** Whitespace never causes a state transition and is always ignored.
   112197 ** This means that a SQL string of all whitespace is invalid.
   112198 **
   112199 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   112200 ** to recognize the end of a trigger can be omitted.  All we have to do
   112201 ** is look for a semicolon that is not part of an string or comment.
   112202 */
   112203 SQLITE_API int sqlite3_complete(const char *zSql){
   112204   u8 state = 0;   /* Current state, using numbers defined in header comment */
   112205   u8 token;       /* Value of the next token */
   112206 
   112207 #ifndef SQLITE_OMIT_TRIGGER
   112208   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   112209   ** statement.  This is the normal case.
   112210   */
   112211   static const u8 trans[8][8] = {
   112212                      /* Token:                                                */
   112213      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   112214      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   112215      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   112216      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   112217      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   112218      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   112219      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   112220      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   112221      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   112222   };
   112223 #else
   112224   /* If triggers are not supported by this compile then the statement machine
   112225   ** used to detect the end of a statement is much simplier
   112226   */
   112227   static const u8 trans[3][3] = {
   112228                      /* Token:           */
   112229      /* State:       **  SEMI  WS  OTHER */
   112230      /* 0 INVALID: */ {    1,  0,     2, },
   112231      /* 1   START: */ {    1,  1,     2, },
   112232      /* 2  NORMAL: */ {    1,  2,     2, },
   112233   };
   112234 #endif /* SQLITE_OMIT_TRIGGER */
   112235 
   112236   while( *zSql ){
   112237     switch( *zSql ){
   112238       case ';': {  /* A semicolon */
   112239         token = tkSEMI;
   112240         break;
   112241       }
   112242       case ' ':
   112243       case '\r':
   112244       case '\t':
   112245       case '\n':
   112246       case '\f': {  /* White space is ignored */
   112247         token = tkWS;
   112248         break;
   112249       }
   112250       case '/': {   /* C-style comments */
   112251         if( zSql[1]!='*' ){
   112252           token = tkOTHER;
   112253           break;
   112254         }
   112255         zSql += 2;
   112256         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   112257         if( zSql[0]==0 ) return 0;
   112258         zSql++;
   112259         token = tkWS;
   112260         break;
   112261       }
   112262       case '-': {   /* SQL-style comments from "--" to end of line */
   112263         if( zSql[1]!='-' ){
   112264           token = tkOTHER;
   112265           break;
   112266         }
   112267         while( *zSql && *zSql!='\n' ){ zSql++; }
   112268         if( *zSql==0 ) return state==1;
   112269         token = tkWS;
   112270         break;
   112271       }
   112272       case '[': {   /* Microsoft-style identifiers in [...] */
   112273         zSql++;
   112274         while( *zSql && *zSql!=']' ){ zSql++; }
   112275         if( *zSql==0 ) return 0;
   112276         token = tkOTHER;
   112277         break;
   112278       }
   112279       case '`':     /* Grave-accent quoted symbols used by MySQL */
   112280       case '"':     /* single- and double-quoted strings */
   112281       case '\'': {
   112282         int c = *zSql;
   112283         zSql++;
   112284         while( *zSql && *zSql!=c ){ zSql++; }
   112285         if( *zSql==0 ) return 0;
   112286         token = tkOTHER;
   112287         break;
   112288       }
   112289       default: {
   112290 #ifdef SQLITE_EBCDIC
   112291         unsigned char c;
   112292 #endif
   112293         if( IdChar((u8)*zSql) ){
   112294           /* Keywords and unquoted identifiers */
   112295           int nId;
   112296           for(nId=1; IdChar(zSql[nId]); nId++){}
   112297 #ifdef SQLITE_OMIT_TRIGGER
   112298           token = tkOTHER;
   112299 #else
   112300           switch( *zSql ){
   112301             case 'c': case 'C': {
   112302               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   112303                 token = tkCREATE;
   112304               }else{
   112305                 token = tkOTHER;
   112306               }
   112307               break;
   112308             }
   112309             case 't': case 'T': {
   112310               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   112311                 token = tkTRIGGER;
   112312               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   112313                 token = tkTEMP;
   112314               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   112315                 token = tkTEMP;
   112316               }else{
   112317                 token = tkOTHER;
   112318               }
   112319               break;
   112320             }
   112321             case 'e':  case 'E': {
   112322               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   112323                 token = tkEND;
   112324               }else
   112325 #ifndef SQLITE_OMIT_EXPLAIN
   112326               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   112327                 token = tkEXPLAIN;
   112328               }else
   112329 #endif
   112330               {
   112331                 token = tkOTHER;
   112332               }
   112333               break;
   112334             }
   112335             default: {
   112336               token = tkOTHER;
   112337               break;
   112338             }
   112339           }
   112340 #endif /* SQLITE_OMIT_TRIGGER */
   112341           zSql += nId-1;
   112342         }else{
   112343           /* Operators and special symbols */
   112344           token = tkOTHER;
   112345         }
   112346         break;
   112347       }
   112348     }
   112349     state = trans[state][token];
   112350     zSql++;
   112351   }
   112352   return state==1;
   112353 }
   112354 
   112355 #ifndef SQLITE_OMIT_UTF16
   112356 /*
   112357 ** This routine is the same as the sqlite3_complete() routine described
   112358 ** above, except that the parameter is required to be UTF-16 encoded, not
   112359 ** UTF-8.
   112360 */
   112361 SQLITE_API int sqlite3_complete16(const void *zSql){
   112362   sqlite3_value *pVal;
   112363   char const *zSql8;
   112364   int rc = SQLITE_NOMEM;
   112365 
   112366 #ifndef SQLITE_OMIT_AUTOINIT
   112367   rc = sqlite3_initialize();
   112368   if( rc ) return rc;
   112369 #endif
   112370   pVal = sqlite3ValueNew(0);
   112371   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   112372   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   112373   if( zSql8 ){
   112374     rc = sqlite3_complete(zSql8);
   112375   }else{
   112376     rc = SQLITE_NOMEM;
   112377   }
   112378   sqlite3ValueFree(pVal);
   112379   return sqlite3ApiExit(0, rc);
   112380 }
   112381 #endif /* SQLITE_OMIT_UTF16 */
   112382 #endif /* SQLITE_OMIT_COMPLETE */
   112383 
   112384 /************** End of complete.c ********************************************/
   112385 /************** Begin file main.c ********************************************/
   112386 /*
   112387 ** 2001 September 15
   112388 **
   112389 ** The author disclaims copyright to this source code.  In place of
   112390 ** a legal notice, here is a blessing:
   112391 **
   112392 **    May you do good and not evil.
   112393 **    May you find forgiveness for yourself and forgive others.
   112394 **    May you share freely, never taking more than you give.
   112395 **
   112396 *************************************************************************
   112397 ** Main file for the SQLite library.  The routines in this file
   112398 ** implement the programmer interface to the library.  Routines in
   112399 ** other files are for internal use by SQLite and should not be
   112400 ** accessed by users of the library.
   112401 */
   112402 
   112403 #ifdef SQLITE_ENABLE_FTS3
   112404 /************** Include fts3.h in the middle of main.c ***********************/
   112405 /************** Begin file fts3.h ********************************************/
   112406 /*
   112407 ** 2006 Oct 10
   112408 **
   112409 ** The author disclaims copyright to this source code.  In place of
   112410 ** a legal notice, here is a blessing:
   112411 **
   112412 **    May you do good and not evil.
   112413 **    May you find forgiveness for yourself and forgive others.
   112414 **    May you share freely, never taking more than you give.
   112415 **
   112416 ******************************************************************************
   112417 **
   112418 ** This header file is used by programs that want to link against the
   112419 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   112420 */
   112421 
   112422 #if 0
   112423 extern "C" {
   112424 #endif  /* __cplusplus */
   112425 
   112426 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
   112427 
   112428 #if 0
   112429 }  /* extern "C" */
   112430 #endif  /* __cplusplus */
   112431 
   112432 /************** End of fts3.h ************************************************/
   112433 /************** Continuing where we left off in main.c ***********************/
   112434 #endif
   112435 #ifdef SQLITE_ENABLE_RTREE
   112436 /************** Include rtree.h in the middle of main.c **********************/
   112437 /************** Begin file rtree.h *******************************************/
   112438 /*
   112439 ** 2008 May 26
   112440 **
   112441 ** The author disclaims copyright to this source code.  In place of
   112442 ** a legal notice, here is a blessing:
   112443 **
   112444 **    May you do good and not evil.
   112445 **    May you find forgiveness for yourself and forgive others.
   112446 **    May you share freely, never taking more than you give.
   112447 **
   112448 ******************************************************************************
   112449 **
   112450 ** This header file is used by programs that want to link against the
   112451 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   112452 */
   112453 
   112454 #if 0
   112455 extern "C" {
   112456 #endif  /* __cplusplus */
   112457 
   112458 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   112459 
   112460 #if 0
   112461 }  /* extern "C" */
   112462 #endif  /* __cplusplus */
   112463 
   112464 /************** End of rtree.h ***********************************************/
   112465 /************** Continuing where we left off in main.c ***********************/
   112466 #endif
   112467 #ifdef SQLITE_ENABLE_ICU
   112468 /************** Include sqliteicu.h in the middle of main.c ******************/
   112469 /************** Begin file sqliteicu.h ***************************************/
   112470 /*
   112471 ** 2008 May 26
   112472 **
   112473 ** The author disclaims copyright to this source code.  In place of
   112474 ** a legal notice, here is a blessing:
   112475 **
   112476 **    May you do good and not evil.
   112477 **    May you find forgiveness for yourself and forgive others.
   112478 **    May you share freely, never taking more than you give.
   112479 **
   112480 ******************************************************************************
   112481 **
   112482 ** This header file is used by programs that want to link against the
   112483 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   112484 */
   112485 
   112486 #if 0
   112487 extern "C" {
   112488 #endif  /* __cplusplus */
   112489 
   112490 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   112491 
   112492 #if 0
   112493 }  /* extern "C" */
   112494 #endif  /* __cplusplus */
   112495 
   112496 
   112497 /************** End of sqliteicu.h *******************************************/
   112498 /************** Continuing where we left off in main.c ***********************/
   112499 #endif
   112500 
   112501 #ifndef SQLITE_AMALGAMATION
   112502 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   112503 ** contains the text of SQLITE_VERSION macro.
   112504 */
   112505 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   112506 #endif
   112507 
   112508 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   112509 ** a pointer to the to the sqlite3_version[] string constant.
   112510 */
   112511 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   112512 
   112513 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
   112514 ** pointer to a string constant whose value is the same as the
   112515 ** SQLITE_SOURCE_ID C preprocessor macro.
   112516 */
   112517 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   112518 
   112519 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   112520 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   112521 */
   112522 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   112523 
   112524 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
   112525 ** zero if and only if SQLite was compiled with mutexing code omitted due to
   112526 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   112527 */
   112528 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   112529 
   112530 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   112531 /*
   112532 ** If the following function pointer is not NULL and if
   112533 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   112534 ** I/O active are written using this function.  These messages
   112535 ** are intended for debugging activity only.
   112536 */
   112537 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   112538 #endif
   112539 
   112540 /*
   112541 ** If the following global variable points to a string which is the
   112542 ** name of a directory, then that directory will be used to store
   112543 ** temporary files.
   112544 **
   112545 ** See also the "PRAGMA temp_store_directory" SQL command.
   112546 */
   112547 SQLITE_API char *sqlite3_temp_directory = 0;
   112548 
   112549 /*
   112550 ** Initialize SQLite.
   112551 **
   112552 ** This routine must be called to initialize the memory allocation,
   112553 ** VFS, and mutex subsystems prior to doing any serious work with
   112554 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   112555 ** this routine will be called automatically by key routines such as
   112556 ** sqlite3_open().
   112557 **
   112558 ** This routine is a no-op except on its very first call for the process,
   112559 ** or for the first call after a call to sqlite3_shutdown.
   112560 **
   112561 ** The first thread to call this routine runs the initialization to
   112562 ** completion.  If subsequent threads call this routine before the first
   112563 ** thread has finished the initialization process, then the subsequent
   112564 ** threads must block until the first thread finishes with the initialization.
   112565 **
   112566 ** The first thread might call this routine recursively.  Recursive
   112567 ** calls to this routine should not block, of course.  Otherwise the
   112568 ** initialization process would never complete.
   112569 **
   112570 ** Let X be the first thread to enter this routine.  Let Y be some other
   112571 ** thread.  Then while the initial invocation of this routine by X is
   112572 ** incomplete, it is required that:
   112573 **
   112574 **    *  Calls to this routine from Y must block until the outer-most
   112575 **       call by X completes.
   112576 **
   112577 **    *  Recursive calls to this routine from thread X return immediately
   112578 **       without blocking.
   112579 */
   112580 SQLITE_API int sqlite3_initialize(void){
   112581   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
   112582   int rc;                                      /* Result code */
   112583 
   112584 #ifdef SQLITE_OMIT_WSD
   112585   rc = sqlite3_wsd_init(4096, 24);
   112586   if( rc!=SQLITE_OK ){
   112587     return rc;
   112588   }
   112589 #endif
   112590 
   112591   /* If SQLite is already completely initialized, then this call
   112592   ** to sqlite3_initialize() should be a no-op.  But the initialization
   112593   ** must be complete.  So isInit must not be set until the very end
   112594   ** of this routine.
   112595   */
   112596   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   112597 
   112598   /* Make sure the mutex subsystem is initialized.  If unable to
   112599   ** initialize the mutex subsystem, return early with the error.
   112600   ** If the system is so sick that we are unable to allocate a mutex,
   112601   ** there is not much SQLite is going to be able to do.
   112602   **
   112603   ** The mutex subsystem must take care of serializing its own
   112604   ** initialization.
   112605   */
   112606   rc = sqlite3MutexInit();
   112607   if( rc ) return rc;
   112608 
   112609   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   112610   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   112611   ** MutexAlloc() is called for a static mutex prior to initializing the
   112612   ** malloc subsystem - this implies that the allocation of a static
   112613   ** mutex must not require support from the malloc subsystem.
   112614   */
   112615   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   112616   sqlite3_mutex_enter(pMaster);
   112617   sqlite3GlobalConfig.isMutexInit = 1;
   112618   if( !sqlite3GlobalConfig.isMallocInit ){
   112619     rc = sqlite3MallocInit();
   112620   }
   112621   if( rc==SQLITE_OK ){
   112622     sqlite3GlobalConfig.isMallocInit = 1;
   112623     if( !sqlite3GlobalConfig.pInitMutex ){
   112624       sqlite3GlobalConfig.pInitMutex =
   112625            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   112626       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   112627         rc = SQLITE_NOMEM;
   112628       }
   112629     }
   112630   }
   112631   if( rc==SQLITE_OK ){
   112632     sqlite3GlobalConfig.nRefInitMutex++;
   112633   }
   112634   sqlite3_mutex_leave(pMaster);
   112635 
   112636   /* If rc is not SQLITE_OK at this point, then either the malloc
   112637   ** subsystem could not be initialized or the system failed to allocate
   112638   ** the pInitMutex mutex. Return an error in either case.  */
   112639   if( rc!=SQLITE_OK ){
   112640     return rc;
   112641   }
   112642 
   112643   /* Do the rest of the initialization under the recursive mutex so
   112644   ** that we will be able to handle recursive calls into
   112645   ** sqlite3_initialize().  The recursive calls normally come through
   112646   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   112647   ** recursive calls might also be possible.
   112648   **
   112649   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   112650   ** to the xInit method, so the xInit method need not be threadsafe.
   112651   **
   112652   ** The following mutex is what serializes access to the appdef pcache xInit
   112653   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   112654   ** call to sqlite3PcacheInitialize().
   112655   */
   112656   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   112657   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   112658     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   112659     sqlite3GlobalConfig.inProgress = 1;
   112660     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   112661     sqlite3RegisterGlobalFunctions();
   112662     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   112663       rc = sqlite3PcacheInitialize();
   112664     }
   112665     if( rc==SQLITE_OK ){
   112666       sqlite3GlobalConfig.isPCacheInit = 1;
   112667       rc = sqlite3OsInit();
   112668     }
   112669     if( rc==SQLITE_OK ){
   112670       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   112671           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   112672       sqlite3GlobalConfig.isInit = 1;
   112673     }
   112674     sqlite3GlobalConfig.inProgress = 0;
   112675   }
   112676   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   112677 
   112678   /* Go back under the static mutex and clean up the recursive
   112679   ** mutex to prevent a resource leak.
   112680   */
   112681   sqlite3_mutex_enter(pMaster);
   112682   sqlite3GlobalConfig.nRefInitMutex--;
   112683   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   112684     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   112685     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   112686     sqlite3GlobalConfig.pInitMutex = 0;
   112687   }
   112688   sqlite3_mutex_leave(pMaster);
   112689 
   112690   /* The following is just a sanity check to make sure SQLite has
   112691   ** been compiled correctly.  It is important to run this code, but
   112692   ** we don't want to run it too often and soak up CPU cycles for no
   112693   ** reason.  So we run it once during initialization.
   112694   */
   112695 #ifndef NDEBUG
   112696 #ifndef SQLITE_OMIT_FLOATING_POINT
   112697   /* This section of code's only "output" is via assert() statements. */
   112698   if ( rc==SQLITE_OK ){
   112699     u64 x = (((u64)1)<<63)-1;
   112700     double y;
   112701     assert(sizeof(x)==8);
   112702     assert(sizeof(x)==sizeof(y));
   112703     memcpy(&y, &x, 8);
   112704     assert( sqlite3IsNaN(y) );
   112705   }
   112706 #endif
   112707 #endif
   112708 
   112709   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   112710   ** compile-time option.
   112711   */
   112712 #ifdef SQLITE_EXTRA_INIT
   112713   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
   112714     int SQLITE_EXTRA_INIT(const char*);
   112715     rc = SQLITE_EXTRA_INIT(0);
   112716   }
   112717 #endif
   112718 
   112719   return rc;
   112720 }
   112721 
   112722 /*
   112723 ** Undo the effects of sqlite3_initialize().  Must not be called while
   112724 ** there are outstanding database connections or memory allocations or
   112725 ** while any part of SQLite is otherwise in use in any thread.  This
   112726 ** routine is not threadsafe.  But it is safe to invoke this routine
   112727 ** on when SQLite is already shut down.  If SQLite is already shut down
   112728 ** when this routine is invoked, then this routine is a harmless no-op.
   112729 */
   112730 SQLITE_API int sqlite3_shutdown(void){
   112731   if( sqlite3GlobalConfig.isInit ){
   112732 #ifdef SQLITE_EXTRA_SHUTDOWN
   112733     void SQLITE_EXTRA_SHUTDOWN(void);
   112734     SQLITE_EXTRA_SHUTDOWN();
   112735 #endif
   112736     sqlite3_os_end();
   112737     sqlite3_reset_auto_extension();
   112738     sqlite3GlobalConfig.isInit = 0;
   112739   }
   112740   if( sqlite3GlobalConfig.isPCacheInit ){
   112741     sqlite3PcacheShutdown();
   112742     sqlite3GlobalConfig.isPCacheInit = 0;
   112743   }
   112744   if( sqlite3GlobalConfig.isMallocInit ){
   112745     sqlite3MallocEnd();
   112746     sqlite3GlobalConfig.isMallocInit = 0;
   112747   }
   112748   if( sqlite3GlobalConfig.isMutexInit ){
   112749     sqlite3MutexEnd();
   112750     sqlite3GlobalConfig.isMutexInit = 0;
   112751   }
   112752 
   112753   return SQLITE_OK;
   112754 }
   112755 
   112756 /*
   112757 ** This API allows applications to modify the global configuration of
   112758 ** the SQLite library at run-time.
   112759 **
   112760 ** This routine should only be called when there are no outstanding
   112761 ** database connections or memory allocations.  This routine is not
   112762 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   112763 ** behavior.
   112764 */
   112765 SQLITE_API int sqlite3_config(int op, ...){
   112766   va_list ap;
   112767   int rc = SQLITE_OK;
   112768 
   112769   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   112770   ** the SQLite library is in use. */
   112771   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   112772 
   112773   va_start(ap, op);
   112774   switch( op ){
   112775 
   112776     /* Mutex configuration options are only available in a threadsafe
   112777     ** compile.
   112778     */
   112779 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   112780     case SQLITE_CONFIG_SINGLETHREAD: {
   112781       /* Disable all mutexing */
   112782       sqlite3GlobalConfig.bCoreMutex = 0;
   112783       sqlite3GlobalConfig.bFullMutex = 0;
   112784       break;
   112785     }
   112786     case SQLITE_CONFIG_MULTITHREAD: {
   112787       /* Disable mutexing of database connections */
   112788       /* Enable mutexing of core data structures */
   112789       sqlite3GlobalConfig.bCoreMutex = 1;
   112790       sqlite3GlobalConfig.bFullMutex = 0;
   112791       break;
   112792     }
   112793     case SQLITE_CONFIG_SERIALIZED: {
   112794       /* Enable all mutexing */
   112795       sqlite3GlobalConfig.bCoreMutex = 1;
   112796       sqlite3GlobalConfig.bFullMutex = 1;
   112797       break;
   112798     }
   112799     case SQLITE_CONFIG_MUTEX: {
   112800       /* Specify an alternative mutex implementation */
   112801       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   112802       break;
   112803     }
   112804     case SQLITE_CONFIG_GETMUTEX: {
   112805       /* Retrieve the current mutex implementation */
   112806       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   112807       break;
   112808     }
   112809 #endif
   112810 
   112811 
   112812     case SQLITE_CONFIG_MALLOC: {
   112813       /* Specify an alternative malloc implementation */
   112814       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   112815       break;
   112816     }
   112817     case SQLITE_CONFIG_GETMALLOC: {
   112818       /* Retrieve the current malloc() implementation */
   112819       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   112820       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   112821       break;
   112822     }
   112823     case SQLITE_CONFIG_MEMSTATUS: {
   112824       /* Enable or disable the malloc status collection */
   112825       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   112826       break;
   112827     }
   112828     case SQLITE_CONFIG_SCRATCH: {
   112829       /* Designate a buffer for scratch memory space */
   112830       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   112831       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   112832       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   112833       break;
   112834     }
   112835     case SQLITE_CONFIG_PAGECACHE: {
   112836       /* Designate a buffer for page cache memory space */
   112837       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   112838       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   112839       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   112840       break;
   112841     }
   112842 
   112843     case SQLITE_CONFIG_PCACHE: {
   112844       /* no-op */
   112845       break;
   112846     }
   112847     case SQLITE_CONFIG_GETPCACHE: {
   112848       /* now an error */
   112849       rc = SQLITE_ERROR;
   112850       break;
   112851     }
   112852 
   112853     case SQLITE_CONFIG_PCACHE2: {
   112854       /* Specify an alternative page cache implementation */
   112855       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
   112856       break;
   112857     }
   112858     case SQLITE_CONFIG_GETPCACHE2: {
   112859       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   112860         sqlite3PCacheSetDefault();
   112861       }
   112862       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   112863       break;
   112864     }
   112865 
   112866 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   112867     case SQLITE_CONFIG_HEAP: {
   112868       /* Designate a buffer for heap memory space */
   112869       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   112870       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   112871       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   112872 
   112873       if( sqlite3GlobalConfig.mnReq<1 ){
   112874         sqlite3GlobalConfig.mnReq = 1;
   112875       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
   112876         /* cap min request size at 2^12 */
   112877         sqlite3GlobalConfig.mnReq = (1<<12);
   112878       }
   112879 
   112880       if( sqlite3GlobalConfig.pHeap==0 ){
   112881         /* If the heap pointer is NULL, then restore the malloc implementation
   112882         ** back to NULL pointers too.  This will cause the malloc to go
   112883         ** back to its default implementation when sqlite3_initialize() is
   112884         ** run.
   112885         */
   112886         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   112887       }else{
   112888         /* The heap pointer is not NULL, then install one of the
   112889         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
   112890         ** ENABLE_MEMSYS5 is defined, return an error.
   112891         */
   112892 #ifdef SQLITE_ENABLE_MEMSYS3
   112893         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   112894 #endif
   112895 #ifdef SQLITE_ENABLE_MEMSYS5
   112896         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   112897 #endif
   112898       }
   112899       break;
   112900     }
   112901 #endif
   112902 
   112903     case SQLITE_CONFIG_LOOKASIDE: {
   112904       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   112905       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   112906       break;
   112907     }
   112908 
   112909     /* Record a pointer to the logger funcction and its first argument.
   112910     ** The default is NULL.  Logging is disabled if the function pointer is
   112911     ** NULL.
   112912     */
   112913     case SQLITE_CONFIG_LOG: {
   112914       /* MSVC is picky about pulling func ptrs from va lists.
   112915       ** http://support.microsoft.com/kb/47961
   112916       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   112917       */
   112918       typedef void(*LOGFUNC_t)(void*,int,const char*);
   112919       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   112920       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   112921       break;
   112922     }
   112923 
   112924     case SQLITE_CONFIG_URI: {
   112925       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
   112926       break;
   112927     }
   112928 
   112929     default: {
   112930       rc = SQLITE_ERROR;
   112931       break;
   112932     }
   112933   }
   112934   va_end(ap);
   112935   return rc;
   112936 }
   112937 
   112938 /*
   112939 ** Set up the lookaside buffers for a database connection.
   112940 ** Return SQLITE_OK on success.
   112941 ** If lookaside is already active, return SQLITE_BUSY.
   112942 **
   112943 ** The sz parameter is the number of bytes in each lookaside slot.
   112944 ** The cnt parameter is the number of slots.  If pStart is NULL the
   112945 ** space for the lookaside memory is obtained from sqlite3_malloc().
   112946 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   112947 ** the lookaside memory.
   112948 */
   112949 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   112950   void *pStart;
   112951   if( db->lookaside.nOut ){
   112952     return SQLITE_BUSY;
   112953   }
   112954   /* Free any existing lookaside buffer for this handle before
   112955   ** allocating a new one so we don't have to have space for
   112956   ** both at the same time.
   112957   */
   112958   if( db->lookaside.bMalloced ){
   112959     sqlite3_free(db->lookaside.pStart);
   112960   }
   112961   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
   112962   ** than a pointer to be useful.
   112963   */
   112964   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   112965   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   112966   if( cnt<0 ) cnt = 0;
   112967   if( sz==0 || cnt==0 ){
   112968     sz = 0;
   112969     pStart = 0;
   112970   }else if( pBuf==0 ){
   112971     sqlite3BeginBenignMalloc();
   112972     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   112973     sqlite3EndBenignMalloc();
   112974     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   112975   }else{
   112976     pStart = pBuf;
   112977   }
   112978   db->lookaside.pStart = pStart;
   112979   db->lookaside.pFree = 0;
   112980   db->lookaside.sz = (u16)sz;
   112981   if( pStart ){
   112982     int i;
   112983     LookasideSlot *p;
   112984     assert( sz > (int)sizeof(LookasideSlot*) );
   112985     p = (LookasideSlot*)pStart;
   112986     for(i=cnt-1; i>=0; i--){
   112987       p->pNext = db->lookaside.pFree;
   112988       db->lookaside.pFree = p;
   112989       p = (LookasideSlot*)&((u8*)p)[sz];
   112990     }
   112991     db->lookaside.pEnd = p;
   112992     db->lookaside.bEnabled = 1;
   112993     db->lookaside.bMalloced = pBuf==0 ?1:0;
   112994   }else{
   112995     db->lookaside.pEnd = 0;
   112996     db->lookaside.bEnabled = 0;
   112997     db->lookaside.bMalloced = 0;
   112998   }
   112999   return SQLITE_OK;
   113000 }
   113001 
   113002 /*
   113003 ** Return the mutex associated with a database connection.
   113004 */
   113005 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   113006   return db->mutex;
   113007 }
   113008 
   113009 /*
   113010 ** Free up as much memory as we can from the given database
   113011 ** connection.
   113012 */
   113013 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
   113014   int i;
   113015   sqlite3_mutex_enter(db->mutex);
   113016   sqlite3BtreeEnterAll(db);
   113017   for(i=0; i<db->nDb; i++){
   113018     Btree *pBt = db->aDb[i].pBt;
   113019     if( pBt ){
   113020       Pager *pPager = sqlite3BtreePager(pBt);
   113021       sqlite3PagerShrink(pPager);
   113022     }
   113023   }
   113024   sqlite3BtreeLeaveAll(db);
   113025   sqlite3_mutex_leave(db->mutex);
   113026   return SQLITE_OK;
   113027 }
   113028 
   113029 /*
   113030 ** Configuration settings for an individual database connection
   113031 */
   113032 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   113033   va_list ap;
   113034   int rc;
   113035   va_start(ap, op);
   113036   switch( op ){
   113037     case SQLITE_DBCONFIG_LOOKASIDE: {
   113038       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   113039       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   113040       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   113041       rc = setupLookaside(db, pBuf, sz, cnt);
   113042       break;
   113043     }
   113044     default: {
   113045       static const struct {
   113046         int op;      /* The opcode */
   113047         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
   113048       } aFlagOp[] = {
   113049         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
   113050         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
   113051       };
   113052       unsigned int i;
   113053       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   113054       for(i=0; i<ArraySize(aFlagOp); i++){
   113055         if( aFlagOp[i].op==op ){
   113056           int onoff = va_arg(ap, int);
   113057           int *pRes = va_arg(ap, int*);
   113058           int oldFlags = db->flags;
   113059           if( onoff>0 ){
   113060             db->flags |= aFlagOp[i].mask;
   113061           }else if( onoff==0 ){
   113062             db->flags &= ~aFlagOp[i].mask;
   113063           }
   113064           if( oldFlags!=db->flags ){
   113065             sqlite3ExpirePreparedStatements(db);
   113066           }
   113067           if( pRes ){
   113068             *pRes = (db->flags & aFlagOp[i].mask)!=0;
   113069           }
   113070           rc = SQLITE_OK;
   113071           break;
   113072         }
   113073       }
   113074       break;
   113075     }
   113076   }
   113077   va_end(ap);
   113078   return rc;
   113079 }
   113080 
   113081 
   113082 /*
   113083 ** Return true if the buffer z[0..n-1] contains all spaces.
   113084 */
   113085 static int allSpaces(const char *z, int n){
   113086   while( n>0 && z[n-1]==' ' ){ n--; }
   113087   return n==0;
   113088 }
   113089 
   113090 /*
   113091 ** This is the default collating function named "BINARY" which is always
   113092 ** available.
   113093 **
   113094 ** If the padFlag argument is not NULL then space padding at the end
   113095 ** of strings is ignored.  This implements the RTRIM collation.
   113096 */
   113097 static int binCollFunc(
   113098   void *padFlag,
   113099   int nKey1, const void *pKey1,
   113100   int nKey2, const void *pKey2
   113101 ){
   113102   int rc, n;
   113103   n = nKey1<nKey2 ? nKey1 : nKey2;
   113104   rc = memcmp(pKey1, pKey2, n);
   113105   if( rc==0 ){
   113106     if( padFlag
   113107      && allSpaces(((char*)pKey1)+n, nKey1-n)
   113108      && allSpaces(((char*)pKey2)+n, nKey2-n)
   113109     ){
   113110       /* Leave rc unchanged at 0 */
   113111     }else{
   113112       rc = nKey1 - nKey2;
   113113     }
   113114   }
   113115   return rc;
   113116 }
   113117 
   113118 /*
   113119 ** Another built-in collating sequence: NOCASE.
   113120 **
   113121 ** This collating sequence is intended to be used for "case independant
   113122 ** comparison". SQLite's knowledge of upper and lower case equivalents
   113123 ** extends only to the 26 characters used in the English language.
   113124 **
   113125 ** At the moment there is only a UTF-8 implementation.
   113126 */
   113127 static int nocaseCollatingFunc(
   113128   void *NotUsed,
   113129   int nKey1, const void *pKey1,
   113130   int nKey2, const void *pKey2
   113131 ){
   113132   int r = sqlite3StrNICmp(
   113133       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   113134   UNUSED_PARAMETER(NotUsed);
   113135   if( 0==r ){
   113136     r = nKey1-nKey2;
   113137   }
   113138   return r;
   113139 }
   113140 
   113141 /*
   113142 ** Return the ROWID of the most recent insert
   113143 */
   113144 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   113145   return db->lastRowid;
   113146 }
   113147 
   113148 /*
   113149 ** Return the number of changes in the most recent call to sqlite3_exec().
   113150 */
   113151 SQLITE_API int sqlite3_changes(sqlite3 *db){
   113152   return db->nChange;
   113153 }
   113154 
   113155 /*
   113156 ** Return the number of changes since the database handle was opened.
   113157 */
   113158 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   113159   return db->nTotalChange;
   113160 }
   113161 
   113162 /*
   113163 ** Close all open savepoints. This function only manipulates fields of the
   113164 ** database handle object, it does not close any savepoints that may be open
   113165 ** at the b-tree/pager level.
   113166 */
   113167 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   113168   while( db->pSavepoint ){
   113169     Savepoint *pTmp = db->pSavepoint;
   113170     db->pSavepoint = pTmp->pNext;
   113171     sqlite3DbFree(db, pTmp);
   113172   }
   113173   db->nSavepoint = 0;
   113174   db->nStatement = 0;
   113175   db->isTransactionSavepoint = 0;
   113176 }
   113177 
   113178 /*
   113179 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   113180 ** if this is not the last copy of the function, do not invoke it. Multiple
   113181 ** copies of a single function are created when create_function() is called
   113182 ** with SQLITE_ANY as the encoding.
   113183 */
   113184 static void functionDestroy(sqlite3 *db, FuncDef *p){
   113185   FuncDestructor *pDestructor = p->pDestructor;
   113186   if( pDestructor ){
   113187     pDestructor->nRef--;
   113188     if( pDestructor->nRef==0 ){
   113189       pDestructor->xDestroy(pDestructor->pUserData);
   113190       sqlite3DbFree(db, pDestructor);
   113191     }
   113192   }
   113193 }
   113194 
   113195 /*
   113196 ** Close an existing SQLite database
   113197 */
   113198 SQLITE_API int sqlite3_close(sqlite3 *db){
   113199   HashElem *i;                    /* Hash table iterator */
   113200   int j;
   113201 
   113202   if( !db ){
   113203     return SQLITE_OK;
   113204   }
   113205   if( !sqlite3SafetyCheckSickOrOk(db) ){
   113206     return SQLITE_MISUSE_BKPT;
   113207   }
   113208   sqlite3_mutex_enter(db->mutex);
   113209 
   113210   /* Force xDestroy calls on all virtual tables */
   113211   sqlite3ResetInternalSchema(db, -1);
   113212 
   113213   /* If a transaction is open, the ResetInternalSchema() call above
   113214   ** will not have called the xDisconnect() method on any virtual
   113215   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   113216   ** call will do so. We need to do this before the check for active
   113217   ** SQL statements below, as the v-table implementation may be storing
   113218   ** some prepared statements internally.
   113219   */
   113220   sqlite3VtabRollback(db);
   113221 
   113222   /* If there are any outstanding VMs, return SQLITE_BUSY. */
   113223   if( db->pVdbe ){
   113224     sqlite3Error(db, SQLITE_BUSY,
   113225         "unable to close due to unfinalised statements");
   113226     sqlite3_mutex_leave(db->mutex);
   113227     return SQLITE_BUSY;
   113228   }
   113229   assert( sqlite3SafetyCheckSickOrOk(db) );
   113230 
   113231   for(j=0; j<db->nDb; j++){
   113232     Btree *pBt = db->aDb[j].pBt;
   113233     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
   113234       sqlite3Error(db, SQLITE_BUSY,
   113235           "unable to close due to unfinished backup operation");
   113236       sqlite3_mutex_leave(db->mutex);
   113237       return SQLITE_BUSY;
   113238     }
   113239   }
   113240 
   113241   /* Free any outstanding Savepoint structures. */
   113242   sqlite3CloseSavepoints(db);
   113243 
   113244   for(j=0; j<db->nDb; j++){
   113245     struct Db *pDb = &db->aDb[j];
   113246     if( pDb->pBt ){
   113247       sqlite3BtreeClose(pDb->pBt);
   113248       pDb->pBt = 0;
   113249       if( j!=1 ){
   113250         pDb->pSchema = 0;
   113251       }
   113252     }
   113253   }
   113254   sqlite3ResetInternalSchema(db, -1);
   113255 
   113256   /* Tell the code in notify.c that the connection no longer holds any
   113257   ** locks and does not require any further unlock-notify callbacks.
   113258   */
   113259   sqlite3ConnectionClosed(db);
   113260 
   113261   assert( db->nDb<=2 );
   113262   assert( db->aDb==db->aDbStatic );
   113263   for(j=0; j<ArraySize(db->aFunc.a); j++){
   113264     FuncDef *pNext, *pHash, *p;
   113265     for(p=db->aFunc.a[j]; p; p=pHash){
   113266       pHash = p->pHash;
   113267       while( p ){
   113268         functionDestroy(db, p);
   113269         pNext = p->pNext;
   113270         sqlite3DbFree(db, p);
   113271         p = pNext;
   113272       }
   113273     }
   113274   }
   113275   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   113276     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   113277     /* Invoke any destructors registered for collation sequence user data. */
   113278     for(j=0; j<3; j++){
   113279       if( pColl[j].xDel ){
   113280         pColl[j].xDel(pColl[j].pUser);
   113281       }
   113282     }
   113283     sqlite3DbFree(db, pColl);
   113284   }
   113285   sqlite3HashClear(&db->aCollSeq);
   113286 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113287   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   113288     Module *pMod = (Module *)sqliteHashData(i);
   113289     if( pMod->xDestroy ){
   113290       pMod->xDestroy(pMod->pAux);
   113291     }
   113292     sqlite3DbFree(db, pMod);
   113293   }
   113294   sqlite3HashClear(&db->aModule);
   113295 #endif
   113296 
   113297   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   113298   if( db->pErr ){
   113299     sqlite3ValueFree(db->pErr);
   113300   }
   113301   sqlite3CloseExtensions(db);
   113302 
   113303   db->magic = SQLITE_MAGIC_ERROR;
   113304 
   113305   /* The temp-database schema is allocated differently from the other schema
   113306   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   113307   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   113308   ** the same sqliteMalloc() as the one that allocates the database
   113309   ** structure?
   113310   */
   113311   sqlite3DbFree(db, db->aDb[1].pSchema);
   113312   sqlite3_mutex_leave(db->mutex);
   113313   db->magic = SQLITE_MAGIC_CLOSED;
   113314   sqlite3_mutex_free(db->mutex);
   113315   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   113316   if( db->lookaside.bMalloced ){
   113317     sqlite3_free(db->lookaside.pStart);
   113318   }
   113319   sqlite3_free(db);
   113320   return SQLITE_OK;
   113321 }
   113322 
   113323 /*
   113324 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
   113325 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
   113326 ** breaker") and made to return tripCode if there are any further
   113327 ** attempts to use that cursor.
   113328 */
   113329 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   113330   int i;
   113331   int inTrans = 0;
   113332   assert( sqlite3_mutex_held(db->mutex) );
   113333   sqlite3BeginBenignMalloc();
   113334   for(i=0; i<db->nDb; i++){
   113335     Btree *p = db->aDb[i].pBt;
   113336     if( p ){
   113337       if( sqlite3BtreeIsInTrans(p) ){
   113338         inTrans = 1;
   113339       }
   113340       sqlite3BtreeRollback(p, tripCode);
   113341       db->aDb[i].inTrans = 0;
   113342     }
   113343   }
   113344   sqlite3VtabRollback(db);
   113345   sqlite3EndBenignMalloc();
   113346 
   113347   if( db->flags&SQLITE_InternChanges ){
   113348     sqlite3ExpirePreparedStatements(db);
   113349     sqlite3ResetInternalSchema(db, -1);
   113350   }
   113351 
   113352   /* Any deferred constraint violations have now been resolved. */
   113353   db->nDeferredCons = 0;
   113354 
   113355   /* If one has been configured, invoke the rollback-hook callback */
   113356   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   113357     db->xRollbackCallback(db->pRollbackArg);
   113358   }
   113359 }
   113360 
   113361 /*
   113362 ** Return a static string that describes the kind of error specified in the
   113363 ** argument.
   113364 */
   113365 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   113366   static const char* const aMsg[] = {
   113367     /* SQLITE_OK          */ "not an error",
   113368     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   113369     /* SQLITE_INTERNAL    */ 0,
   113370     /* SQLITE_PERM        */ "access permission denied",
   113371     /* SQLITE_ABORT       */ "callback requested query abort",
   113372     /* SQLITE_BUSY        */ "database is locked",
   113373     /* SQLITE_LOCKED      */ "database table is locked",
   113374     /* SQLITE_NOMEM       */ "out of memory",
   113375     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   113376     /* SQLITE_INTERRUPT   */ "interrupted",
   113377     /* SQLITE_IOERR       */ "disk I/O error",
   113378     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   113379     /* SQLITE_NOTFOUND    */ "unknown operation",
   113380     /* SQLITE_FULL        */ "database or disk is full",
   113381     /* SQLITE_CANTOPEN    */ "unable to open database file",
   113382     /* SQLITE_PROTOCOL    */ "locking protocol",
   113383     /* SQLITE_EMPTY       */ "table contains no data",
   113384     /* SQLITE_SCHEMA      */ "database schema has changed",
   113385     /* SQLITE_TOOBIG      */ "string or blob too big",
   113386     /* SQLITE_CONSTRAINT  */ "constraint failed",
   113387     /* SQLITE_MISMATCH    */ "datatype mismatch",
   113388     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   113389     /* SQLITE_NOLFS       */ "large file support is disabled",
   113390     /* SQLITE_AUTH        */ "authorization denied",
   113391     /* SQLITE_FORMAT      */ "auxiliary database format error",
   113392     /* SQLITE_RANGE       */ "bind or column index out of range",
   113393     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   113394   };
   113395   const char *zErr = "unknown error";
   113396   switch( rc ){
   113397     case SQLITE_ABORT_ROLLBACK: {
   113398       zErr = "abort due to ROLLBACK";
   113399       break;
   113400     }
   113401     default: {
   113402       rc &= 0xff;
   113403       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
   113404         zErr = aMsg[rc];
   113405       }
   113406       break;
   113407     }
   113408   }
   113409   return zErr;
   113410 }
   113411 
   113412 /*
   113413 ** This routine implements a busy callback that sleeps and tries
   113414 ** again until a timeout value is reached.  The timeout value is
   113415 ** an integer number of milliseconds passed in as the first
   113416 ** argument.
   113417 */
   113418 static int sqliteDefaultBusyCallback(
   113419  void *ptr,               /* Database connection */
   113420  int count                /* Number of times table has been busy */
   113421 ){
   113422 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   113423   static const u8 delays[] =
   113424      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   113425   static const u8 totals[] =
   113426      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   113427 # define NDELAY ArraySize(delays)
   113428   sqlite3 *db = (sqlite3 *)ptr;
   113429   int timeout = db->busyTimeout;
   113430   int delay, prior;
   113431 
   113432   assert( count>=0 );
   113433   if( count < NDELAY ){
   113434     delay = delays[count];
   113435     prior = totals[count];
   113436   }else{
   113437     delay = delays[NDELAY-1];
   113438     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   113439   }
   113440   if( prior + delay > timeout ){
   113441     delay = timeout - prior;
   113442     if( delay<=0 ) return 0;
   113443   }
   113444   sqlite3OsSleep(db->pVfs, delay*1000);
   113445   return 1;
   113446 #else
   113447   sqlite3 *db = (sqlite3 *)ptr;
   113448   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   113449   if( (count+1)*1000 > timeout ){
   113450     return 0;
   113451   }
   113452   sqlite3OsSleep(db->pVfs, 1000000);
   113453   return 1;
   113454 #endif
   113455 }
   113456 
   113457 /*
   113458 ** Invoke the given busy handler.
   113459 **
   113460 ** This routine is called when an operation failed with a lock.
   113461 ** If this routine returns non-zero, the lock is retried.  If it
   113462 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   113463 */
   113464 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   113465   int rc;
   113466   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   113467   rc = p->xFunc(p->pArg, p->nBusy);
   113468   if( rc==0 ){
   113469     p->nBusy = -1;
   113470   }else{
   113471     p->nBusy++;
   113472   }
   113473   return rc;
   113474 }
   113475 
   113476 /*
   113477 ** This routine sets the busy callback for an Sqlite database to the
   113478 ** given callback function with the given argument.
   113479 */
   113480 SQLITE_API int sqlite3_busy_handler(
   113481   sqlite3 *db,
   113482   int (*xBusy)(void*,int),
   113483   void *pArg
   113484 ){
   113485   sqlite3_mutex_enter(db->mutex);
   113486   db->busyHandler.xFunc = xBusy;
   113487   db->busyHandler.pArg = pArg;
   113488   db->busyHandler.nBusy = 0;
   113489   sqlite3_mutex_leave(db->mutex);
   113490   return SQLITE_OK;
   113491 }
   113492 
   113493 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   113494 /*
   113495 ** This routine sets the progress callback for an Sqlite database to the
   113496 ** given callback function with the given argument. The progress callback will
   113497 ** be invoked every nOps opcodes.
   113498 */
   113499 SQLITE_API void sqlite3_progress_handler(
   113500   sqlite3 *db,
   113501   int nOps,
   113502   int (*xProgress)(void*),
   113503   void *pArg
   113504 ){
   113505   sqlite3_mutex_enter(db->mutex);
   113506   if( nOps>0 ){
   113507     db->xProgress = xProgress;
   113508     db->nProgressOps = nOps;
   113509     db->pProgressArg = pArg;
   113510   }else{
   113511     db->xProgress = 0;
   113512     db->nProgressOps = 0;
   113513     db->pProgressArg = 0;
   113514   }
   113515   sqlite3_mutex_leave(db->mutex);
   113516 }
   113517 #endif
   113518 
   113519 
   113520 /*
   113521 ** This routine installs a default busy handler that waits for the
   113522 ** specified number of milliseconds before returning 0.
   113523 */
   113524 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   113525   if( ms>0 ){
   113526     db->busyTimeout = ms;
   113527     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   113528   }else{
   113529     sqlite3_busy_handler(db, 0, 0);
   113530   }
   113531   return SQLITE_OK;
   113532 }
   113533 
   113534 /*
   113535 ** Cause any pending operation to stop at its earliest opportunity.
   113536 */
   113537 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   113538   db->u1.isInterrupted = 1;
   113539 }
   113540 
   113541 
   113542 /*
   113543 ** This function is exactly the same as sqlite3_create_function(), except
   113544 ** that it is designed to be called by internal code. The difference is
   113545 ** that if a malloc() fails in sqlite3_create_function(), an error code
   113546 ** is returned and the mallocFailed flag cleared.
   113547 */
   113548 SQLITE_PRIVATE int sqlite3CreateFunc(
   113549   sqlite3 *db,
   113550   const char *zFunctionName,
   113551   int nArg,
   113552   int enc,
   113553   void *pUserData,
   113554   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113555   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113556   void (*xFinal)(sqlite3_context*),
   113557   FuncDestructor *pDestructor
   113558 ){
   113559   FuncDef *p;
   113560   int nName;
   113561 
   113562   assert( sqlite3_mutex_held(db->mutex) );
   113563   if( zFunctionName==0 ||
   113564       (xFunc && (xFinal || xStep)) ||
   113565       (!xFunc && (xFinal && !xStep)) ||
   113566       (!xFunc && (!xFinal && xStep)) ||
   113567       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   113568       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   113569     return SQLITE_MISUSE_BKPT;
   113570   }
   113571 
   113572 #ifndef SQLITE_OMIT_UTF16
   113573   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   113574   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   113575   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   113576   **
   113577   ** If SQLITE_ANY is specified, add three versions of the function
   113578   ** to the hash table.
   113579   */
   113580   if( enc==SQLITE_UTF16 ){
   113581     enc = SQLITE_UTF16NATIVE;
   113582   }else if( enc==SQLITE_ANY ){
   113583     int rc;
   113584     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
   113585          pUserData, xFunc, xStep, xFinal, pDestructor);
   113586     if( rc==SQLITE_OK ){
   113587       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
   113588           pUserData, xFunc, xStep, xFinal, pDestructor);
   113589     }
   113590     if( rc!=SQLITE_OK ){
   113591       return rc;
   113592     }
   113593     enc = SQLITE_UTF16BE;
   113594   }
   113595 #else
   113596   enc = SQLITE_UTF8;
   113597 #endif
   113598 
   113599   /* Check if an existing function is being overridden or deleted. If so,
   113600   ** and there are active VMs, then return SQLITE_BUSY. If a function
   113601   ** is being overridden/deleted but there are no active VMs, allow the
   113602   ** operation to continue but invalidate all precompiled statements.
   113603   */
   113604   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   113605   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
   113606     if( db->activeVdbeCnt ){
   113607       sqlite3Error(db, SQLITE_BUSY,
   113608         "unable to delete/modify user-function due to active statements");
   113609       assert( !db->mallocFailed );
   113610       return SQLITE_BUSY;
   113611     }else{
   113612       sqlite3ExpirePreparedStatements(db);
   113613     }
   113614   }
   113615 
   113616   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   113617   assert(p || db->mallocFailed);
   113618   if( !p ){
   113619     return SQLITE_NOMEM;
   113620   }
   113621 
   113622   /* If an older version of the function with a configured destructor is
   113623   ** being replaced invoke the destructor function here. */
   113624   functionDestroy(db, p);
   113625 
   113626   if( pDestructor ){
   113627     pDestructor->nRef++;
   113628   }
   113629   p->pDestructor = pDestructor;
   113630   p->flags = 0;
   113631   p->xFunc = xFunc;
   113632   p->xStep = xStep;
   113633   p->xFinalize = xFinal;
   113634   p->pUserData = pUserData;
   113635   p->nArg = (u16)nArg;
   113636   return SQLITE_OK;
   113637 }
   113638 
   113639 /*
   113640 ** Create new user functions.
   113641 */
   113642 SQLITE_API int sqlite3_create_function(
   113643   sqlite3 *db,
   113644   const char *zFunc,
   113645   int nArg,
   113646   int enc,
   113647   void *p,
   113648   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113649   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113650   void (*xFinal)(sqlite3_context*)
   113651 ){
   113652   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   113653                                     xFinal, 0);
   113654 }
   113655 
   113656 SQLITE_API int sqlite3_create_function_v2(
   113657   sqlite3 *db,
   113658   const char *zFunc,
   113659   int nArg,
   113660   int enc,
   113661   void *p,
   113662   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113663   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113664   void (*xFinal)(sqlite3_context*),
   113665   void (*xDestroy)(void *)
   113666 ){
   113667   int rc = SQLITE_ERROR;
   113668   FuncDestructor *pArg = 0;
   113669   sqlite3_mutex_enter(db->mutex);
   113670   if( xDestroy ){
   113671     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   113672     if( !pArg ){
   113673       xDestroy(p);
   113674       goto out;
   113675     }
   113676     pArg->xDestroy = xDestroy;
   113677     pArg->pUserData = p;
   113678   }
   113679   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   113680   if( pArg && pArg->nRef==0 ){
   113681     assert( rc!=SQLITE_OK );
   113682     xDestroy(p);
   113683     sqlite3DbFree(db, pArg);
   113684   }
   113685 
   113686  out:
   113687   rc = sqlite3ApiExit(db, rc);
   113688   sqlite3_mutex_leave(db->mutex);
   113689   return rc;
   113690 }
   113691 
   113692 #ifndef SQLITE_OMIT_UTF16
   113693 SQLITE_API int sqlite3_create_function16(
   113694   sqlite3 *db,
   113695   const void *zFunctionName,
   113696   int nArg,
   113697   int eTextRep,
   113698   void *p,
   113699   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   113700   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   113701   void (*xFinal)(sqlite3_context*)
   113702 ){
   113703   int rc;
   113704   char *zFunc8;
   113705   sqlite3_mutex_enter(db->mutex);
   113706   assert( !db->mallocFailed );
   113707   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   113708   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   113709   sqlite3DbFree(db, zFunc8);
   113710   rc = sqlite3ApiExit(db, rc);
   113711   sqlite3_mutex_leave(db->mutex);
   113712   return rc;
   113713 }
   113714 #endif
   113715 
   113716 
   113717 /*
   113718 ** Declare that a function has been overloaded by a virtual table.
   113719 **
   113720 ** If the function already exists as a regular global function, then
   113721 ** this routine is a no-op.  If the function does not exist, then create
   113722 ** a new one that always throws a run-time error.
   113723 **
   113724 ** When virtual tables intend to provide an overloaded function, they
   113725 ** should call this routine to make sure the global function exists.
   113726 ** A global function must exist in order for name resolution to work
   113727 ** properly.
   113728 */
   113729 SQLITE_API int sqlite3_overload_function(
   113730   sqlite3 *db,
   113731   const char *zName,
   113732   int nArg
   113733 ){
   113734   int nName = sqlite3Strlen30(zName);
   113735   int rc = SQLITE_OK;
   113736   sqlite3_mutex_enter(db->mutex);
   113737   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   113738     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   113739                            0, sqlite3InvalidFunction, 0, 0, 0);
   113740   }
   113741   rc = sqlite3ApiExit(db, rc);
   113742   sqlite3_mutex_leave(db->mutex);
   113743   return rc;
   113744 }
   113745 
   113746 #ifndef SQLITE_OMIT_TRACE
   113747 /*
   113748 ** Register a trace function.  The pArg from the previously registered trace
   113749 ** is returned.
   113750 **
   113751 ** A NULL trace function means that no tracing is executes.  A non-NULL
   113752 ** trace is a pointer to a function that is invoked at the start of each
   113753 ** SQL statement.
   113754 */
   113755 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   113756   void *pOld;
   113757   sqlite3_mutex_enter(db->mutex);
   113758   pOld = db->pTraceArg;
   113759   db->xTrace = xTrace;
   113760   db->pTraceArg = pArg;
   113761   sqlite3_mutex_leave(db->mutex);
   113762   return pOld;
   113763 }
   113764 /*
   113765 ** Register a profile function.  The pArg from the previously registered
   113766 ** profile function is returned.
   113767 **
   113768 ** A NULL profile function means that no profiling is executes.  A non-NULL
   113769 ** profile is a pointer to a function that is invoked at the conclusion of
   113770 ** each SQL statement that is run.
   113771 */
   113772 SQLITE_API void *sqlite3_profile(
   113773   sqlite3 *db,
   113774   void (*xProfile)(void*,const char*,sqlite_uint64),
   113775   void *pArg
   113776 ){
   113777   void *pOld;
   113778   sqlite3_mutex_enter(db->mutex);
   113779   pOld = db->pProfileArg;
   113780   db->xProfile = xProfile;
   113781   db->pProfileArg = pArg;
   113782   sqlite3_mutex_leave(db->mutex);
   113783   return pOld;
   113784 }
   113785 #endif /* SQLITE_OMIT_TRACE */
   113786 
   113787 /*
   113788 ** Register a function to be invoked when a transaction commits.
   113789 ** If the invoked function returns non-zero, then the commit becomes a
   113790 ** rollback.
   113791 */
   113792 SQLITE_API void *sqlite3_commit_hook(
   113793   sqlite3 *db,              /* Attach the hook to this database */
   113794   int (*xCallback)(void*),  /* Function to invoke on each commit */
   113795   void *pArg                /* Argument to the function */
   113796 ){
   113797   void *pOld;
   113798   sqlite3_mutex_enter(db->mutex);
   113799   pOld = db->pCommitArg;
   113800   db->xCommitCallback = xCallback;
   113801   db->pCommitArg = pArg;
   113802   sqlite3_mutex_leave(db->mutex);
   113803   return pOld;
   113804 }
   113805 
   113806 /*
   113807 ** Register a callback to be invoked each time a row is updated,
   113808 ** inserted or deleted using this database connection.
   113809 */
   113810 SQLITE_API void *sqlite3_update_hook(
   113811   sqlite3 *db,              /* Attach the hook to this database */
   113812   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   113813   void *pArg                /* Argument to the function */
   113814 ){
   113815   void *pRet;
   113816   sqlite3_mutex_enter(db->mutex);
   113817   pRet = db->pUpdateArg;
   113818   db->xUpdateCallback = xCallback;
   113819   db->pUpdateArg = pArg;
   113820   sqlite3_mutex_leave(db->mutex);
   113821   return pRet;
   113822 }
   113823 
   113824 /*
   113825 ** Register a callback to be invoked each time a transaction is rolled
   113826 ** back by this database connection.
   113827 */
   113828 SQLITE_API void *sqlite3_rollback_hook(
   113829   sqlite3 *db,              /* Attach the hook to this database */
   113830   void (*xCallback)(void*), /* Callback function */
   113831   void *pArg                /* Argument to the function */
   113832 ){
   113833   void *pRet;
   113834   sqlite3_mutex_enter(db->mutex);
   113835   pRet = db->pRollbackArg;
   113836   db->xRollbackCallback = xCallback;
   113837   db->pRollbackArg = pArg;
   113838   sqlite3_mutex_leave(db->mutex);
   113839   return pRet;
   113840 }
   113841 
   113842 #ifndef SQLITE_OMIT_WAL
   113843 /*
   113844 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   113845 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   113846 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   113847 ** wal_autocheckpoint()).
   113848 */
   113849 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   113850   void *pClientData,     /* Argument */
   113851   sqlite3 *db,           /* Connection */
   113852   const char *zDb,       /* Database */
   113853   int nFrame             /* Size of WAL */
   113854 ){
   113855   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   113856     sqlite3BeginBenignMalloc();
   113857     sqlite3_wal_checkpoint(db, zDb);
   113858     sqlite3EndBenignMalloc();
   113859   }
   113860   return SQLITE_OK;
   113861 }
   113862 #endif /* SQLITE_OMIT_WAL */
   113863 
   113864 /*
   113865 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   113866 ** a database after committing a transaction if there are nFrame or
   113867 ** more frames in the log file. Passing zero or a negative value as the
   113868 ** nFrame parameter disables automatic checkpoints entirely.
   113869 **
   113870 ** The callback registered by this function replaces any existing callback
   113871 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   113872 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   113873 ** configured by this function.
   113874 */
   113875 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   113876 #ifdef SQLITE_OMIT_WAL
   113877   UNUSED_PARAMETER(db);
   113878   UNUSED_PARAMETER(nFrame);
   113879 #else
   113880   if( nFrame>0 ){
   113881     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   113882   }else{
   113883     sqlite3_wal_hook(db, 0, 0);
   113884   }
   113885 #endif
   113886   return SQLITE_OK;
   113887 }
   113888 
   113889 /*
   113890 ** Register a callback to be invoked each time a transaction is written
   113891 ** into the write-ahead-log by this database connection.
   113892 */
   113893 SQLITE_API void *sqlite3_wal_hook(
   113894   sqlite3 *db,                    /* Attach the hook to this db handle */
   113895   int(*xCallback)(void *, sqlite3*, const char*, int),
   113896   void *pArg                      /* First argument passed to xCallback() */
   113897 ){
   113898 #ifndef SQLITE_OMIT_WAL
   113899   void *pRet;
   113900   sqlite3_mutex_enter(db->mutex);
   113901   pRet = db->pWalArg;
   113902   db->xWalCallback = xCallback;
   113903   db->pWalArg = pArg;
   113904   sqlite3_mutex_leave(db->mutex);
   113905   return pRet;
   113906 #else
   113907   return 0;
   113908 #endif
   113909 }
   113910 
   113911 /*
   113912 ** Checkpoint database zDb.
   113913 */
   113914 SQLITE_API int sqlite3_wal_checkpoint_v2(
   113915   sqlite3 *db,                    /* Database handle */
   113916   const char *zDb,                /* Name of attached database (or NULL) */
   113917   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   113918   int *pnLog,                     /* OUT: Size of WAL log in frames */
   113919   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   113920 ){
   113921 #ifdef SQLITE_OMIT_WAL
   113922   return SQLITE_OK;
   113923 #else
   113924   int rc;                         /* Return code */
   113925   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   113926 
   113927   /* Initialize the output variables to -1 in case an error occurs. */
   113928   if( pnLog ) *pnLog = -1;
   113929   if( pnCkpt ) *pnCkpt = -1;
   113930 
   113931   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
   113932   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
   113933   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
   113934   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
   113935     return SQLITE_MISUSE;
   113936   }
   113937 
   113938   sqlite3_mutex_enter(db->mutex);
   113939   if( zDb && zDb[0] ){
   113940     iDb = sqlite3FindDbName(db, zDb);
   113941   }
   113942   if( iDb<0 ){
   113943     rc = SQLITE_ERROR;
   113944     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   113945   }else{
   113946     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   113947     sqlite3Error(db, rc, 0);
   113948   }
   113949   rc = sqlite3ApiExit(db, rc);
   113950   sqlite3_mutex_leave(db->mutex);
   113951   return rc;
   113952 #endif
   113953 }
   113954 
   113955 
   113956 /*
   113957 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   113958 ** to contains a zero-length string, all attached databases are
   113959 ** checkpointed.
   113960 */
   113961 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   113962   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
   113963 }
   113964 
   113965 #ifndef SQLITE_OMIT_WAL
   113966 /*
   113967 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   113968 ** not currently open in WAL mode.
   113969 **
   113970 ** If a transaction is open on the database being checkpointed, this
   113971 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   113972 ** an error occurs while running the checkpoint, an SQLite error code is
   113973 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   113974 **
   113975 ** The mutex on database handle db should be held by the caller. The mutex
   113976 ** associated with the specific b-tree being checkpointed is taken by
   113977 ** this function while the checkpoint is running.
   113978 **
   113979 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   113980 ** checkpointed. If an error is encountered it is returned immediately -
   113981 ** no attempt is made to checkpoint any remaining databases.
   113982 **
   113983 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   113984 */
   113985 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   113986   int rc = SQLITE_OK;             /* Return code */
   113987   int i;                          /* Used to iterate through attached dbs */
   113988   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   113989 
   113990   assert( sqlite3_mutex_held(db->mutex) );
   113991   assert( !pnLog || *pnLog==-1 );
   113992   assert( !pnCkpt || *pnCkpt==-1 );
   113993 
   113994   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   113995     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   113996       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   113997       pnLog = 0;
   113998       pnCkpt = 0;
   113999       if( rc==SQLITE_BUSY ){
   114000         bBusy = 1;
   114001         rc = SQLITE_OK;
   114002       }
   114003     }
   114004   }
   114005 
   114006   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   114007 }
   114008 #endif /* SQLITE_OMIT_WAL */
   114009 
   114010 /*
   114011 ** This function returns true if main-memory should be used instead of
   114012 ** a temporary file for transient pager files and statement journals.
   114013 ** The value returned depends on the value of db->temp_store (runtime
   114014 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   114015 ** following table describes the relationship between these two values
   114016 ** and this functions return value.
   114017 **
   114018 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   114019 **   -----------------     --------------     ------------------------------
   114020 **   0                     any                file      (return 0)
   114021 **   1                     1                  file      (return 0)
   114022 **   1                     2                  memory    (return 1)
   114023 **   1                     0                  file      (return 0)
   114024 **   2                     1                  file      (return 0)
   114025 **   2                     2                  memory    (return 1)
   114026 **   2                     0                  memory    (return 1)
   114027 **   3                     any                memory    (return 1)
   114028 */
   114029 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   114030 #if SQLITE_TEMP_STORE==1
   114031   return ( db->temp_store==2 );
   114032 #endif
   114033 #if SQLITE_TEMP_STORE==2
   114034   return ( db->temp_store!=1 );
   114035 #endif
   114036 #if SQLITE_TEMP_STORE==3
   114037   return 1;
   114038 #endif
   114039 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   114040   return 0;
   114041 #endif
   114042 }
   114043 
   114044 /*
   114045 ** Return UTF-8 encoded English language explanation of the most recent
   114046 ** error.
   114047 */
   114048 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   114049   const char *z;
   114050   if( !db ){
   114051     return sqlite3ErrStr(SQLITE_NOMEM);
   114052   }
   114053   if( !sqlite3SafetyCheckSickOrOk(db) ){
   114054     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   114055   }
   114056   sqlite3_mutex_enter(db->mutex);
   114057   if( db->mallocFailed ){
   114058     z = sqlite3ErrStr(SQLITE_NOMEM);
   114059   }else{
   114060     z = (char*)sqlite3_value_text(db->pErr);
   114061     assert( !db->mallocFailed );
   114062     if( z==0 ){
   114063       z = sqlite3ErrStr(db->errCode);
   114064     }
   114065   }
   114066   sqlite3_mutex_leave(db->mutex);
   114067   return z;
   114068 }
   114069 
   114070 #ifndef SQLITE_OMIT_UTF16
   114071 /*
   114072 ** Return UTF-16 encoded English language explanation of the most recent
   114073 ** error.
   114074 */
   114075 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   114076   static const u16 outOfMem[] = {
   114077     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   114078   };
   114079   static const u16 misuse[] = {
   114080     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   114081     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   114082     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   114083     'o', 'u', 't', ' ',
   114084     'o', 'f', ' ',
   114085     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   114086   };
   114087 
   114088   const void *z;
   114089   if( !db ){
   114090     return (void *)outOfMem;
   114091   }
   114092   if( !sqlite3SafetyCheckSickOrOk(db) ){
   114093     return (void *)misuse;
   114094   }
   114095   sqlite3_mutex_enter(db->mutex);
   114096   if( db->mallocFailed ){
   114097     z = (void *)outOfMem;
   114098   }else{
   114099     z = sqlite3_value_text16(db->pErr);
   114100     if( z==0 ){
   114101       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
   114102            SQLITE_UTF8, SQLITE_STATIC);
   114103       z = sqlite3_value_text16(db->pErr);
   114104     }
   114105     /* A malloc() may have failed within the call to sqlite3_value_text16()
   114106     ** above. If this is the case, then the db->mallocFailed flag needs to
   114107     ** be cleared before returning. Do this directly, instead of via
   114108     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   114109     */
   114110     db->mallocFailed = 0;
   114111   }
   114112   sqlite3_mutex_leave(db->mutex);
   114113   return z;
   114114 }
   114115 #endif /* SQLITE_OMIT_UTF16 */
   114116 
   114117 /*
   114118 ** Return the most recent error code generated by an SQLite routine. If NULL is
   114119 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   114120 */
   114121 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   114122   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   114123     return SQLITE_MISUSE_BKPT;
   114124   }
   114125   if( !db || db->mallocFailed ){
   114126     return SQLITE_NOMEM;
   114127   }
   114128   return db->errCode & db->errMask;
   114129 }
   114130 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   114131   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   114132     return SQLITE_MISUSE_BKPT;
   114133   }
   114134   if( !db || db->mallocFailed ){
   114135     return SQLITE_NOMEM;
   114136   }
   114137   return db->errCode;
   114138 }
   114139 
   114140 /*
   114141 ** Create a new collating function for database "db".  The name is zName
   114142 ** and the encoding is enc.
   114143 */
   114144 static int createCollation(
   114145   sqlite3* db,
   114146   const char *zName,
   114147   u8 enc,
   114148   void* pCtx,
   114149   int(*xCompare)(void*,int,const void*,int,const void*),
   114150   void(*xDel)(void*)
   114151 ){
   114152   CollSeq *pColl;
   114153   int enc2;
   114154   int nName = sqlite3Strlen30(zName);
   114155 
   114156   assert( sqlite3_mutex_held(db->mutex) );
   114157 
   114158   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   114159   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   114160   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   114161   */
   114162   enc2 = enc;
   114163   testcase( enc2==SQLITE_UTF16 );
   114164   testcase( enc2==SQLITE_UTF16_ALIGNED );
   114165   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   114166     enc2 = SQLITE_UTF16NATIVE;
   114167   }
   114168   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   114169     return SQLITE_MISUSE_BKPT;
   114170   }
   114171 
   114172   /* Check if this call is removing or replacing an existing collation
   114173   ** sequence. If so, and there are active VMs, return busy. If there
   114174   ** are no active VMs, invalidate any pre-compiled statements.
   114175   */
   114176   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   114177   if( pColl && pColl->xCmp ){
   114178     if( db->activeVdbeCnt ){
   114179       sqlite3Error(db, SQLITE_BUSY,
   114180         "unable to delete/modify collation sequence due to active statements");
   114181       return SQLITE_BUSY;
   114182     }
   114183     sqlite3ExpirePreparedStatements(db);
   114184 
   114185     /* If collation sequence pColl was created directly by a call to
   114186     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   114187     ** then any copies made by synthCollSeq() need to be invalidated.
   114188     ** Also, collation destructor - CollSeq.xDel() - function may need
   114189     ** to be called.
   114190     */
   114191     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   114192       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   114193       int j;
   114194       for(j=0; j<3; j++){
   114195         CollSeq *p = &aColl[j];
   114196         if( p->enc==pColl->enc ){
   114197           if( p->xDel ){
   114198             p->xDel(p->pUser);
   114199           }
   114200           p->xCmp = 0;
   114201         }
   114202       }
   114203     }
   114204   }
   114205 
   114206   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   114207   if( pColl==0 ) return SQLITE_NOMEM;
   114208   pColl->xCmp = xCompare;
   114209   pColl->pUser = pCtx;
   114210   pColl->xDel = xDel;
   114211   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   114212   sqlite3Error(db, SQLITE_OK, 0);
   114213   return SQLITE_OK;
   114214 }
   114215 
   114216 
   114217 /*
   114218 ** This array defines hard upper bounds on limit values.  The
   114219 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   114220 ** #defines in sqlite3.h.
   114221 */
   114222 static const int aHardLimit[] = {
   114223   SQLITE_MAX_LENGTH,
   114224   SQLITE_MAX_SQL_LENGTH,
   114225   SQLITE_MAX_COLUMN,
   114226   SQLITE_MAX_EXPR_DEPTH,
   114227   SQLITE_MAX_COMPOUND_SELECT,
   114228   SQLITE_MAX_VDBE_OP,
   114229   SQLITE_MAX_FUNCTION_ARG,
   114230   SQLITE_MAX_ATTACHED,
   114231   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   114232   SQLITE_MAX_VARIABLE_NUMBER,
   114233   SQLITE_MAX_TRIGGER_DEPTH,
   114234 };
   114235 
   114236 /*
   114237 ** Make sure the hard limits are set to reasonable values
   114238 */
   114239 #if SQLITE_MAX_LENGTH<100
   114240 # error SQLITE_MAX_LENGTH must be at least 100
   114241 #endif
   114242 #if SQLITE_MAX_SQL_LENGTH<100
   114243 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   114244 #endif
   114245 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   114246 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   114247 #endif
   114248 #if SQLITE_MAX_COMPOUND_SELECT<2
   114249 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   114250 #endif
   114251 #if SQLITE_MAX_VDBE_OP<40
   114252 # error SQLITE_MAX_VDBE_OP must be at least 40
   114253 #endif
   114254 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   114255 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   114256 #endif
   114257 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
   114258 # error SQLITE_MAX_ATTACHED must be between 0 and 62
   114259 #endif
   114260 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   114261 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   114262 #endif
   114263 #if SQLITE_MAX_COLUMN>32767
   114264 # error SQLITE_MAX_COLUMN must not exceed 32767
   114265 #endif
   114266 #if SQLITE_MAX_TRIGGER_DEPTH<1
   114267 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   114268 #endif
   114269 
   114270 
   114271 /*
   114272 ** Change the value of a limit.  Report the old value.
   114273 ** If an invalid limit index is supplied, report -1.
   114274 ** Make no changes but still report the old value if the
   114275 ** new limit is negative.
   114276 **
   114277 ** A new lower limit does not shrink existing constructs.
   114278 ** It merely prevents new constructs that exceed the limit
   114279 ** from forming.
   114280 */
   114281 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   114282   int oldLimit;
   114283 
   114284 
   114285   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   114286   ** there is a hard upper bound set at compile-time by a C preprocessor
   114287   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   114288   ** "_MAX_".)
   114289   */
   114290   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   114291   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   114292   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   114293   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   114294   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   114295   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   114296   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   114297   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   114298   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   114299                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   114300   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   114301   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   114302   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   114303 
   114304 
   114305   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   114306     return -1;
   114307   }
   114308   oldLimit = db->aLimit[limitId];
   114309   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   114310     if( newLimit>aHardLimit[limitId] ){
   114311       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   114312     }
   114313     db->aLimit[limitId] = newLimit;
   114314   }
   114315   return oldLimit;                     /* IMP: R-53341-35419 */
   114316 }
   114317 
   114318 /*
   114319 ** This function is used to parse both URIs and non-URI filenames passed by the
   114320 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
   114321 ** URIs specified as part of ATTACH statements.
   114322 **
   114323 ** The first argument to this function is the name of the VFS to use (or
   114324 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
   114325 ** query parameter. The second argument contains the URI (or non-URI filename)
   114326 ** itself. When this function is called the *pFlags variable should contain
   114327 ** the default flags to open the database handle with. The value stored in
   114328 ** *pFlags may be updated before returning if the URI filename contains
   114329 ** "cache=xxx" or "mode=xxx" query parameters.
   114330 **
   114331 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
   114332 ** the VFS that should be used to open the database file. *pzFile is set to
   114333 ** point to a buffer containing the name of the file to open. It is the
   114334 ** responsibility of the caller to eventually call sqlite3_free() to release
   114335 ** this buffer.
   114336 **
   114337 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
   114338 ** may be set to point to a buffer containing an English language error
   114339 ** message. It is the responsibility of the caller to eventually release
   114340 ** this buffer by calling sqlite3_free().
   114341 */
   114342 SQLITE_PRIVATE int sqlite3ParseUri(
   114343   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   114344   const char *zUri,               /* Nul-terminated URI to parse */
   114345   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
   114346   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   114347   char **pzFile,                  /* OUT: Filename component of URI */
   114348   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
   114349 ){
   114350   int rc = SQLITE_OK;
   114351   unsigned int flags = *pFlags;
   114352   const char *zVfs = zDefaultVfs;
   114353   char *zFile;
   114354   char c;
   114355   int nUri = sqlite3Strlen30(zUri);
   114356 
   114357   assert( *pzErrMsg==0 );
   114358 
   114359   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
   114360    && nUri>=5 && memcmp(zUri, "file:", 5)==0
   114361   ){
   114362     char *zOpt;
   114363     int eState;                   /* Parser state when parsing URI */
   114364     int iIn;                      /* Input character index */
   114365     int iOut = 0;                 /* Output character index */
   114366     int nByte = nUri+2;           /* Bytes of space to allocate */
   114367 
   114368     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
   114369     ** method that there may be extra parameters following the file-name.  */
   114370     flags |= SQLITE_OPEN_URI;
   114371 
   114372     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
   114373     zFile = sqlite3_malloc(nByte);
   114374     if( !zFile ) return SQLITE_NOMEM;
   114375 
   114376     /* Discard the scheme and authority segments of the URI. */
   114377     if( zUri[5]=='/' && zUri[6]=='/' ){
   114378       iIn = 7;
   114379       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
   114380 
   114381       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
   114382         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
   114383             iIn-7, &zUri[7]);
   114384         rc = SQLITE_ERROR;
   114385         goto parse_uri_out;
   114386       }
   114387     }else{
   114388       iIn = 5;
   114389     }
   114390 
   114391     /* Copy the filename and any query parameters into the zFile buffer.
   114392     ** Decode %HH escape codes along the way.
   114393     **
   114394     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
   114395     ** on the parsing context. As follows:
   114396     **
   114397     **   0: Parsing file-name.
   114398     **   1: Parsing name section of a name=value query parameter.
   114399     **   2: Parsing value section of a name=value query parameter.
   114400     */
   114401     eState = 0;
   114402     while( (c = zUri[iIn])!=0 && c!='#' ){
   114403       iIn++;
   114404       if( c=='%'
   114405        && sqlite3Isxdigit(zUri[iIn])
   114406        && sqlite3Isxdigit(zUri[iIn+1])
   114407       ){
   114408         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
   114409         octet += sqlite3HexToInt(zUri[iIn++]);
   114410 
   114411         assert( octet>=0 && octet<256 );
   114412         if( octet==0 ){
   114413           /* This branch is taken when "%00" appears within the URI. In this
   114414           ** case we ignore all text in the remainder of the path, name or
   114415           ** value currently being parsed. So ignore the current character
   114416           ** and skip to the next "?", "=" or "&", as appropriate. */
   114417           while( (c = zUri[iIn])!=0 && c!='#'
   114418               && (eState!=0 || c!='?')
   114419               && (eState!=1 || (c!='=' && c!='&'))
   114420               && (eState!=2 || c!='&')
   114421           ){
   114422             iIn++;
   114423           }
   114424           continue;
   114425         }
   114426         c = octet;
   114427       }else if( eState==1 && (c=='&' || c=='=') ){
   114428         if( zFile[iOut-1]==0 ){
   114429           /* An empty option name. Ignore this option altogether. */
   114430           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
   114431           continue;
   114432         }
   114433         if( c=='&' ){
   114434           zFile[iOut++] = '\0';
   114435         }else{
   114436           eState = 2;
   114437         }
   114438         c = 0;
   114439       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
   114440         c = 0;
   114441         eState = 1;
   114442       }
   114443       zFile[iOut++] = c;
   114444     }
   114445     if( eState==1 ) zFile[iOut++] = '\0';
   114446     zFile[iOut++] = '\0';
   114447     zFile[iOut++] = '\0';
   114448 
   114449     /* Check if there were any options specified that should be interpreted
   114450     ** here. Options that are interpreted here include "vfs" and those that
   114451     ** correspond to flags that may be passed to the sqlite3_open_v2()
   114452     ** method. */
   114453     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
   114454     while( zOpt[0] ){
   114455       int nOpt = sqlite3Strlen30(zOpt);
   114456       char *zVal = &zOpt[nOpt+1];
   114457       int nVal = sqlite3Strlen30(zVal);
   114458 
   114459       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
   114460         zVfs = zVal;
   114461       }else{
   114462         struct OpenMode {
   114463           const char *z;
   114464           int mode;
   114465         } *aMode = 0;
   114466         char *zModeType = 0;
   114467         int mask = 0;
   114468         int limit = 0;
   114469 
   114470         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
   114471           static struct OpenMode aCacheMode[] = {
   114472             { "shared",  SQLITE_OPEN_SHAREDCACHE },
   114473             { "private", SQLITE_OPEN_PRIVATECACHE },
   114474             { 0, 0 }
   114475           };
   114476 
   114477           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
   114478           aMode = aCacheMode;
   114479           limit = mask;
   114480           zModeType = "cache";
   114481         }
   114482         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
   114483           static struct OpenMode aOpenMode[] = {
   114484             { "ro",  SQLITE_OPEN_READONLY },
   114485             { "rw",  SQLITE_OPEN_READWRITE },
   114486             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
   114487             { 0, 0 }
   114488           };
   114489 
   114490           mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   114491           aMode = aOpenMode;
   114492           limit = mask & flags;
   114493           zModeType = "access";
   114494         }
   114495 
   114496         if( aMode ){
   114497           int i;
   114498           int mode = 0;
   114499           for(i=0; aMode[i].z; i++){
   114500             const char *z = aMode[i].z;
   114501             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
   114502               mode = aMode[i].mode;
   114503               break;
   114504             }
   114505           }
   114506           if( mode==0 ){
   114507             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
   114508             rc = SQLITE_ERROR;
   114509             goto parse_uri_out;
   114510           }
   114511           if( mode>limit ){
   114512             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
   114513                                         zModeType, zVal);
   114514             rc = SQLITE_PERM;
   114515             goto parse_uri_out;
   114516           }
   114517           flags = (flags & ~mask) | mode;
   114518         }
   114519       }
   114520 
   114521       zOpt = &zVal[nVal+1];
   114522     }
   114523 
   114524   }else{
   114525     zFile = sqlite3_malloc(nUri+2);
   114526     if( !zFile ) return SQLITE_NOMEM;
   114527     memcpy(zFile, zUri, nUri);
   114528     zFile[nUri] = '\0';
   114529     zFile[nUri+1] = '\0';
   114530   }
   114531 
   114532   *ppVfs = sqlite3_vfs_find(zVfs);
   114533   if( *ppVfs==0 ){
   114534     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
   114535     rc = SQLITE_ERROR;
   114536   }
   114537  parse_uri_out:
   114538   if( rc!=SQLITE_OK ){
   114539     sqlite3_free(zFile);
   114540     zFile = 0;
   114541   }
   114542   *pFlags = flags;
   114543   *pzFile = zFile;
   114544   return rc;
   114545 }
   114546 
   114547 
   114548 /*
   114549 ** This routine does the work of opening a database on behalf of
   114550 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   114551 ** is UTF-8 encoded.
   114552 */
   114553 static int openDatabase(
   114554   const char *zFilename, /* Database filename UTF-8 encoded */
   114555   sqlite3 **ppDb,        /* OUT: Returned database handle */
   114556   unsigned int flags,    /* Operational flags */
   114557   const char *zVfs       /* Name of the VFS to use */
   114558 ){
   114559   sqlite3 *db;                    /* Store allocated handle here */
   114560   int rc;                         /* Return code */
   114561   int isThreadsafe;               /* True for threadsafe connections */
   114562   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   114563   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
   114564 
   114565   *ppDb = 0;
   114566 #ifndef SQLITE_OMIT_AUTOINIT
   114567   rc = sqlite3_initialize();
   114568   if( rc ) return rc;
   114569 #endif
   114570 
   114571   /* Only allow sensible combinations of bits in the flags argument.
   114572   ** Throw an error if any non-sense combination is used.  If we
   114573   ** do not block illegal combinations here, it could trigger
   114574   ** assert() statements in deeper layers.  Sensible combinations
   114575   ** are:
   114576   **
   114577   **  1:  SQLITE_OPEN_READONLY
   114578   **  2:  SQLITE_OPEN_READWRITE
   114579   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   114580   */
   114581   assert( SQLITE_OPEN_READONLY  == 0x01 );
   114582   assert( SQLITE_OPEN_READWRITE == 0x02 );
   114583   assert( SQLITE_OPEN_CREATE    == 0x04 );
   114584   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   114585   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   114586   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   114587   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
   114588 
   114589   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   114590     isThreadsafe = 0;
   114591   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   114592     isThreadsafe = 0;
   114593   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   114594     isThreadsafe = 1;
   114595   }else{
   114596     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   114597   }
   114598   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   114599     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   114600   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   114601     flags |= SQLITE_OPEN_SHAREDCACHE;
   114602   }
   114603 
   114604   /* Remove harmful bits from the flags parameter
   114605   **
   114606   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   114607   ** dealt with in the previous code block.  Besides these, the only
   114608   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   114609   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   114610   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   114611   ** off all other flags.
   114612   */
   114613   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   114614                SQLITE_OPEN_EXCLUSIVE |
   114615                SQLITE_OPEN_MAIN_DB |
   114616                SQLITE_OPEN_TEMP_DB |
   114617                SQLITE_OPEN_TRANSIENT_DB |
   114618                SQLITE_OPEN_MAIN_JOURNAL |
   114619                SQLITE_OPEN_TEMP_JOURNAL |
   114620                SQLITE_OPEN_SUBJOURNAL |
   114621                SQLITE_OPEN_MASTER_JOURNAL |
   114622                SQLITE_OPEN_NOMUTEX |
   114623                SQLITE_OPEN_FULLMUTEX |
   114624                SQLITE_OPEN_WAL
   114625              );
   114626 
   114627   /* Allocate the sqlite data structure */
   114628   db = sqlite3MallocZero( sizeof(sqlite3) );
   114629   if( db==0 ) goto opendb_out;
   114630   if( isThreadsafe ){
   114631     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   114632     if( db->mutex==0 ){
   114633       sqlite3_free(db);
   114634       db = 0;
   114635       goto opendb_out;
   114636     }
   114637   }
   114638   sqlite3_mutex_enter(db->mutex);
   114639   db->errMask = 0xff;
   114640   db->nDb = 2;
   114641   db->magic = SQLITE_MAGIC_BUSY;
   114642   db->aDb = db->aDbStatic;
   114643 
   114644   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   114645   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   114646   db->autoCommit = 1;
   114647   db->nextAutovac = -1;
   114648   db->nextPagesize = 0;
   114649   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
   114650 #if SQLITE_DEFAULT_FILE_FORMAT<4
   114651                  | SQLITE_LegacyFileFmt
   114652 #endif
   114653 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   114654                  | SQLITE_LoadExtension
   114655 #endif
   114656 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   114657                  | SQLITE_RecTriggers
   114658 #endif
   114659 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   114660                  | SQLITE_ForeignKeys
   114661 #endif
   114662       ;
   114663   sqlite3HashInit(&db->aCollSeq);
   114664 #ifndef SQLITE_OMIT_VIRTUALTABLE
   114665   sqlite3HashInit(&db->aModule);
   114666 #endif
   114667 
   114668   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   114669   ** and UTF-16, so add a version for each to avoid any unnecessary
   114670   ** conversions. The only error that can occur here is a malloc() failure.
   114671   */
   114672   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
   114673   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
   114674   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
   114675   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
   114676   if( db->mallocFailed ){
   114677     goto opendb_out;
   114678   }
   114679   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   114680   assert( db->pDfltColl!=0 );
   114681 
   114682   /* Also add a UTF-8 case-insensitive collation sequence. */
   114683   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
   114684 
   114685   /* Parse the filename/URI argument. */
   114686   db->openFlags = flags;
   114687   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   114688   if( rc!=SQLITE_OK ){
   114689     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   114690     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
   114691     sqlite3_free(zErrMsg);
   114692     goto opendb_out;
   114693   }
   114694 
   114695   /* Open the backend database driver */
   114696   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
   114697                         flags | SQLITE_OPEN_MAIN_DB);
   114698   if( rc!=SQLITE_OK ){
   114699     if( rc==SQLITE_IOERR_NOMEM ){
   114700       rc = SQLITE_NOMEM;
   114701     }
   114702     sqlite3Error(db, rc, 0);
   114703     goto opendb_out;
   114704   }
   114705   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   114706   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   114707 
   114708 
   114709   /* The default safety_level for the main database is 'full'; for the temp
   114710   ** database it is 'NONE'. This matches the pager layer defaults.
   114711   */
   114712   db->aDb[0].zName = "main";
   114713   db->aDb[0].safety_level = 3;
   114714   db->aDb[1].zName = "temp";
   114715   db->aDb[1].safety_level = 1;
   114716 
   114717   db->magic = SQLITE_MAGIC_OPEN;
   114718   if( db->mallocFailed ){
   114719     goto opendb_out;
   114720   }
   114721 
   114722   /* Register all built-in functions, but do not attempt to read the
   114723   ** database schema yet. This is delayed until the first time the database
   114724   ** is accessed.
   114725   */
   114726   sqlite3Error(db, SQLITE_OK, 0);
   114727   sqlite3RegisterBuiltinFunctions(db);
   114728 
   114729   /* Load automatic extensions - extensions that have been registered
   114730   ** using the sqlite3_automatic_extension() API.
   114731   */
   114732   rc = sqlite3_errcode(db);
   114733   if( rc==SQLITE_OK ){
   114734     sqlite3AutoLoadExtensions(db);
   114735     rc = sqlite3_errcode(db);
   114736     if( rc!=SQLITE_OK ){
   114737       goto opendb_out;
   114738     }
   114739   }
   114740 
   114741 #ifdef SQLITE_ENABLE_FTS1
   114742   if( !db->mallocFailed ){
   114743     extern int sqlite3Fts1Init(sqlite3*);
   114744     rc = sqlite3Fts1Init(db);
   114745   }
   114746 #endif
   114747 
   114748 #ifdef SQLITE_ENABLE_FTS2
   114749   if( !db->mallocFailed && rc==SQLITE_OK ){
   114750     extern int sqlite3Fts2Init(sqlite3*);
   114751     rc = sqlite3Fts2Init(db);
   114752   }
   114753 #endif
   114754 
   114755 #ifdef SQLITE_ENABLE_FTS3
   114756     if( !db->mallocFailed && rc==SQLITE_OK ){
   114757       rc = sqlite3Fts3Init(db);
   114758     }
   114759 #endif
   114760 
   114761 #ifdef SQLITE_ENABLE_ICU
   114762   if( !db->mallocFailed && rc==SQLITE_OK ){
   114763     rc = sqlite3IcuInit(db);
   114764   }
   114765 #endif
   114766 
   114767 #ifdef SQLITE_ENABLE_RTREE
   114768   if( !db->mallocFailed && rc==SQLITE_OK){
   114769     rc = sqlite3RtreeInit(db);
   114770   }
   114771 #endif
   114772 
   114773   sqlite3Error(db, rc, 0);
   114774 
   114775   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   114776   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   114777   ** mode.  Doing nothing at all also makes NORMAL the default.
   114778   */
   114779 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   114780   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   114781   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   114782                           SQLITE_DEFAULT_LOCKING_MODE);
   114783 #endif
   114784 
   114785   /* Enable the lookaside-malloc subsystem */
   114786   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   114787                         sqlite3GlobalConfig.nLookaside);
   114788 
   114789   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   114790 
   114791 opendb_out:
   114792   sqlite3_free(zOpen);
   114793   if( db ){
   114794     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   114795     sqlite3_mutex_leave(db->mutex);
   114796   }
   114797   rc = sqlite3_errcode(db);
   114798   assert( db!=0 || rc==SQLITE_NOMEM );
   114799   if( rc==SQLITE_NOMEM ){
   114800     sqlite3_close(db);
   114801     db = 0;
   114802   }else if( rc!=SQLITE_OK ){
   114803     db->magic = SQLITE_MAGIC_SICK;
   114804   }
   114805   *ppDb = db;
   114806   return sqlite3ApiExit(0, rc);
   114807 }
   114808 
   114809 /*
   114810 ** Open a new database handle.
   114811 */
   114812 SQLITE_API int sqlite3_open(
   114813   const char *zFilename,
   114814   sqlite3 **ppDb
   114815 ){
   114816   return openDatabase(zFilename, ppDb,
   114817                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   114818 }
   114819 SQLITE_API int sqlite3_open_v2(
   114820   const char *filename,   /* Database filename (UTF-8) */
   114821   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   114822   int flags,              /* Flags */
   114823   const char *zVfs        /* Name of VFS module to use */
   114824 ){
   114825   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
   114826 }
   114827 
   114828 #ifndef SQLITE_OMIT_UTF16
   114829 /*
   114830 ** Open a new database handle.
   114831 */
   114832 SQLITE_API int sqlite3_open16(
   114833   const void *zFilename,
   114834   sqlite3 **ppDb
   114835 ){
   114836   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   114837   sqlite3_value *pVal;
   114838   int rc;
   114839 
   114840   assert( zFilename );
   114841   assert( ppDb );
   114842   *ppDb = 0;
   114843 #ifndef SQLITE_OMIT_AUTOINIT
   114844   rc = sqlite3_initialize();
   114845   if( rc ) return rc;
   114846 #endif
   114847   pVal = sqlite3ValueNew(0);
   114848   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   114849   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   114850   if( zFilename8 ){
   114851     rc = openDatabase(zFilename8, ppDb,
   114852                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   114853     assert( *ppDb || rc==SQLITE_NOMEM );
   114854     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   114855       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   114856     }
   114857   }else{
   114858     rc = SQLITE_NOMEM;
   114859   }
   114860   sqlite3ValueFree(pVal);
   114861 
   114862   return sqlite3ApiExit(0, rc);
   114863 }
   114864 #endif /* SQLITE_OMIT_UTF16 */
   114865 
   114866 /*
   114867 ** Register a new collation sequence with the database handle db.
   114868 */
   114869 SQLITE_API int sqlite3_create_collation(
   114870   sqlite3* db,
   114871   const char *zName,
   114872   int enc,
   114873   void* pCtx,
   114874   int(*xCompare)(void*,int,const void*,int,const void*)
   114875 ){
   114876   int rc;
   114877   sqlite3_mutex_enter(db->mutex);
   114878   assert( !db->mallocFailed );
   114879   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
   114880   rc = sqlite3ApiExit(db, rc);
   114881   sqlite3_mutex_leave(db->mutex);
   114882   return rc;
   114883 }
   114884 
   114885 /*
   114886 ** Register a new collation sequence with the database handle db.
   114887 */
   114888 SQLITE_API int sqlite3_create_collation_v2(
   114889   sqlite3* db,
   114890   const char *zName,
   114891   int enc,
   114892   void* pCtx,
   114893   int(*xCompare)(void*,int,const void*,int,const void*),
   114894   void(*xDel)(void*)
   114895 ){
   114896   int rc;
   114897   sqlite3_mutex_enter(db->mutex);
   114898   assert( !db->mallocFailed );
   114899   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
   114900   rc = sqlite3ApiExit(db, rc);
   114901   sqlite3_mutex_leave(db->mutex);
   114902   return rc;
   114903 }
   114904 
   114905 #ifndef SQLITE_OMIT_UTF16
   114906 /*
   114907 ** Register a new collation sequence with the database handle db.
   114908 */
   114909 SQLITE_API int sqlite3_create_collation16(
   114910   sqlite3* db,
   114911   const void *zName,
   114912   int enc,
   114913   void* pCtx,
   114914   int(*xCompare)(void*,int,const void*,int,const void*)
   114915 ){
   114916   int rc = SQLITE_OK;
   114917   char *zName8;
   114918   sqlite3_mutex_enter(db->mutex);
   114919   assert( !db->mallocFailed );
   114920   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   114921   if( zName8 ){
   114922     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
   114923     sqlite3DbFree(db, zName8);
   114924   }
   114925   rc = sqlite3ApiExit(db, rc);
   114926   sqlite3_mutex_leave(db->mutex);
   114927   return rc;
   114928 }
   114929 #endif /* SQLITE_OMIT_UTF16 */
   114930 
   114931 /*
   114932 ** Register a collation sequence factory callback with the database handle
   114933 ** db. Replace any previously installed collation sequence factory.
   114934 */
   114935 SQLITE_API int sqlite3_collation_needed(
   114936   sqlite3 *db,
   114937   void *pCollNeededArg,
   114938   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   114939 ){
   114940   sqlite3_mutex_enter(db->mutex);
   114941   db->xCollNeeded = xCollNeeded;
   114942   db->xCollNeeded16 = 0;
   114943   db->pCollNeededArg = pCollNeededArg;
   114944   sqlite3_mutex_leave(db->mutex);
   114945   return SQLITE_OK;
   114946 }
   114947 
   114948 #ifndef SQLITE_OMIT_UTF16
   114949 /*
   114950 ** Register a collation sequence factory callback with the database handle
   114951 ** db. Replace any previously installed collation sequence factory.
   114952 */
   114953 SQLITE_API int sqlite3_collation_needed16(
   114954   sqlite3 *db,
   114955   void *pCollNeededArg,
   114956   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   114957 ){
   114958   sqlite3_mutex_enter(db->mutex);
   114959   db->xCollNeeded = 0;
   114960   db->xCollNeeded16 = xCollNeeded16;
   114961   db->pCollNeededArg = pCollNeededArg;
   114962   sqlite3_mutex_leave(db->mutex);
   114963   return SQLITE_OK;
   114964 }
   114965 #endif /* SQLITE_OMIT_UTF16 */
   114966 
   114967 #ifndef SQLITE_OMIT_DEPRECATED
   114968 /*
   114969 ** This function is now an anachronism. It used to be used to recover from a
   114970 ** malloc() failure, but SQLite now does this automatically.
   114971 */
   114972 SQLITE_API int sqlite3_global_recover(void){
   114973   return SQLITE_OK;
   114974 }
   114975 #endif
   114976 
   114977 /*
   114978 ** Test to see whether or not the database connection is in autocommit
   114979 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   114980 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   114981 ** by the next COMMIT or ROLLBACK.
   114982 **
   114983 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
   114984 */
   114985 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   114986   return db->autoCommit;
   114987 }
   114988 
   114989 /*
   114990 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   114991 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   114992 ** constants.  They server two purposes:
   114993 **
   114994 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   114995 **       to detect when version error conditions occurs.
   114996 **
   114997 **   2.  Invoke sqlite3_log() to provide the source code location where
   114998 **       a low-level error is first detected.
   114999 */
   115000 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   115001   testcase( sqlite3GlobalConfig.xLog!=0 );
   115002   sqlite3_log(SQLITE_CORRUPT,
   115003               "database corruption at line %d of [%.10s]",
   115004               lineno, 20+sqlite3_sourceid());
   115005   return SQLITE_CORRUPT;
   115006 }
   115007 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   115008   testcase( sqlite3GlobalConfig.xLog!=0 );
   115009   sqlite3_log(SQLITE_MISUSE,
   115010               "misuse at line %d of [%.10s]",
   115011               lineno, 20+sqlite3_sourceid());
   115012   return SQLITE_MISUSE;
   115013 }
   115014 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   115015   testcase( sqlite3GlobalConfig.xLog!=0 );
   115016   sqlite3_log(SQLITE_CANTOPEN,
   115017               "cannot open file at line %d of [%.10s]",
   115018               lineno, 20+sqlite3_sourceid());
   115019   return SQLITE_CANTOPEN;
   115020 }
   115021 
   115022 
   115023 #ifndef SQLITE_OMIT_DEPRECATED
   115024 /*
   115025 ** This is a convenience routine that makes sure that all thread-specific
   115026 ** data for this thread has been deallocated.
   115027 **
   115028 ** SQLite no longer uses thread-specific data so this routine is now a
   115029 ** no-op.  It is retained for historical compatibility.
   115030 */
   115031 SQLITE_API void sqlite3_thread_cleanup(void){
   115032 }
   115033 #endif
   115034 
   115035 /*
   115036 ** Return meta information about a specific column of a database table.
   115037 ** See comment in sqlite3.h (sqlite.h.in) for details.
   115038 */
   115039 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   115040 SQLITE_API int sqlite3_table_column_metadata(
   115041   sqlite3 *db,                /* Connection handle */
   115042   const char *zDbName,        /* Database name or NULL */
   115043   const char *zTableName,     /* Table name */
   115044   const char *zColumnName,    /* Column name */
   115045   char const **pzDataType,    /* OUTPUT: Declared data type */
   115046   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   115047   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   115048   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   115049   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   115050 ){
   115051   int rc;
   115052   char *zErrMsg = 0;
   115053   Table *pTab = 0;
   115054   Column *pCol = 0;
   115055   int iCol;
   115056 
   115057   char const *zDataType = 0;
   115058   char const *zCollSeq = 0;
   115059   int notnull = 0;
   115060   int primarykey = 0;
   115061   int autoinc = 0;
   115062 
   115063   /* Ensure the database schema has been loaded */
   115064   sqlite3_mutex_enter(db->mutex);
   115065   sqlite3BtreeEnterAll(db);
   115066   rc = sqlite3Init(db, &zErrMsg);
   115067   if( SQLITE_OK!=rc ){
   115068     goto error_out;
   115069   }
   115070 
   115071   /* Locate the table in question */
   115072   pTab = sqlite3FindTable(db, zTableName, zDbName);
   115073   if( !pTab || pTab->pSelect ){
   115074     pTab = 0;
   115075     goto error_out;
   115076   }
   115077 
   115078   /* Find the column for which info is requested */
   115079   if( sqlite3IsRowid(zColumnName) ){
   115080     iCol = pTab->iPKey;
   115081     if( iCol>=0 ){
   115082       pCol = &pTab->aCol[iCol];
   115083     }
   115084   }else{
   115085     for(iCol=0; iCol<pTab->nCol; iCol++){
   115086       pCol = &pTab->aCol[iCol];
   115087       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   115088         break;
   115089       }
   115090     }
   115091     if( iCol==pTab->nCol ){
   115092       pTab = 0;
   115093       goto error_out;
   115094     }
   115095   }
   115096 
   115097   /* The following block stores the meta information that will be returned
   115098   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   115099   ** and autoinc. At this point there are two possibilities:
   115100   **
   115101   **     1. The specified column name was rowid", "oid" or "_rowid_"
   115102   **        and there is no explicitly declared IPK column.
   115103   **
   115104   **     2. The table is not a view and the column name identified an
   115105   **        explicitly declared column. Copy meta information from *pCol.
   115106   */
   115107   if( pCol ){
   115108     zDataType = pCol->zType;
   115109     zCollSeq = pCol->zColl;
   115110     notnull = pCol->notNull!=0;
   115111     primarykey  = pCol->isPrimKey!=0;
   115112     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   115113   }else{
   115114     zDataType = "INTEGER";
   115115     primarykey = 1;
   115116   }
   115117   if( !zCollSeq ){
   115118     zCollSeq = "BINARY";
   115119   }
   115120 
   115121 error_out:
   115122   sqlite3BtreeLeaveAll(db);
   115123 
   115124   /* Whether the function call succeeded or failed, set the output parameters
   115125   ** to whatever their local counterparts contain. If an error did occur,
   115126   ** this has the effect of zeroing all output parameters.
   115127   */
   115128   if( pzDataType ) *pzDataType = zDataType;
   115129   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   115130   if( pNotNull ) *pNotNull = notnull;
   115131   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   115132   if( pAutoinc ) *pAutoinc = autoinc;
   115133 
   115134   if( SQLITE_OK==rc && !pTab ){
   115135     sqlite3DbFree(db, zErrMsg);
   115136     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   115137         zColumnName);
   115138     rc = SQLITE_ERROR;
   115139   }
   115140   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   115141   sqlite3DbFree(db, zErrMsg);
   115142   rc = sqlite3ApiExit(db, rc);
   115143   sqlite3_mutex_leave(db->mutex);
   115144   return rc;
   115145 }
   115146 #endif
   115147 
   115148 /*
   115149 ** Sleep for a little while.  Return the amount of time slept.
   115150 */
   115151 SQLITE_API int sqlite3_sleep(int ms){
   115152   sqlite3_vfs *pVfs;
   115153   int rc;
   115154   pVfs = sqlite3_vfs_find(0);
   115155   if( pVfs==0 ) return 0;
   115156 
   115157   /* This function works in milliseconds, but the underlying OsSleep()
   115158   ** API uses microseconds. Hence the 1000's.
   115159   */
   115160   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   115161   return rc;
   115162 }
   115163 
   115164 /*
   115165 ** Enable or disable the extended result codes.
   115166 */
   115167 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   115168   sqlite3_mutex_enter(db->mutex);
   115169   db->errMask = onoff ? 0xffffffff : 0xff;
   115170   sqlite3_mutex_leave(db->mutex);
   115171   return SQLITE_OK;
   115172 }
   115173 
   115174 /*
   115175 ** Invoke the xFileControl method on a particular database.
   115176 */
   115177 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   115178   int rc = SQLITE_ERROR;
   115179   Btree *pBtree;
   115180 
   115181   sqlite3_mutex_enter(db->mutex);
   115182   pBtree = sqlite3DbNameToBtree(db, zDbName);
   115183   if( pBtree ){
   115184     Pager *pPager;
   115185     sqlite3_file *fd;
   115186     sqlite3BtreeEnter(pBtree);
   115187     pPager = sqlite3BtreePager(pBtree);
   115188     assert( pPager!=0 );
   115189     fd = sqlite3PagerFile(pPager);
   115190     assert( fd!=0 );
   115191     if( op==SQLITE_FCNTL_FILE_POINTER ){
   115192       *(sqlite3_file**)pArg = fd;
   115193       rc = SQLITE_OK;
   115194     }else if( fd->pMethods ){
   115195       rc = sqlite3OsFileControl(fd, op, pArg);
   115196     }else{
   115197       rc = SQLITE_NOTFOUND;
   115198     }
   115199     sqlite3BtreeLeave(pBtree);
   115200   }
   115201   sqlite3_mutex_leave(db->mutex);
   115202   return rc;
   115203 }
   115204 
   115205 /*
   115206 ** Interface to the testing logic.
   115207 */
   115208 SQLITE_API int sqlite3_test_control(int op, ...){
   115209   int rc = 0;
   115210 #ifndef SQLITE_OMIT_BUILTIN_TEST
   115211   va_list ap;
   115212   va_start(ap, op);
   115213   switch( op ){
   115214 
   115215     /*
   115216     ** Save the current state of the PRNG.
   115217     */
   115218     case SQLITE_TESTCTRL_PRNG_SAVE: {
   115219       sqlite3PrngSaveState();
   115220       break;
   115221     }
   115222 
   115223     /*
   115224     ** Restore the state of the PRNG to the last state saved using
   115225     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   115226     ** this verb acts like PRNG_RESET.
   115227     */
   115228     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   115229       sqlite3PrngRestoreState();
   115230       break;
   115231     }
   115232 
   115233     /*
   115234     ** Reset the PRNG back to its uninitialized state.  The next call
   115235     ** to sqlite3_randomness() will reseed the PRNG using a single call
   115236     ** to the xRandomness method of the default VFS.
   115237     */
   115238     case SQLITE_TESTCTRL_PRNG_RESET: {
   115239       sqlite3PrngResetState();
   115240       break;
   115241     }
   115242 
   115243     /*
   115244     **  sqlite3_test_control(BITVEC_TEST, size, program)
   115245     **
   115246     ** Run a test against a Bitvec object of size.  The program argument
   115247     ** is an array of integers that defines the test.  Return -1 on a
   115248     ** memory allocation error, 0 on success, or non-zero for an error.
   115249     ** See the sqlite3BitvecBuiltinTest() for additional information.
   115250     */
   115251     case SQLITE_TESTCTRL_BITVEC_TEST: {
   115252       int sz = va_arg(ap, int);
   115253       int *aProg = va_arg(ap, int*);
   115254       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   115255       break;
   115256     }
   115257 
   115258     /*
   115259     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   115260     **
   115261     ** Register hooks to call to indicate which malloc() failures
   115262     ** are benign.
   115263     */
   115264     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   115265       typedef void (*void_function)(void);
   115266       void_function xBenignBegin;
   115267       void_function xBenignEnd;
   115268       xBenignBegin = va_arg(ap, void_function);
   115269       xBenignEnd = va_arg(ap, void_function);
   115270       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   115271       break;
   115272     }
   115273 
   115274     /*
   115275     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   115276     **
   115277     ** Set the PENDING byte to the value in the argument, if X>0.
   115278     ** Make no changes if X==0.  Return the value of the pending byte
   115279     ** as it existing before this routine was called.
   115280     **
   115281     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   115282     ** an incompatible database file format.  Changing the PENDING byte
   115283     ** while any database connection is open results in undefined and
   115284     ** dileterious behavior.
   115285     */
   115286     case SQLITE_TESTCTRL_PENDING_BYTE: {
   115287       rc = PENDING_BYTE;
   115288 #ifndef SQLITE_OMIT_WSD
   115289       {
   115290         unsigned int newVal = va_arg(ap, unsigned int);
   115291         if( newVal ) sqlite3PendingByte = newVal;
   115292       }
   115293 #endif
   115294       break;
   115295     }
   115296 
   115297     /*
   115298     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   115299     **
   115300     ** This action provides a run-time test to see whether or not
   115301     ** assert() was enabled at compile-time.  If X is true and assert()
   115302     ** is enabled, then the return value is true.  If X is true and
   115303     ** assert() is disabled, then the return value is zero.  If X is
   115304     ** false and assert() is enabled, then the assertion fires and the
   115305     ** process aborts.  If X is false and assert() is disabled, then the
   115306     ** return value is zero.
   115307     */
   115308     case SQLITE_TESTCTRL_ASSERT: {
   115309       volatile int x = 0;
   115310       assert( (x = va_arg(ap,int))!=0 );
   115311       rc = x;
   115312       break;
   115313     }
   115314 
   115315 
   115316     /*
   115317     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   115318     **
   115319     ** This action provides a run-time test to see how the ALWAYS and
   115320     ** NEVER macros were defined at compile-time.
   115321     **
   115322     ** The return value is ALWAYS(X).
   115323     **
   115324     ** The recommended test is X==2.  If the return value is 2, that means
   115325     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   115326     ** default setting.  If the return value is 1, then ALWAYS() is either
   115327     ** hard-coded to true or else it asserts if its argument is false.
   115328     ** The first behavior (hard-coded to true) is the case if
   115329     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   115330     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   115331     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   115332     **
   115333     ** The run-time test procedure might look something like this:
   115334     **
   115335     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   115336     **      // ALWAYS() and NEVER() are no-op pass-through macros
   115337     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   115338     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   115339     **    }else{
   115340     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   115341     **    }
   115342     */
   115343     case SQLITE_TESTCTRL_ALWAYS: {
   115344       int x = va_arg(ap,int);
   115345       rc = ALWAYS(x);
   115346       break;
   115347     }
   115348 
   115349     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   115350     **
   115351     ** Set the nReserve size to N for the main database on the database
   115352     ** connection db.
   115353     */
   115354     case SQLITE_TESTCTRL_RESERVE: {
   115355       sqlite3 *db = va_arg(ap, sqlite3*);
   115356       int x = va_arg(ap,int);
   115357       sqlite3_mutex_enter(db->mutex);
   115358       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   115359       sqlite3_mutex_leave(db->mutex);
   115360       break;
   115361     }
   115362 
   115363     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   115364     **
   115365     ** Enable or disable various optimizations for testing purposes.  The
   115366     ** argument N is a bitmask of optimizations to be disabled.  For normal
   115367     ** operation N should be 0.  The idea is that a test program (like the
   115368     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   115369     ** with various optimizations disabled to verify that the same answer
   115370     ** is obtained in every case.
   115371     */
   115372     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   115373       sqlite3 *db = va_arg(ap, sqlite3*);
   115374       int x = va_arg(ap,int);
   115375       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
   115376       break;
   115377     }
   115378 
   115379 #ifdef SQLITE_N_KEYWORD
   115380     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   115381     **
   115382     ** If zWord is a keyword recognized by the parser, then return the
   115383     ** number of keywords.  Or if zWord is not a keyword, return 0.
   115384     **
   115385     ** This test feature is only available in the amalgamation since
   115386     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   115387     ** is built using separate source files.
   115388     */
   115389     case SQLITE_TESTCTRL_ISKEYWORD: {
   115390       const char *zWord = va_arg(ap, const char*);
   115391       int n = sqlite3Strlen30(zWord);
   115392       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   115393       break;
   115394     }
   115395 #endif
   115396 
   115397     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   115398     **
   115399     ** Pass pFree into sqlite3ScratchFree().
   115400     ** If sz>0 then allocate a scratch buffer into pNew.
   115401     */
   115402     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   115403       void *pFree, **ppNew;
   115404       int sz;
   115405       sz = va_arg(ap, int);
   115406       ppNew = va_arg(ap, void**);
   115407       pFree = va_arg(ap, void*);
   115408       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   115409       sqlite3ScratchFree(pFree);
   115410       break;
   115411     }
   115412 
   115413     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
   115414     **
   115415     ** If parameter onoff is non-zero, configure the wrappers so that all
   115416     ** subsequent calls to localtime() and variants fail. If onoff is zero,
   115417     ** undo this setting.
   115418     */
   115419     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
   115420       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
   115421       break;
   115422     }
   115423 
   115424 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   115425     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
   115426     **                        sqlite3_stmt*,const char**);
   115427     **
   115428     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
   115429     ** a string that describes the optimized parse tree.  This test-control
   115430     ** returns a pointer to that string.
   115431     */
   115432     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
   115433       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
   115434       const char **pzRet = va_arg(ap, const char**);
   115435       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
   115436       break;
   115437     }
   115438 #endif
   115439 
   115440   }
   115441   va_end(ap);
   115442 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   115443   return rc;
   115444 }
   115445 
   115446 /*
   115447 ** This is a utility routine, useful to VFS implementations, that checks
   115448 ** to see if a database file was a URI that contained a specific query
   115449 ** parameter, and if so obtains the value of the query parameter.
   115450 **
   115451 ** The zFilename argument is the filename pointer passed into the xOpen()
   115452 ** method of a VFS implementation.  The zParam argument is the name of the
   115453 ** query parameter we seek.  This routine returns the value of the zParam
   115454 ** parameter if it exists.  If the parameter does not exist, this routine
   115455 ** returns a NULL pointer.
   115456 */
   115457 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   115458   if( zFilename==0 ) return 0;
   115459   zFilename += sqlite3Strlen30(zFilename) + 1;
   115460   while( zFilename[0] ){
   115461     int x = strcmp(zFilename, zParam);
   115462     zFilename += sqlite3Strlen30(zFilename) + 1;
   115463     if( x==0 ) return zFilename;
   115464     zFilename += sqlite3Strlen30(zFilename) + 1;
   115465   }
   115466   return 0;
   115467 }
   115468 
   115469 /*
   115470 ** Return a boolean value for a query parameter.
   115471 */
   115472 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
   115473   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   115474   bDflt = bDflt!=0;
   115475   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
   115476 }
   115477 
   115478 /*
   115479 ** Return a 64-bit integer value for a query parameter.
   115480 */
   115481 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
   115482   const char *zFilename,    /* Filename as passed to xOpen */
   115483   const char *zParam,       /* URI parameter sought */
   115484   sqlite3_int64 bDflt       /* return if parameter is missing */
   115485 ){
   115486   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   115487   sqlite3_int64 v;
   115488   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
   115489     bDflt = v;
   115490   }
   115491   return bDflt;
   115492 }
   115493 
   115494 /*
   115495 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
   115496 */
   115497 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
   115498   int i;
   115499   for(i=0; i<db->nDb; i++){
   115500     if( db->aDb[i].pBt
   115501      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
   115502     ){
   115503       return db->aDb[i].pBt;
   115504     }
   115505   }
   115506   return 0;
   115507 }
   115508 
   115509 /*
   115510 ** Return the filename of the database associated with a database
   115511 ** connection.
   115512 */
   115513 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
   115514   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   115515   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
   115516 }
   115517 
   115518 /*
   115519 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
   115520 ** no such database exists.
   115521 */
   115522 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
   115523   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   115524   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
   115525 }
   115526 
   115527 /************** End of main.c ************************************************/
   115528 /************** Begin file notify.c ******************************************/
   115529 /*
   115530 ** 2009 March 3
   115531 **
   115532 ** The author disclaims copyright to this source code.  In place of
   115533 ** a legal notice, here is a blessing:
   115534 **
   115535 **    May you do good and not evil.
   115536 **    May you find forgiveness for yourself and forgive others.
   115537 **    May you share freely, never taking more than you give.
   115538 **
   115539 *************************************************************************
   115540 **
   115541 ** This file contains the implementation of the sqlite3_unlock_notify()
   115542 ** API method and its associated functionality.
   115543 */
   115544 
   115545 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   115546 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   115547 
   115548 /*
   115549 ** Public interfaces:
   115550 **
   115551 **   sqlite3ConnectionBlocked()
   115552 **   sqlite3ConnectionUnlocked()
   115553 **   sqlite3ConnectionClosed()
   115554 **   sqlite3_unlock_notify()
   115555 */
   115556 
   115557 #define assertMutexHeld() \
   115558   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   115559 
   115560 /*
   115561 ** Head of a linked list of all sqlite3 objects created by this process
   115562 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   115563 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   115564 ** mutex is held.
   115565 */
   115566 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   115567 
   115568 #ifndef NDEBUG
   115569 /*
   115570 ** This function is a complex assert() that verifies the following
   115571 ** properties of the blocked connections list:
   115572 **
   115573 **   1) Each entry in the list has a non-NULL value for either
   115574 **      pUnlockConnection or pBlockingConnection, or both.
   115575 **
   115576 **   2) All entries in the list that share a common value for
   115577 **      xUnlockNotify are grouped together.
   115578 **
   115579 **   3) If the argument db is not NULL, then none of the entries in the
   115580 **      blocked connections list have pUnlockConnection or pBlockingConnection
   115581 **      set to db. This is used when closing connection db.
   115582 */
   115583 static void checkListProperties(sqlite3 *db){
   115584   sqlite3 *p;
   115585   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   115586     int seen = 0;
   115587     sqlite3 *p2;
   115588 
   115589     /* Verify property (1) */
   115590     assert( p->pUnlockConnection || p->pBlockingConnection );
   115591 
   115592     /* Verify property (2) */
   115593     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   115594       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   115595       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   115596       assert( db==0 || p->pUnlockConnection!=db );
   115597       assert( db==0 || p->pBlockingConnection!=db );
   115598     }
   115599   }
   115600 }
   115601 #else
   115602 # define checkListProperties(x)
   115603 #endif
   115604 
   115605 /*
   115606 ** Remove connection db from the blocked connections list. If connection
   115607 ** db is not currently a part of the list, this function is a no-op.
   115608 */
   115609 static void removeFromBlockedList(sqlite3 *db){
   115610   sqlite3 **pp;
   115611   assertMutexHeld();
   115612   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   115613     if( *pp==db ){
   115614       *pp = (*pp)->pNextBlocked;
   115615       break;
   115616     }
   115617   }
   115618 }
   115619 
   115620 /*
   115621 ** Add connection db to the blocked connections list. It is assumed
   115622 ** that it is not already a part of the list.
   115623 */
   115624 static void addToBlockedList(sqlite3 *db){
   115625   sqlite3 **pp;
   115626   assertMutexHeld();
   115627   for(
   115628     pp=&sqlite3BlockedList;
   115629     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   115630     pp=&(*pp)->pNextBlocked
   115631   );
   115632   db->pNextBlocked = *pp;
   115633   *pp = db;
   115634 }
   115635 
   115636 /*
   115637 ** Obtain the STATIC_MASTER mutex.
   115638 */
   115639 static void enterMutex(void){
   115640   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   115641   checkListProperties(0);
   115642 }
   115643 
   115644 /*
   115645 ** Release the STATIC_MASTER mutex.
   115646 */
   115647 static void leaveMutex(void){
   115648   assertMutexHeld();
   115649   checkListProperties(0);
   115650   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   115651 }
   115652 
   115653 /*
   115654 ** Register an unlock-notify callback.
   115655 **
   115656 ** This is called after connection "db" has attempted some operation
   115657 ** but has received an SQLITE_LOCKED error because another connection
   115658 ** (call it pOther) in the same process was busy using the same shared
   115659 ** cache.  pOther is found by looking at db->pBlockingConnection.
   115660 **
   115661 ** If there is no blocking connection, the callback is invoked immediately,
   115662 ** before this routine returns.
   115663 **
   115664 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   115665 ** a deadlock.
   115666 **
   115667 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   115668 ** its locks.
   115669 **
   115670 ** Each call to this routine overrides any prior callbacks registered
   115671 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   115672 ** cancelled.
   115673 */
   115674 SQLITE_API int sqlite3_unlock_notify(
   115675   sqlite3 *db,
   115676   void (*xNotify)(void **, int),
   115677   void *pArg
   115678 ){
   115679   int rc = SQLITE_OK;
   115680 
   115681   sqlite3_mutex_enter(db->mutex);
   115682   enterMutex();
   115683 
   115684   if( xNotify==0 ){
   115685     removeFromBlockedList(db);
   115686     db->pBlockingConnection = 0;
   115687     db->pUnlockConnection = 0;
   115688     db->xUnlockNotify = 0;
   115689     db->pUnlockArg = 0;
   115690   }else if( 0==db->pBlockingConnection ){
   115691     /* The blocking transaction has been concluded. Or there never was a
   115692     ** blocking transaction. In either case, invoke the notify callback
   115693     ** immediately.
   115694     */
   115695     xNotify(&pArg, 1);
   115696   }else{
   115697     sqlite3 *p;
   115698 
   115699     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   115700     if( p ){
   115701       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   115702     }else{
   115703       db->pUnlockConnection = db->pBlockingConnection;
   115704       db->xUnlockNotify = xNotify;
   115705       db->pUnlockArg = pArg;
   115706       removeFromBlockedList(db);
   115707       addToBlockedList(db);
   115708     }
   115709   }
   115710 
   115711   leaveMutex();
   115712   assert( !db->mallocFailed );
   115713   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   115714   sqlite3_mutex_leave(db->mutex);
   115715   return rc;
   115716 }
   115717 
   115718 /*
   115719 ** This function is called while stepping or preparing a statement
   115720 ** associated with connection db. The operation will return SQLITE_LOCKED
   115721 ** to the user because it requires a lock that will not be available
   115722 ** until connection pBlocker concludes its current transaction.
   115723 */
   115724 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   115725   enterMutex();
   115726   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   115727     addToBlockedList(db);
   115728   }
   115729   db->pBlockingConnection = pBlocker;
   115730   leaveMutex();
   115731 }
   115732 
   115733 /*
   115734 ** This function is called when
   115735 ** the transaction opened by database db has just finished. Locks held
   115736 ** by database connection db have been released.
   115737 **
   115738 ** This function loops through each entry in the blocked connections
   115739 ** list and does the following:
   115740 **
   115741 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   115742 **      set to db, then set pBlockingConnection=0.
   115743 **
   115744 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   115745 **      set to db, then invoke the configured unlock-notify callback and
   115746 **      set pUnlockConnection=0.
   115747 **
   115748 **   3) If the two steps above mean that pBlockingConnection==0 and
   115749 **      pUnlockConnection==0, remove the entry from the blocked connections
   115750 **      list.
   115751 */
   115752 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   115753   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   115754   int nArg = 0;                            /* Number of entries in aArg[] */
   115755   sqlite3 **pp;                            /* Iterator variable */
   115756   void **aArg;               /* Arguments to the unlock callback */
   115757   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   115758   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   115759 
   115760   aArg = aStatic;
   115761   enterMutex();         /* Enter STATIC_MASTER mutex */
   115762 
   115763   /* This loop runs once for each entry in the blocked-connections list. */
   115764   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   115765     sqlite3 *p = *pp;
   115766 
   115767     /* Step 1. */
   115768     if( p->pBlockingConnection==db ){
   115769       p->pBlockingConnection = 0;
   115770     }
   115771 
   115772     /* Step 2. */
   115773     if( p->pUnlockConnection==db ){
   115774       assert( p->xUnlockNotify );
   115775       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   115776         xUnlockNotify(aArg, nArg);
   115777         nArg = 0;
   115778       }
   115779 
   115780       sqlite3BeginBenignMalloc();
   115781       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   115782       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   115783       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   115784        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   115785       ){
   115786         /* The aArg[] array needs to grow. */
   115787         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   115788         if( pNew ){
   115789           memcpy(pNew, aArg, nArg*sizeof(void *));
   115790           sqlite3_free(aDyn);
   115791           aDyn = aArg = pNew;
   115792         }else{
   115793           /* This occurs when the array of context pointers that need to
   115794           ** be passed to the unlock-notify callback is larger than the
   115795           ** aStatic[] array allocated on the stack and the attempt to
   115796           ** allocate a larger array from the heap has failed.
   115797           **
   115798           ** This is a difficult situation to handle. Returning an error
   115799           ** code to the caller is insufficient, as even if an error code
   115800           ** is returned the transaction on connection db will still be
   115801           ** closed and the unlock-notify callbacks on blocked connections
   115802           ** will go unissued. This might cause the application to wait
   115803           ** indefinitely for an unlock-notify callback that will never
   115804           ** arrive.
   115805           **
   115806           ** Instead, invoke the unlock-notify callback with the context
   115807           ** array already accumulated. We can then clear the array and
   115808           ** begin accumulating any further context pointers without
   115809           ** requiring any dynamic allocation. This is sub-optimal because
   115810           ** it means that instead of one callback with a large array of
   115811           ** context pointers the application will receive two or more
   115812           ** callbacks with smaller arrays of context pointers, which will
   115813           ** reduce the applications ability to prioritize multiple
   115814           ** connections. But it is the best that can be done under the
   115815           ** circumstances.
   115816           */
   115817           xUnlockNotify(aArg, nArg);
   115818           nArg = 0;
   115819         }
   115820       }
   115821       sqlite3EndBenignMalloc();
   115822 
   115823       aArg[nArg++] = p->pUnlockArg;
   115824       xUnlockNotify = p->xUnlockNotify;
   115825       p->pUnlockConnection = 0;
   115826       p->xUnlockNotify = 0;
   115827       p->pUnlockArg = 0;
   115828     }
   115829 
   115830     /* Step 3. */
   115831     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   115832       /* Remove connection p from the blocked connections list. */
   115833       *pp = p->pNextBlocked;
   115834       p->pNextBlocked = 0;
   115835     }else{
   115836       pp = &p->pNextBlocked;
   115837     }
   115838   }
   115839 
   115840   if( nArg!=0 ){
   115841     xUnlockNotify(aArg, nArg);
   115842   }
   115843   sqlite3_free(aDyn);
   115844   leaveMutex();         /* Leave STATIC_MASTER mutex */
   115845 }
   115846 
   115847 /*
   115848 ** This is called when the database connection passed as an argument is
   115849 ** being closed. The connection is removed from the blocked list.
   115850 */
   115851 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   115852   sqlite3ConnectionUnlocked(db);
   115853   enterMutex();
   115854   removeFromBlockedList(db);
   115855   checkListProperties(db);
   115856   leaveMutex();
   115857 }
   115858 #endif
   115859 
   115860 /************** End of notify.c **********************************************/
   115861 /************** Begin file fts3.c ********************************************/
   115862 /*
   115863 ** 2006 Oct 10
   115864 **
   115865 ** The author disclaims copyright to this source code.  In place of
   115866 ** a legal notice, here is a blessing:
   115867 **
   115868 **    May you do good and not evil.
   115869 **    May you find forgiveness for yourself and forgive others.
   115870 **    May you share freely, never taking more than you give.
   115871 **
   115872 ******************************************************************************
   115873 **
   115874 ** This is an SQLite module implementing full-text search.
   115875 */
   115876 
   115877 /*
   115878 ** The code in this file is only compiled if:
   115879 **
   115880 **     * The FTS3 module is being built as an extension
   115881 **       (in which case SQLITE_CORE is not defined), or
   115882 **
   115883 **     * The FTS3 module is being built into the core of
   115884 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   115885 */
   115886 
   115887 /* The full-text index is stored in a series of b+tree (-like)
   115888 ** structures called segments which map terms to doclists.  The
   115889 ** structures are like b+trees in layout, but are constructed from the
   115890 ** bottom up in optimal fashion and are not updatable.  Since trees
   115891 ** are built from the bottom up, things will be described from the
   115892 ** bottom up.
   115893 **
   115894 **
   115895 **** Varints ****
   115896 ** The basic unit of encoding is a variable-length integer called a
   115897 ** varint.  We encode variable-length integers in little-endian order
   115898 ** using seven bits * per byte as follows:
   115899 **
   115900 ** KEY:
   115901 **         A = 0xxxxxxx    7 bits of data and one flag bit
   115902 **         B = 1xxxxxxx    7 bits of data and one flag bit
   115903 **
   115904 **  7 bits - A
   115905 ** 14 bits - BA
   115906 ** 21 bits - BBA
   115907 ** and so on.
   115908 **
   115909 ** This is similar in concept to how sqlite encodes "varints" but
   115910 ** the encoding is not the same.  SQLite varints are big-endian
   115911 ** are are limited to 9 bytes in length whereas FTS3 varints are
   115912 ** little-endian and can be up to 10 bytes in length (in theory).
   115913 **
   115914 ** Example encodings:
   115915 **
   115916 **     1:    0x01
   115917 **   127:    0x7f
   115918 **   128:    0x81 0x00
   115919 **
   115920 **
   115921 **** Document lists ****
   115922 ** A doclist (document list) holds a docid-sorted list of hits for a
   115923 ** given term.  Doclists hold docids and associated token positions.
   115924 ** A docid is the unique integer identifier for a single document.
   115925 ** A position is the index of a word within the document.  The first
   115926 ** word of the document has a position of 0.
   115927 **
   115928 ** FTS3 used to optionally store character offsets using a compile-time
   115929 ** option.  But that functionality is no longer supported.
   115930 **
   115931 ** A doclist is stored like this:
   115932 **
   115933 ** array {
   115934 **   varint docid;
   115935 **   array {                (position list for column 0)
   115936 **     varint position;     (2 more than the delta from previous position)
   115937 **   }
   115938 **   array {
   115939 **     varint POS_COLUMN;   (marks start of position list for new column)
   115940 **     varint column;       (index of new column)
   115941 **     array {
   115942 **       varint position;   (2 more than the delta from previous position)
   115943 **     }
   115944 **   }
   115945 **   varint POS_END;        (marks end of positions for this document.
   115946 ** }
   115947 **
   115948 ** Here, array { X } means zero or more occurrences of X, adjacent in
   115949 ** memory.  A "position" is an index of a token in the token stream
   115950 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   115951 ** in the same logical place as the position element, and act as sentinals
   115952 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   115953 ** The positions numbers are not stored literally but rather as two more
   115954 ** than the difference from the prior position, or the just the position plus
   115955 ** 2 for the first position.  Example:
   115956 **
   115957 **   label:       A B C D E  F  G H   I  J K
   115958 **   value:     123 5 9 1 1 14 35 0 234 72 0
   115959 **
   115960 ** The 123 value is the first docid.  For column zero in this document
   115961 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   115962 ** at D signals the start of a new column; the 1 at E indicates that the
   115963 ** new column is column number 1.  There are two positions at 12 and 45
   115964 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   115965 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
   115966 ** terminates with the 0 at K.
   115967 **
   115968 ** A "position-list" is the list of positions for multiple columns for
   115969 ** a single docid.  A "column-list" is the set of positions for a single
   115970 ** column.  Hence, a position-list consists of one or more column-lists,
   115971 ** a document record consists of a docid followed by a position-list and
   115972 ** a doclist consists of one or more document records.
   115973 **
   115974 ** A bare doclist omits the position information, becoming an
   115975 ** array of varint-encoded docids.
   115976 **
   115977 **** Segment leaf nodes ****
   115978 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   115979 ** nodes are written using LeafWriter, and read using LeafReader (to
   115980 ** iterate through a single leaf node's data) and LeavesReader (to
   115981 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   115982 ** the format:
   115983 **
   115984 ** varint iHeight;             (height from leaf level, always 0)
   115985 ** varint nTerm;               (length of first term)
   115986 ** char pTerm[nTerm];          (content of first term)
   115987 ** varint nDoclist;            (length of term's associated doclist)
   115988 ** char pDoclist[nDoclist];    (content of doclist)
   115989 ** array {
   115990 **                             (further terms are delta-encoded)
   115991 **   varint nPrefix;           (length of prefix shared with previous term)
   115992 **   varint nSuffix;           (length of unshared suffix)
   115993 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   115994 **   varint nDoclist;          (length of term's associated doclist)
   115995 **   char pDoclist[nDoclist];  (content of doclist)
   115996 ** }
   115997 **
   115998 ** Here, array { X } means zero or more occurrences of X, adjacent in
   115999 ** memory.
   116000 **
   116001 ** Leaf nodes are broken into blocks which are stored contiguously in
   116002 ** the %_segments table in sorted order.  This means that when the end
   116003 ** of a node is reached, the next term is in the node with the next
   116004 ** greater node id.
   116005 **
   116006 ** New data is spilled to a new leaf node when the current node
   116007 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   116008 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   116009 ** node (a leaf node with a single term and doclist).  The goal of
   116010 ** these settings is to pack together groups of small doclists while
   116011 ** making it efficient to directly access large doclists.  The
   116012 ** assumption is that large doclists represent terms which are more
   116013 ** likely to be query targets.
   116014 **
   116015 ** TODO(shess) It may be useful for blocking decisions to be more
   116016 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   116017 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   116018 ** that this might extend through 2x or 4x the pagesize.
   116019 **
   116020 **
   116021 **** Segment interior nodes ****
   116022 ** Segment interior nodes store blockids for subtree nodes and terms
   116023 ** to describe what data is stored by the each subtree.  Interior
   116024 ** nodes are written using InteriorWriter, and read using
   116025 ** InteriorReader.  InteriorWriters are created as needed when
   116026 ** SegmentWriter creates new leaf nodes, or when an interior node
   116027 ** itself grows too big and must be split.  The format of interior
   116028 ** nodes:
   116029 **
   116030 ** varint iHeight;           (height from leaf level, always >0)
   116031 ** varint iBlockid;          (block id of node's leftmost subtree)
   116032 ** optional {
   116033 **   varint nTerm;           (length of first term)
   116034 **   char pTerm[nTerm];      (content of first term)
   116035 **   array {
   116036 **                                (further terms are delta-encoded)
   116037 **     varint nPrefix;            (length of shared prefix with previous term)
   116038 **     varint nSuffix;            (length of unshared suffix)
   116039 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   116040 **   }
   116041 ** }
   116042 **
   116043 ** Here, optional { X } means an optional element, while array { X }
   116044 ** means zero or more occurrences of X, adjacent in memory.
   116045 **
   116046 ** An interior node encodes n terms separating n+1 subtrees.  The
   116047 ** subtree blocks are contiguous, so only the first subtree's blockid
   116048 ** is encoded.  The subtree at iBlockid will contain all terms less
   116049 ** than the first term encoded (or all terms if no term is encoded).
   116050 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   116051 ** than pTerm[i+1], the subtree for that term will be rooted at
   116052 ** iBlockid+i.  Interior nodes only store enough term data to
   116053 ** distinguish adjacent children (if the rightmost term of the left
   116054 ** child is "something", and the leftmost term of the right child is
   116055 ** "wicked", only "w" is stored).
   116056 **
   116057 ** New data is spilled to a new interior node at the same height when
   116058 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   116059 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   116060 ** interior nodes and making the tree too skinny.  The interior nodes
   116061 ** at a given height are naturally tracked by interior nodes at
   116062 ** height+1, and so on.
   116063 **
   116064 **
   116065 **** Segment directory ****
   116066 ** The segment directory in table %_segdir stores meta-information for
   116067 ** merging and deleting segments, and also the root node of the
   116068 ** segment's tree.
   116069 **
   116070 ** The root node is the top node of the segment's tree after encoding
   116071 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   116072 ** This could be either a leaf node or an interior node.  If the top
   116073 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   116074 ** and a new root interior node is generated (which should always fit
   116075 ** within ROOT_MAX because it only needs space for 2 varints, the
   116076 ** height and the blockid of the previous root).
   116077 **
   116078 ** The meta-information in the segment directory is:
   116079 **   level               - segment level (see below)
   116080 **   idx                 - index within level
   116081 **                       - (level,idx uniquely identify a segment)
   116082 **   start_block         - first leaf node
   116083 **   leaves_end_block    - last leaf node
   116084 **   end_block           - last block (including interior nodes)
   116085 **   root                - contents of root node
   116086 **
   116087 ** If the root node is a leaf node, then start_block,
   116088 ** leaves_end_block, and end_block are all 0.
   116089 **
   116090 **
   116091 **** Segment merging ****
   116092 ** To amortize update costs, segments are grouped into levels and
   116093 ** merged in batches.  Each increase in level represents exponentially
   116094 ** more documents.
   116095 **
   116096 ** New documents (actually, document updates) are tokenized and
   116097 ** written individually (using LeafWriter) to a level 0 segment, with
   116098 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   116099 ** level 0 segments are merged into a single level 1 segment.  Level 1
   116100 ** is populated like level 0, and eventually MERGE_COUNT level 1
   116101 ** segments are merged to a single level 2 segment (representing
   116102 ** MERGE_COUNT^2 updates), and so on.
   116103 **
   116104 ** A segment merge traverses all segments at a given level in
   116105 ** parallel, performing a straightforward sorted merge.  Since segment
   116106 ** leaf nodes are written in to the %_segments table in order, this
   116107 ** merge traverses the underlying sqlite disk structures efficiently.
   116108 ** After the merge, all segment blocks from the merged level are
   116109 ** deleted.
   116110 **
   116111 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   116112 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   116113 ** very similar performance numbers to 16 on insertion, though they're
   116114 ** a tiny bit slower (perhaps due to more overhead in merge-time
   116115 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   116116 ** 16, 2 about 66% slower than 16.
   116117 **
   116118 ** At query time, high MERGE_COUNT increases the number of segments
   116119 ** which need to be scanned and merged.  For instance, with 100k docs
   116120 ** inserted:
   116121 **
   116122 **    MERGE_COUNT   segments
   116123 **       16           25
   116124 **        8           12
   116125 **        4           10
   116126 **        2            6
   116127 **
   116128 ** This appears to have only a moderate impact on queries for very
   116129 ** frequent terms (which are somewhat dominated by segment merge
   116130 ** costs), and infrequent and non-existent terms still seem to be fast
   116131 ** even with many segments.
   116132 **
   116133 ** TODO(shess) That said, it would be nice to have a better query-side
   116134 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   116135 ** optimizations to things like doclist merging will swing the sweet
   116136 ** spot around.
   116137 **
   116138 **
   116139 **
   116140 **** Handling of deletions and updates ****
   116141 ** Since we're using a segmented structure, with no docid-oriented
   116142 ** index into the term index, we clearly cannot simply update the term
   116143 ** index when a document is deleted or updated.  For deletions, we
   116144 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   116145 ** we simply write the new doclist.  Segment merges overwrite older
   116146 ** data for a particular docid with newer data, so deletes or updates
   116147 ** will eventually overtake the earlier data and knock it out.  The
   116148 ** query logic likewise merges doclists so that newer data knocks out
   116149 ** older data.
   116150 */
   116151 
   116152 /************** Include fts3Int.h in the middle of fts3.c ********************/
   116153 /************** Begin file fts3Int.h *****************************************/
   116154 /*
   116155 ** 2009 Nov 12
   116156 **
   116157 ** The author disclaims copyright to this source code.  In place of
   116158 ** a legal notice, here is a blessing:
   116159 **
   116160 **    May you do good and not evil.
   116161 **    May you find forgiveness for yourself and forgive others.
   116162 **    May you share freely, never taking more than you give.
   116163 **
   116164 ******************************************************************************
   116165 **
   116166 */
   116167 #ifndef _FTSINT_H
   116168 #define _FTSINT_H
   116169 
   116170 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   116171 # define NDEBUG 1
   116172 #endif
   116173 
   116174 /*
   116175 ** FTS4 is really an extension for FTS3.  It is enabled using the
   116176 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   116177 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   116178 */
   116179 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   116180 # define SQLITE_ENABLE_FTS3
   116181 #endif
   116182 
   116183 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   116184 
   116185 /* If not building as part of the core, include sqlite3ext.h. */
   116186 #ifndef SQLITE_CORE
   116187 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
   116188 #endif
   116189 
   116190 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   116191 /************** Begin file fts3_tokenizer.h **********************************/
   116192 /*
   116193 ** 2006 July 10
   116194 **
   116195 ** The author disclaims copyright to this source code.
   116196 **
   116197 *************************************************************************
   116198 ** Defines the interface to tokenizers used by fulltext-search.  There
   116199 ** are three basic components:
   116200 **
   116201 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   116202 ** interface functions.  This is essentially the class structure for
   116203 ** tokenizers.
   116204 **
   116205 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   116206 ** including customization information defined at creation time.
   116207 **
   116208 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   116209 ** tokens from a particular input.
   116210 */
   116211 #ifndef _FTS3_TOKENIZER_H_
   116212 #define _FTS3_TOKENIZER_H_
   116213 
   116214 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   116215 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   116216 ** we will need a way to register the API consistently.
   116217 */
   116218 
   116219 /*
   116220 ** Structures used by the tokenizer interface. When a new tokenizer
   116221 ** implementation is registered, the caller provides a pointer to
   116222 ** an sqlite3_tokenizer_module containing pointers to the callback
   116223 ** functions that make up an implementation.
   116224 **
   116225 ** When an fts3 table is created, it passes any arguments passed to
   116226 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   116227 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   116228 ** implementation. The xCreate() function in turn returns an
   116229 ** sqlite3_tokenizer structure representing the specific tokenizer to
   116230 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   116231 **
   116232 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   116233 ** method is called. It returns an sqlite3_tokenizer_cursor object
   116234 ** that may be used to tokenize a specific input buffer based on
   116235 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   116236 ** object.
   116237 */
   116238 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   116239 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   116240 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   116241 
   116242 struct sqlite3_tokenizer_module {
   116243 
   116244   /*
   116245   ** Structure version. Should always be set to 0 or 1.
   116246   */
   116247   int iVersion;
   116248 
   116249   /*
   116250   ** Create a new tokenizer. The values in the argv[] array are the
   116251   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   116252   ** TABLE statement that created the fts3 table. For example, if
   116253   ** the following SQL is executed:
   116254   **
   116255   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   116256   **
   116257   ** then argc is set to 2, and the argv[] array contains pointers
   116258   ** to the strings "arg1" and "arg2".
   116259   **
   116260   ** This method should return either SQLITE_OK (0), or an SQLite error
   116261   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   116262   ** to point at the newly created tokenizer structure. The generic
   116263   ** sqlite3_tokenizer.pModule variable should not be initialised by
   116264   ** this callback. The caller will do so.
   116265   */
   116266   int (*xCreate)(
   116267     int argc,                           /* Size of argv array */
   116268     const char *const*argv,             /* Tokenizer argument strings */
   116269     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   116270   );
   116271 
   116272   /*
   116273   ** Destroy an existing tokenizer. The fts3 module calls this method
   116274   ** exactly once for each successful call to xCreate().
   116275   */
   116276   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   116277 
   116278   /*
   116279   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   116280   ** is responsible for ensuring that the input buffer remains valid
   116281   ** until the cursor is closed (using the xClose() method).
   116282   */
   116283   int (*xOpen)(
   116284     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   116285     const char *pInput, int nBytes,      /* Input buffer */
   116286     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   116287   );
   116288 
   116289   /*
   116290   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   116291   ** method exactly once for each successful call to xOpen().
   116292   */
   116293   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   116294 
   116295   /*
   116296   ** Retrieve the next token from the tokenizer cursor pCursor. This
   116297   ** method should either return SQLITE_OK and set the values of the
   116298   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   116299   ** the end of the buffer has been reached, or an SQLite error code.
   116300   **
   116301   ** *ppToken should be set to point at a buffer containing the
   116302   ** normalized version of the token (i.e. after any case-folding and/or
   116303   ** stemming has been performed). *pnBytes should be set to the length
   116304   ** of this buffer in bytes. The input text that generated the token is
   116305   ** identified by the byte offsets returned in *piStartOffset and
   116306   ** *piEndOffset. *piStartOffset should be set to the index of the first
   116307   ** byte of the token in the input buffer. *piEndOffset should be set
   116308   ** to the index of the first byte just past the end of the token in
   116309   ** the input buffer.
   116310   **
   116311   ** The buffer *ppToken is set to point at is managed by the tokenizer
   116312   ** implementation. It is only required to be valid until the next call
   116313   ** to xNext() or xClose().
   116314   */
   116315   /* TODO(shess) current implementation requires pInput to be
   116316   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   116317   ** should be converted to zInput.
   116318   */
   116319   int (*xNext)(
   116320     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   116321     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   116322     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   116323     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   116324     int *piPosition      /* OUT: Number of tokens returned before this one */
   116325   );
   116326 
   116327   /***********************************************************************
   116328   ** Methods below this point are only available if iVersion>=1.
   116329   */
   116330 
   116331   /*
   116332   ** Configure the language id of a tokenizer cursor.
   116333   */
   116334   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
   116335 };
   116336 
   116337 struct sqlite3_tokenizer {
   116338   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   116339   /* Tokenizer implementations will typically add additional fields */
   116340 };
   116341 
   116342 struct sqlite3_tokenizer_cursor {
   116343   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   116344   /* Tokenizer implementations will typically add additional fields */
   116345 };
   116346 
   116347 int fts3_global_term_cnt(int iTerm, int iCol);
   116348 int fts3_term_cnt(int iTerm, int iCol);
   116349 
   116350 
   116351 #endif /* _FTS3_TOKENIZER_H_ */
   116352 
   116353 /************** End of fts3_tokenizer.h **************************************/
   116354 /************** Continuing where we left off in fts3Int.h ********************/
   116355 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   116356 /************** Begin file fts3_hash.h ***************************************/
   116357 /*
   116358 ** 2001 September 22
   116359 **
   116360 ** The author disclaims copyright to this source code.  In place of
   116361 ** a legal notice, here is a blessing:
   116362 **
   116363 **    May you do good and not evil.
   116364 **    May you find forgiveness for yourself and forgive others.
   116365 **    May you share freely, never taking more than you give.
   116366 **
   116367 *************************************************************************
   116368 ** This is the header file for the generic hash-table implemenation
   116369 ** used in SQLite.  We've modified it slightly to serve as a standalone
   116370 ** hash table implementation for the full-text indexing module.
   116371 **
   116372 */
   116373 #ifndef _FTS3_HASH_H_
   116374 #define _FTS3_HASH_H_
   116375 
   116376 /* Forward declarations of structures. */
   116377 typedef struct Fts3Hash Fts3Hash;
   116378 typedef struct Fts3HashElem Fts3HashElem;
   116379 
   116380 /* A complete hash table is an instance of the following structure.
   116381 ** The internals of this structure are intended to be opaque -- client
   116382 ** code should not attempt to access or modify the fields of this structure
   116383 ** directly.  Change this structure only by using the routines below.
   116384 ** However, many of the "procedures" and "functions" for modifying and
   116385 ** accessing this structure are really macros, so we can't really make
   116386 ** this structure opaque.
   116387 */
   116388 struct Fts3Hash {
   116389   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   116390   char copyKey;           /* True if copy of key made on insert */
   116391   int count;              /* Number of entries in this table */
   116392   Fts3HashElem *first;    /* The first element of the array */
   116393   int htsize;             /* Number of buckets in the hash table */
   116394   struct _fts3ht {        /* the hash table */
   116395     int count;               /* Number of entries with this hash */
   116396     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   116397   } *ht;
   116398 };
   116399 
   116400 /* Each element in the hash table is an instance of the following
   116401 ** structure.  All elements are stored on a single doubly-linked list.
   116402 **
   116403 ** Again, this structure is intended to be opaque, but it can't really
   116404 ** be opaque because it is used by macros.
   116405 */
   116406 struct Fts3HashElem {
   116407   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   116408   void *data;                /* Data associated with this element */
   116409   void *pKey; int nKey;      /* Key associated with this element */
   116410 };
   116411 
   116412 /*
   116413 ** There are 2 different modes of operation for a hash table:
   116414 **
   116415 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   116416 **                           (including the null-terminator, if any).  Case
   116417 **                           is respected in comparisons.
   116418 **
   116419 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   116420 **                           memcmp() is used to compare keys.
   116421 **
   116422 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   116423 */
   116424 #define FTS3_HASH_STRING    1
   116425 #define FTS3_HASH_BINARY    2
   116426 
   116427 /*
   116428 ** Access routines.  To delete, insert a NULL pointer.
   116429 */
   116430 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   116431 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   116432 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   116433 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   116434 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   116435 
   116436 /*
   116437 ** Shorthand for the functions above
   116438 */
   116439 #define fts3HashInit     sqlite3Fts3HashInit
   116440 #define fts3HashInsert   sqlite3Fts3HashInsert
   116441 #define fts3HashFind     sqlite3Fts3HashFind
   116442 #define fts3HashClear    sqlite3Fts3HashClear
   116443 #define fts3HashFindElem sqlite3Fts3HashFindElem
   116444 
   116445 /*
   116446 ** Macros for looping over all elements of a hash table.  The idiom is
   116447 ** like this:
   116448 **
   116449 **   Fts3Hash h;
   116450 **   Fts3HashElem *p;
   116451 **   ...
   116452 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   116453 **     SomeStructure *pData = fts3HashData(p);
   116454 **     // do something with pData
   116455 **   }
   116456 */
   116457 #define fts3HashFirst(H)  ((H)->first)
   116458 #define fts3HashNext(E)   ((E)->next)
   116459 #define fts3HashData(E)   ((E)->data)
   116460 #define fts3HashKey(E)    ((E)->pKey)
   116461 #define fts3HashKeysize(E) ((E)->nKey)
   116462 
   116463 /*
   116464 ** Number of entries in a hash table
   116465 */
   116466 #define fts3HashCount(H)  ((H)->count)
   116467 
   116468 #endif /* _FTS3_HASH_H_ */
   116469 
   116470 /************** End of fts3_hash.h *******************************************/
   116471 /************** Continuing where we left off in fts3Int.h ********************/
   116472 
   116473 /*
   116474 ** This constant controls how often segments are merged. Once there are
   116475 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   116476 ** segment of level N+1.
   116477 */
   116478 #define FTS3_MERGE_COUNT 16
   116479 
   116480 /*
   116481 ** This is the maximum amount of data (in bytes) to store in the
   116482 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   116483 ** populated as documents are inserted/updated/deleted in a transaction
   116484 ** and used to create a new segment when the transaction is committed.
   116485 ** However if this limit is reached midway through a transaction, a new
   116486 ** segment is created and the hash table cleared immediately.
   116487 */
   116488 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   116489 
   116490 /*
   116491 ** Macro to return the number of elements in an array. SQLite has a
   116492 ** similar macro called ArraySize(). Use a different name to avoid
   116493 ** a collision when building an amalgamation with built-in FTS3.
   116494 */
   116495 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   116496 
   116497 
   116498 #ifndef MIN
   116499 # define MIN(x,y) ((x)<(y)?(x):(y))
   116500 #endif
   116501 
   116502 /*
   116503 ** Maximum length of a varint encoded integer. The varint format is different
   116504 ** from that used by SQLite, so the maximum length is 10, not 9.
   116505 */
   116506 #define FTS3_VARINT_MAX 10
   116507 
   116508 /*
   116509 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
   116510 ** in the document set and zero or more prefix indexes. All indexes are stored
   116511 ** as one or more b+-trees in the %_segments and %_segdir tables.
   116512 **
   116513 ** It is possible to determine which index a b+-tree belongs to based on the
   116514 ** value stored in the "%_segdir.level" column. Given this value L, the index
   116515 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
   116516 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
   116517 ** between 1024 and 2047 to index 1, and so on.
   116518 **
   116519 ** It is considered impossible for an index to use more than 1024 levels. In
   116520 ** theory though this may happen, but only after at least
   116521 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
   116522 */
   116523 #define FTS3_SEGDIR_MAXLEVEL      1024
   116524 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
   116525 
   116526 /*
   116527 ** The testcase() macro is only used by the amalgamation.  If undefined,
   116528 ** make it a no-op.
   116529 */
   116530 #ifndef testcase
   116531 # define testcase(X)
   116532 #endif
   116533 
   116534 /*
   116535 ** Terminator values for position-lists and column-lists.
   116536 */
   116537 #define POS_COLUMN  (1)     /* Column-list terminator */
   116538 #define POS_END     (0)     /* Position-list terminator */
   116539 
   116540 /*
   116541 ** This section provides definitions to allow the
   116542 ** FTS3 extension to be compiled outside of the
   116543 ** amalgamation.
   116544 */
   116545 #ifndef SQLITE_AMALGAMATION
   116546 /*
   116547 ** Macros indicating that conditional expressions are always true or
   116548 ** false.
   116549 */
   116550 #ifdef SQLITE_COVERAGE_TEST
   116551 # define ALWAYS(x) (1)
   116552 # define NEVER(X)  (0)
   116553 #else
   116554 # define ALWAYS(x) (x)
   116555 # define NEVER(X)  (x)
   116556 #endif
   116557 
   116558 /*
   116559 ** Internal types used by SQLite.
   116560 */
   116561 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   116562 typedef short int i16;            /* 2-byte (or larger) signed integer */
   116563 typedef unsigned int u32;         /* 4-byte unsigned integer */
   116564 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   116565 
   116566 /*
   116567 ** Macro used to suppress compiler warnings for unused parameters.
   116568 */
   116569 #define UNUSED_PARAMETER(x) (void)(x)
   116570 
   116571 /*
   116572 ** Activate assert() only if SQLITE_TEST is enabled.
   116573 */
   116574 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   116575 # define NDEBUG 1
   116576 #endif
   116577 
   116578 /*
   116579 ** The TESTONLY macro is used to enclose variable declarations or
   116580 ** other bits of code that are needed to support the arguments
   116581 ** within testcase() and assert() macros.
   116582 */
   116583 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   116584 # define TESTONLY(X)  X
   116585 #else
   116586 # define TESTONLY(X)
   116587 #endif
   116588 
   116589 #endif /* SQLITE_AMALGAMATION */
   116590 
   116591 #ifdef SQLITE_DEBUG
   116592 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
   116593 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
   116594 #else
   116595 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
   116596 #endif
   116597 
   116598 typedef struct Fts3Table Fts3Table;
   116599 typedef struct Fts3Cursor Fts3Cursor;
   116600 typedef struct Fts3Expr Fts3Expr;
   116601 typedef struct Fts3Phrase Fts3Phrase;
   116602 typedef struct Fts3PhraseToken Fts3PhraseToken;
   116603 
   116604 typedef struct Fts3Doclist Fts3Doclist;
   116605 typedef struct Fts3SegFilter Fts3SegFilter;
   116606 typedef struct Fts3DeferredToken Fts3DeferredToken;
   116607 typedef struct Fts3SegReader Fts3SegReader;
   116608 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
   116609 
   116610 /*
   116611 ** A connection to a fulltext index is an instance of the following
   116612 ** structure. The xCreate and xConnect methods create an instance
   116613 ** of this structure and xDestroy and xDisconnect free that instance.
   116614 ** All other methods receive a pointer to the structure as one of their
   116615 ** arguments.
   116616 */
   116617 struct Fts3Table {
   116618   sqlite3_vtab base;              /* Base class used by SQLite core */
   116619   sqlite3 *db;                    /* The database connection */
   116620   const char *zDb;                /* logical database name */
   116621   const char *zName;              /* virtual table name */
   116622   int nColumn;                    /* number of named columns in virtual table */
   116623   char **azColumn;                /* column names.  malloced */
   116624   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   116625   char *zContentTbl;              /* content=xxx option, or NULL */
   116626   char *zLanguageid;              /* languageid=xxx option, or NULL */
   116627 
   116628   /* Precompiled statements used by the implementation. Each of these
   116629   ** statements is run and reset within a single virtual table API call.
   116630   */
   116631   sqlite3_stmt *aStmt[28];
   116632 
   116633   char *zReadExprlist;
   116634   char *zWriteExprlist;
   116635 
   116636   int nNodeSize;                  /* Soft limit for node size */
   116637   u8 bHasStat;                    /* True if %_stat table exists */
   116638   u8 bHasDocsize;                 /* True if %_docsize table exists */
   116639   u8 bDescIdx;                    /* True if doclists are in reverse order */
   116640   int nPgsz;                      /* Page size for host database */
   116641   char *zSegmentsTbl;             /* Name of %_segments table */
   116642   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   116643 
   116644   /* TODO: Fix the first paragraph of this comment.
   116645   **
   116646   ** The following array of hash tables is used to buffer pending index
   116647   ** updates during transactions. Variable nPendingData estimates the memory
   116648   ** size of the pending data, including hash table overhead, not including
   116649   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, the buffer
   116650   ** is flushed automatically. Variable iPrevDocid is the docid of the most
   116651   ** recently inserted record.
   116652   **
   116653   ** A single FTS4 table may have multiple full-text indexes. For each index
   116654   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
   116655   ** terms that appear in the document set. Each subsequent index in aIndex[]
   116656   ** is an index of prefixes of a specific length.
   116657   */
   116658   int nIndex;                     /* Size of aIndex[] */
   116659   struct Fts3Index {
   116660     int nPrefix;                  /* Prefix length (0 for main terms index) */
   116661     Fts3Hash hPending;            /* Pending terms table for this index */
   116662   } *aIndex;
   116663   int nMaxPendingData;            /* Max pending data before flush to disk */
   116664   int nPendingData;               /* Current bytes of pending data */
   116665   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
   116666   int iPrevLangid;                /* Langid of recently inserted document */
   116667 
   116668 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   116669   /* State variables used for validating that the transaction control
   116670   ** methods of the virtual table are called at appropriate times.  These
   116671   ** values do not contribute to FTS functionality; they are used for
   116672   ** verifying the operation of the SQLite core.
   116673   */
   116674   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
   116675   int mxSavepoint;       /* Largest valid xSavepoint integer */
   116676 #endif
   116677 };
   116678 
   116679 /*
   116680 ** When the core wants to read from the virtual table, it creates a
   116681 ** virtual table cursor (an instance of the following structure) using
   116682 ** the xOpen method. Cursors are destroyed using the xClose method.
   116683 */
   116684 struct Fts3Cursor {
   116685   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   116686   i16 eSearch;                    /* Search strategy (see below) */
   116687   u8 isEof;                       /* True if at End Of Results */
   116688   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   116689   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   116690   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   116691   int iLangid;                    /* Language being queried for */
   116692   int nPhrase;                    /* Number of matchable phrases in query */
   116693   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   116694   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   116695   char *pNextId;                  /* Pointer into the body of aDoclist */
   116696   char *aDoclist;                 /* List of docids for full-text queries */
   116697   int nDoclist;                   /* Size of buffer at aDoclist */
   116698   u8 bDesc;                       /* True to sort in descending order */
   116699   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   116700   int nRowAvg;                    /* Average size of database rows, in pages */
   116701   sqlite3_int64 nDoc;             /* Documents in table */
   116702 
   116703   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   116704   u32 *aMatchinfo;                /* Information about most recent match */
   116705   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
   116706   char *zMatchinfo;               /* Matchinfo specification */
   116707 };
   116708 
   116709 #define FTS3_EVAL_FILTER    0
   116710 #define FTS3_EVAL_NEXT      1
   116711 #define FTS3_EVAL_MATCHINFO 2
   116712 
   116713 /*
   116714 ** The Fts3Cursor.eSearch member is always set to one of the following.
   116715 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   116716 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   116717 ** of the column to be searched.  For example, in
   116718 **
   116719 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   116720 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   116721 **
   116722 ** Because the LHS of the MATCH operator is 2nd column "b",
   116723 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   116724 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   116725 ** indicating that all columns should be searched,
   116726 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   116727 */
   116728 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   116729 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   116730 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   116731 
   116732 
   116733 struct Fts3Doclist {
   116734   char *aAll;                    /* Array containing doclist (or NULL) */
   116735   int nAll;                      /* Size of a[] in bytes */
   116736   char *pNextDocid;              /* Pointer to next docid */
   116737 
   116738   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
   116739   int bFreeList;                 /* True if pList should be sqlite3_free()d */
   116740   char *pList;                   /* Pointer to position list following iDocid */
   116741   int nList;                     /* Length of position list */
   116742 };
   116743 
   116744 /*
   116745 ** A "phrase" is a sequence of one or more tokens that must match in
   116746 ** sequence.  A single token is the base case and the most common case.
   116747 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   116748 ** nToken will be the number of tokens in the string.
   116749 */
   116750 struct Fts3PhraseToken {
   116751   char *z;                        /* Text of the token */
   116752   int n;                          /* Number of bytes in buffer z */
   116753   int isPrefix;                   /* True if token ends with a "*" character */
   116754   int bFirst;                     /* True if token must appear at position 0 */
   116755 
   116756   /* Variables above this point are populated when the expression is
   116757   ** parsed (by code in fts3_expr.c). Below this point the variables are
   116758   ** used when evaluating the expression. */
   116759   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   116760   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
   116761 };
   116762 
   116763 struct Fts3Phrase {
   116764   /* Cache of doclist for this phrase. */
   116765   Fts3Doclist doclist;
   116766   int bIncr;                 /* True if doclist is loaded incrementally */
   116767   int iDoclistToken;
   116768 
   116769   /* Variables below this point are populated by fts3_expr.c when parsing
   116770   ** a MATCH expression. Everything above is part of the evaluation phase.
   116771   */
   116772   int nToken;                /* Number of tokens in the phrase */
   116773   int iColumn;               /* Index of column this phrase must match */
   116774   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   116775 };
   116776 
   116777 /*
   116778 ** A tree of these objects forms the RHS of a MATCH operator.
   116779 **
   116780 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
   116781 ** points to a malloced buffer, size nDoclist bytes, containing the results
   116782 ** of this phrase query in FTS3 doclist format. As usual, the initial
   116783 ** "Length" field found in doclists stored on disk is omitted from this
   116784 ** buffer.
   116785 **
   116786 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
   116787 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
   116788 ** where nCol is the number of columns in the queried FTS table. The array
   116789 ** is populated as follows:
   116790 **
   116791 **   aMI[iCol*3 + 0] = Undefined
   116792 **   aMI[iCol*3 + 1] = Number of occurrences
   116793 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
   116794 **
   116795 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
   116796 ** when the expression node is.
   116797 */
   116798 struct Fts3Expr {
   116799   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   116800   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   116801   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   116802   Fts3Expr *pLeft;           /* Left operand */
   116803   Fts3Expr *pRight;          /* Right operand */
   116804   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   116805 
   116806   /* The following are used by the fts3_eval.c module. */
   116807   sqlite3_int64 iDocid;      /* Current docid */
   116808   u8 bEof;                   /* True this expression is at EOF already */
   116809   u8 bStart;                 /* True if iDocid is valid */
   116810   u8 bDeferred;              /* True if this expression is entirely deferred */
   116811 
   116812   u32 *aMI;
   116813 };
   116814 
   116815 /*
   116816 ** Candidate values for Fts3Query.eType. Note that the order of the first
   116817 ** four values is in order of precedence when parsing expressions. For
   116818 ** example, the following:
   116819 **
   116820 **   "a OR b AND c NOT d NEAR e"
   116821 **
   116822 ** is equivalent to:
   116823 **
   116824 **   "a OR (b AND (c NOT (d NEAR e)))"
   116825 */
   116826 #define FTSQUERY_NEAR   1
   116827 #define FTSQUERY_NOT    2
   116828 #define FTSQUERY_AND    3
   116829 #define FTSQUERY_OR     4
   116830 #define FTSQUERY_PHRASE 5
   116831 
   116832 
   116833 /* fts3_write.c */
   116834 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   116835 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   116836 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   116837 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   116838 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
   116839   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   116840 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   116841   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
   116842 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   116843 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
   116844 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
   116845 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
   116846 
   116847 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   116848 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   116849 
   116850 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   116851 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   116852 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   116853 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   116854 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   116855 
   116856 /* Special values interpreted by sqlite3SegReaderCursor() */
   116857 #define FTS3_SEGCURSOR_PENDING        -1
   116858 #define FTS3_SEGCURSOR_ALL            -2
   116859 
   116860 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
   116861 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
   116862 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
   116863 
   116864 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
   116865     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
   116866 
   116867 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   116868 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   116869 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   116870 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   116871 #define FTS3_SEGMENT_PREFIX        0x00000008
   116872 #define FTS3_SEGMENT_SCAN          0x00000010
   116873 #define FTS3_SEGMENT_FIRST         0x00000020
   116874 
   116875 /* Type passed as 4th argument to SegmentReaderIterate() */
   116876 struct Fts3SegFilter {
   116877   const char *zTerm;
   116878   int nTerm;
   116879   int iCol;
   116880   int flags;
   116881 };
   116882 
   116883 struct Fts3MultiSegReader {
   116884   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
   116885   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
   116886   int nSegment;                   /* Size of apSegment array */
   116887   int nAdvance;                   /* How many seg-readers to advance */
   116888   Fts3SegFilter *pFilter;         /* Pointer to filter object */
   116889   char *aBuffer;                  /* Buffer to merge doclists in */
   116890   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
   116891 
   116892   int iColFilter;                 /* If >=0, filter for this column */
   116893   int bRestart;
   116894 
   116895   /* Used by fts3.c only. */
   116896   int nCost;                      /* Cost of running iterator */
   116897   int bLookup;                    /* True if a lookup of a single entry. */
   116898 
   116899   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
   116900   char *zTerm;                    /* Pointer to term buffer */
   116901   int nTerm;                      /* Size of zTerm in bytes */
   116902   char *aDoclist;                 /* Pointer to doclist buffer */
   116903   int nDoclist;                   /* Size of aDoclist[] in bytes */
   116904 };
   116905 
   116906 /* fts3.c */
   116907 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   116908 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   116909 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   116910 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   116911 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   116912 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
   116913 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
   116914 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
   116915 
   116916 /* fts3_tokenizer.c */
   116917 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   116918 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   116919 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   116920     sqlite3_tokenizer **, char **
   116921 );
   116922 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   116923 
   116924 /* fts3_snippet.c */
   116925 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   116926 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   116927   const char *, const char *, int, int
   116928 );
   116929 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   116930 
   116931 /* fts3_expr.c */
   116932 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
   116933   char **, int, int, int, const char *, int, Fts3Expr **
   116934 );
   116935 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   116936 #ifdef SQLITE_TEST
   116937 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   116938 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
   116939 #endif
   116940 
   116941 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   116942   sqlite3_tokenizer_cursor **
   116943 );
   116944 
   116945 /* fts3_aux.c */
   116946 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
   116947 
   116948 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
   116949 
   116950 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   116951     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
   116952 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   116953     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
   116954 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
   116955 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
   116956 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
   116957 
   116958 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
   116959 
   116960 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
   116961 #endif /* _FTSINT_H */
   116962 
   116963 /************** End of fts3Int.h *********************************************/
   116964 /************** Continuing where we left off in fts3.c ***********************/
   116965 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   116966 
   116967 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   116968 # define SQLITE_CORE 1
   116969 #endif
   116970 
   116971 /* #include <assert.h> */
   116972 /* #include <stdlib.h> */
   116973 /* #include <stddef.h> */
   116974 /* #include <stdio.h> */
   116975 /* #include <string.h> */
   116976 /* #include <stdarg.h> */
   116977 
   116978 #ifndef SQLITE_CORE
   116979   SQLITE_EXTENSION_INIT1
   116980 #endif
   116981 
   116982 static int fts3EvalNext(Fts3Cursor *pCsr);
   116983 static int fts3EvalStart(Fts3Cursor *pCsr);
   116984 static int fts3TermSegReaderCursor(
   116985     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
   116986 
   116987 /*
   116988 ** Write a 64-bit variable-length integer to memory starting at p[0].
   116989 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   116990 ** The number of bytes written is returned.
   116991 */
   116992 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   116993   unsigned char *q = (unsigned char *) p;
   116994   sqlite_uint64 vu = v;
   116995   do{
   116996     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   116997     vu >>= 7;
   116998   }while( vu!=0 );
   116999   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   117000   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   117001   return (int) (q - (unsigned char *)p);
   117002 }
   117003 
   117004 /*
   117005 ** Read a 64-bit variable-length integer from memory starting at p[0].
   117006 ** Return the number of bytes read, or 0 on error.
   117007 ** The value is stored in *v.
   117008 */
   117009 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   117010   const unsigned char *q = (const unsigned char *) p;
   117011   sqlite_uint64 x = 0, y = 1;
   117012   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
   117013     x += y * (*q++ & 0x7f);
   117014     y <<= 7;
   117015   }
   117016   x += y * (*q++);
   117017   *v = (sqlite_int64) x;
   117018   return (int) (q - (unsigned char *)p);
   117019 }
   117020 
   117021 /*
   117022 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   117023 ** 32-bit integer before it is returned.
   117024 */
   117025 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   117026  sqlite_int64 i;
   117027  int ret = sqlite3Fts3GetVarint(p, &i);
   117028  *pi = (int) i;
   117029  return ret;
   117030 }
   117031 
   117032 /*
   117033 ** Return the number of bytes required to encode v as a varint
   117034 */
   117035 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   117036   int i = 0;
   117037   do{
   117038     i++;
   117039     v >>= 7;
   117040   }while( v!=0 );
   117041   return i;
   117042 }
   117043 
   117044 /*
   117045 ** Convert an SQL-style quoted string into a normal string by removing
   117046 ** the quote characters.  The conversion is done in-place.  If the
   117047 ** input does not begin with a quote character, then this routine
   117048 ** is a no-op.
   117049 **
   117050 ** Examples:
   117051 **
   117052 **     "abc"   becomes   abc
   117053 **     'xyz'   becomes   xyz
   117054 **     [pqr]   becomes   pqr
   117055 **     `mno`   becomes   mno
   117056 **
   117057 */
   117058 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   117059   char quote;                     /* Quote character (if any ) */
   117060 
   117061   quote = z[0];
   117062   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   117063     int iIn = 1;                  /* Index of next byte to read from input */
   117064     int iOut = 0;                 /* Index of next byte to write to output */
   117065 
   117066     /* If the first byte was a '[', then the close-quote character is a ']' */
   117067     if( quote=='[' ) quote = ']';
   117068 
   117069     while( ALWAYS(z[iIn]) ){
   117070       if( z[iIn]==quote ){
   117071         if( z[iIn+1]!=quote ) break;
   117072         z[iOut++] = quote;
   117073         iIn += 2;
   117074       }else{
   117075         z[iOut++] = z[iIn++];
   117076       }
   117077     }
   117078     z[iOut] = '\0';
   117079   }
   117080 }
   117081 
   117082 /*
   117083 ** Read a single varint from the doclist at *pp and advance *pp to point
   117084 ** to the first byte past the end of the varint.  Add the value of the varint
   117085 ** to *pVal.
   117086 */
   117087 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   117088   sqlite3_int64 iVal;
   117089   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   117090   *pVal += iVal;
   117091 }
   117092 
   117093 /*
   117094 ** When this function is called, *pp points to the first byte following a
   117095 ** varint that is part of a doclist (or position-list, or any other list
   117096 ** of varints). This function moves *pp to point to the start of that varint,
   117097 ** and sets *pVal by the varint value.
   117098 **
   117099 ** Argument pStart points to the first byte of the doclist that the
   117100 ** varint is part of.
   117101 */
   117102 static void fts3GetReverseVarint(
   117103   char **pp,
   117104   char *pStart,
   117105   sqlite3_int64 *pVal
   117106 ){
   117107   sqlite3_int64 iVal;
   117108   char *p;
   117109 
   117110   /* Pointer p now points at the first byte past the varint we are
   117111   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   117112   ** clear on character p[-1]. */
   117113   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
   117114   p++;
   117115   *pp = p;
   117116 
   117117   sqlite3Fts3GetVarint(p, &iVal);
   117118   *pVal = iVal;
   117119 }
   117120 
   117121 /*
   117122 ** The xDisconnect() virtual table method.
   117123 */
   117124 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   117125   Fts3Table *p = (Fts3Table *)pVtab;
   117126   int i;
   117127 
   117128   assert( p->nPendingData==0 );
   117129   assert( p->pSegments==0 );
   117130 
   117131   /* Free any prepared statements held */
   117132   for(i=0; i<SizeofArray(p->aStmt); i++){
   117133     sqlite3_finalize(p->aStmt[i]);
   117134   }
   117135   sqlite3_free(p->zSegmentsTbl);
   117136   sqlite3_free(p->zReadExprlist);
   117137   sqlite3_free(p->zWriteExprlist);
   117138   sqlite3_free(p->zContentTbl);
   117139   sqlite3_free(p->zLanguageid);
   117140 
   117141   /* Invoke the tokenizer destructor to free the tokenizer. */
   117142   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   117143 
   117144   sqlite3_free(p);
   117145   return SQLITE_OK;
   117146 }
   117147 
   117148 /*
   117149 ** Construct one or more SQL statements from the format string given
   117150 ** and then evaluate those statements. The success code is written
   117151 ** into *pRc.
   117152 **
   117153 ** If *pRc is initially non-zero then this routine is a no-op.
   117154 */
   117155 static void fts3DbExec(
   117156   int *pRc,              /* Success code */
   117157   sqlite3 *db,           /* Database in which to run SQL */
   117158   const char *zFormat,   /* Format string for SQL */
   117159   ...                    /* Arguments to the format string */
   117160 ){
   117161   va_list ap;
   117162   char *zSql;
   117163   if( *pRc ) return;
   117164   va_start(ap, zFormat);
   117165   zSql = sqlite3_vmprintf(zFormat, ap);
   117166   va_end(ap);
   117167   if( zSql==0 ){
   117168     *pRc = SQLITE_NOMEM;
   117169   }else{
   117170     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   117171     sqlite3_free(zSql);
   117172   }
   117173 }
   117174 
   117175 /*
   117176 ** The xDestroy() virtual table method.
   117177 */
   117178 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   117179   Fts3Table *p = (Fts3Table *)pVtab;
   117180   int rc = SQLITE_OK;              /* Return code */
   117181   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
   117182   sqlite3 *db = p->db;             /* Database handle */
   117183 
   117184   /* Drop the shadow tables */
   117185   if( p->zContentTbl==0 ){
   117186     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
   117187   }
   117188   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
   117189   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
   117190   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
   117191   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
   117192 
   117193   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   117194   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   117195   ** Otherwise, return an SQLite error code.
   117196   */
   117197   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   117198 }
   117199 
   117200 
   117201 /*
   117202 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   117203 ** passed as the first argument. This is done as part of the xConnect()
   117204 ** and xCreate() methods.
   117205 **
   117206 ** If *pRc is non-zero when this function is called, it is a no-op.
   117207 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   117208 ** before returning.
   117209 */
   117210 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   117211   if( *pRc==SQLITE_OK ){
   117212     int i;                        /* Iterator variable */
   117213     int rc;                       /* Return code */
   117214     char *zSql;                   /* SQL statement passed to declare_vtab() */
   117215     char *zCols;                  /* List of user defined columns */
   117216     const char *zLanguageid;
   117217 
   117218     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
   117219     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   117220 
   117221     /* Create a list of user columns for the virtual table */
   117222     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   117223     for(i=1; zCols && i<p->nColumn; i++){
   117224       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   117225     }
   117226 
   117227     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   117228     zSql = sqlite3_mprintf(
   117229         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
   117230         zCols, p->zName, zLanguageid
   117231     );
   117232     if( !zCols || !zSql ){
   117233       rc = SQLITE_NOMEM;
   117234     }else{
   117235       rc = sqlite3_declare_vtab(p->db, zSql);
   117236     }
   117237 
   117238     sqlite3_free(zSql);
   117239     sqlite3_free(zCols);
   117240     *pRc = rc;
   117241   }
   117242 }
   117243 
   117244 /*
   117245 ** Create the backing store tables (%_content, %_segments and %_segdir)
   117246 ** required by the FTS3 table passed as the only argument. This is done
   117247 ** as part of the vtab xCreate() method.
   117248 **
   117249 ** If the p->bHasDocsize boolean is true (indicating that this is an
   117250 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   117251 ** %_stat tables required by FTS4.
   117252 */
   117253 static int fts3CreateTables(Fts3Table *p){
   117254   int rc = SQLITE_OK;             /* Return code */
   117255   int i;                          /* Iterator variable */
   117256   sqlite3 *db = p->db;            /* The database connection */
   117257 
   117258   if( p->zContentTbl==0 ){
   117259     const char *zLanguageid = p->zLanguageid;
   117260     char *zContentCols;           /* Columns of %_content table */
   117261 
   117262     /* Create a list of user columns for the content table */
   117263     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   117264     for(i=0; zContentCols && i<p->nColumn; i++){
   117265       char *z = p->azColumn[i];
   117266       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   117267     }
   117268     if( zLanguageid && zContentCols ){
   117269       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
   117270     }
   117271     if( zContentCols==0 ) rc = SQLITE_NOMEM;
   117272 
   117273     /* Create the content table */
   117274     fts3DbExec(&rc, db,
   117275        "CREATE TABLE %Q.'%q_content'(%s)",
   117276        p->zDb, p->zName, zContentCols
   117277     );
   117278     sqlite3_free(zContentCols);
   117279   }
   117280 
   117281   /* Create other tables */
   117282   fts3DbExec(&rc, db,
   117283       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   117284       p->zDb, p->zName
   117285   );
   117286   fts3DbExec(&rc, db,
   117287       "CREATE TABLE %Q.'%q_segdir'("
   117288         "level INTEGER,"
   117289         "idx INTEGER,"
   117290         "start_block INTEGER,"
   117291         "leaves_end_block INTEGER,"
   117292         "end_block INTEGER,"
   117293         "root BLOB,"
   117294         "PRIMARY KEY(level, idx)"
   117295       ");",
   117296       p->zDb, p->zName
   117297   );
   117298   if( p->bHasDocsize ){
   117299     fts3DbExec(&rc, db,
   117300         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   117301         p->zDb, p->zName
   117302     );
   117303   }
   117304   if( p->bHasStat ){
   117305     fts3DbExec(&rc, db,
   117306         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
   117307         p->zDb, p->zName
   117308     );
   117309   }
   117310   return rc;
   117311 }
   117312 
   117313 /*
   117314 ** Store the current database page-size in bytes in p->nPgsz.
   117315 **
   117316 ** If *pRc is non-zero when this function is called, it is a no-op.
   117317 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   117318 ** before returning.
   117319 */
   117320 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   117321   if( *pRc==SQLITE_OK ){
   117322     int rc;                       /* Return code */
   117323     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   117324     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   117325 
   117326     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   117327     if( !zSql ){
   117328       rc = SQLITE_NOMEM;
   117329     }else{
   117330       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   117331       if( rc==SQLITE_OK ){
   117332         sqlite3_step(pStmt);
   117333         p->nPgsz = sqlite3_column_int(pStmt, 0);
   117334         rc = sqlite3_finalize(pStmt);
   117335       }else if( rc==SQLITE_AUTH ){
   117336         p->nPgsz = 1024;
   117337         rc = SQLITE_OK;
   117338       }
   117339     }
   117340     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   117341     sqlite3_free(zSql);
   117342     *pRc = rc;
   117343   }
   117344 }
   117345 
   117346 /*
   117347 ** "Special" FTS4 arguments are column specifications of the following form:
   117348 **
   117349 **   <key> = <value>
   117350 **
   117351 ** There may not be whitespace surrounding the "=" character. The <value>
   117352 ** term may be quoted, but the <key> may not.
   117353 */
   117354 static int fts3IsSpecialColumn(
   117355   const char *z,
   117356   int *pnKey,
   117357   char **pzValue
   117358 ){
   117359   char *zValue;
   117360   const char *zCsr = z;
   117361 
   117362   while( *zCsr!='=' ){
   117363     if( *zCsr=='\0' ) return 0;
   117364     zCsr++;
   117365   }
   117366 
   117367   *pnKey = (int)(zCsr-z);
   117368   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   117369   if( zValue ){
   117370     sqlite3Fts3Dequote(zValue);
   117371   }
   117372   *pzValue = zValue;
   117373   return 1;
   117374 }
   117375 
   117376 /*
   117377 ** Append the output of a printf() style formatting to an existing string.
   117378 */
   117379 static void fts3Appendf(
   117380   int *pRc,                       /* IN/OUT: Error code */
   117381   char **pz,                      /* IN/OUT: Pointer to string buffer */
   117382   const char *zFormat,            /* Printf format string to append */
   117383   ...                             /* Arguments for printf format string */
   117384 ){
   117385   if( *pRc==SQLITE_OK ){
   117386     va_list ap;
   117387     char *z;
   117388     va_start(ap, zFormat);
   117389     z = sqlite3_vmprintf(zFormat, ap);
   117390     va_end(ap);
   117391     if( z && *pz ){
   117392       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   117393       sqlite3_free(z);
   117394       z = z2;
   117395     }
   117396     if( z==0 ) *pRc = SQLITE_NOMEM;
   117397     sqlite3_free(*pz);
   117398     *pz = z;
   117399   }
   117400 }
   117401 
   117402 /*
   117403 ** Return a copy of input string zInput enclosed in double-quotes (") and
   117404 ** with all double quote characters escaped. For example:
   117405 **
   117406 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
   117407 **
   117408 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
   117409 ** is the callers responsibility to call sqlite3_free() to release this
   117410 ** memory.
   117411 */
   117412 static char *fts3QuoteId(char const *zInput){
   117413   int nRet;
   117414   char *zRet;
   117415   nRet = 2 + (int)strlen(zInput)*2 + 1;
   117416   zRet = sqlite3_malloc(nRet);
   117417   if( zRet ){
   117418     int i;
   117419     char *z = zRet;
   117420     *(z++) = '"';
   117421     for(i=0; zInput[i]; i++){
   117422       if( zInput[i]=='"' ) *(z++) = '"';
   117423       *(z++) = zInput[i];
   117424     }
   117425     *(z++) = '"';
   117426     *(z++) = '\0';
   117427   }
   117428   return zRet;
   117429 }
   117430 
   117431 /*
   117432 ** Return a list of comma separated SQL expressions and a FROM clause that
   117433 ** could be used in a SELECT statement such as the following:
   117434 **
   117435 **     SELECT <list of expressions> FROM %_content AS x ...
   117436 **
   117437 ** to return the docid, followed by each column of text data in order
   117438 ** from left to write. If parameter zFunc is not NULL, then instead of
   117439 ** being returned directly each column of text data is passed to an SQL
   117440 ** function named zFunc first. For example, if zFunc is "unzip" and the
   117441 ** table has the three user-defined columns "a", "b", and "c", the following
   117442 ** string is returned:
   117443 **
   117444 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
   117445 **
   117446 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   117447 ** is the responsibility of the caller to eventually free it.
   117448 **
   117449 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   117450 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   117451 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   117452 ** no error occurs, *pRc is left unmodified.
   117453 */
   117454 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
   117455   char *zRet = 0;
   117456   char *zFree = 0;
   117457   char *zFunction;
   117458   int i;
   117459 
   117460   if( p->zContentTbl==0 ){
   117461     if( !zFunc ){
   117462       zFunction = "";
   117463     }else{
   117464       zFree = zFunction = fts3QuoteId(zFunc);
   117465     }
   117466     fts3Appendf(pRc, &zRet, "docid");
   117467     for(i=0; i<p->nColumn; i++){
   117468       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
   117469     }
   117470     if( p->zLanguageid ){
   117471       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
   117472     }
   117473     sqlite3_free(zFree);
   117474   }else{
   117475     fts3Appendf(pRc, &zRet, "rowid");
   117476     for(i=0; i<p->nColumn; i++){
   117477       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
   117478     }
   117479     if( p->zLanguageid ){
   117480       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
   117481     }
   117482   }
   117483   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
   117484       p->zDb,
   117485       (p->zContentTbl ? p->zContentTbl : p->zName),
   117486       (p->zContentTbl ? "" : "_content")
   117487   );
   117488   return zRet;
   117489 }
   117490 
   117491 /*
   117492 ** Return a list of N comma separated question marks, where N is the number
   117493 ** of columns in the %_content table (one for the docid plus one for each
   117494 ** user-defined text column).
   117495 **
   117496 ** If argument zFunc is not NULL, then all but the first question mark
   117497 ** is preceded by zFunc and an open bracket, and followed by a closed
   117498 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
   117499 ** user-defined text columns, the following string is returned:
   117500 **
   117501 **     "?, zip(?), zip(?), zip(?)"
   117502 **
   117503 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   117504 ** is the responsibility of the caller to eventually free it.
   117505 **
   117506 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   117507 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   117508 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   117509 ** no error occurs, *pRc is left unmodified.
   117510 */
   117511 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
   117512   char *zRet = 0;
   117513   char *zFree = 0;
   117514   char *zFunction;
   117515   int i;
   117516 
   117517   if( !zFunc ){
   117518     zFunction = "";
   117519   }else{
   117520     zFree = zFunction = fts3QuoteId(zFunc);
   117521   }
   117522   fts3Appendf(pRc, &zRet, "?");
   117523   for(i=0; i<p->nColumn; i++){
   117524     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
   117525   }
   117526   if( p->zLanguageid ){
   117527     fts3Appendf(pRc, &zRet, ", ?");
   117528   }
   117529   sqlite3_free(zFree);
   117530   return zRet;
   117531 }
   117532 
   117533 /*
   117534 ** This function interprets the string at (*pp) as a non-negative integer
   117535 ** value. It reads the integer and sets *pnOut to the value read, then
   117536 ** sets *pp to point to the byte immediately following the last byte of
   117537 ** the integer value.
   117538 **
   117539 ** Only decimal digits ('0'..'9') may be part of an integer value.
   117540 **
   117541 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
   117542 ** the output value undefined. Otherwise SQLITE_OK is returned.
   117543 **
   117544 ** This function is used when parsing the "prefix=" FTS4 parameter.
   117545 */
   117546 static int fts3GobbleInt(const char **pp, int *pnOut){
   117547   const char *p;                  /* Iterator pointer */
   117548   int nInt = 0;                   /* Output value */
   117549 
   117550   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
   117551     nInt = nInt * 10 + (p[0] - '0');
   117552   }
   117553   if( p==*pp ) return SQLITE_ERROR;
   117554   *pnOut = nInt;
   117555   *pp = p;
   117556   return SQLITE_OK;
   117557 }
   117558 
   117559 /*
   117560 ** This function is called to allocate an array of Fts3Index structures
   117561 ** representing the indexes maintained by the current FTS table. FTS tables
   117562 ** always maintain the main "terms" index, but may also maintain one or
   117563 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
   117564 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
   117565 **
   117566 ** Argument zParam is passed the value of the "prefix=" option if one was
   117567 ** specified, or NULL otherwise.
   117568 **
   117569 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
   117570 ** the allocated array. *pnIndex is set to the number of elements in the
   117571 ** array. If an error does occur, an SQLite error code is returned.
   117572 **
   117573 ** Regardless of whether or not an error is returned, it is the responsibility
   117574 ** of the caller to call sqlite3_free() on the output array to free it.
   117575 */
   117576 static int fts3PrefixParameter(
   117577   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
   117578   int *pnIndex,                   /* OUT: size of *apIndex[] array */
   117579   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
   117580 ){
   117581   struct Fts3Index *aIndex;       /* Allocated array */
   117582   int nIndex = 1;                 /* Number of entries in array */
   117583 
   117584   if( zParam && zParam[0] ){
   117585     const char *p;
   117586     nIndex++;
   117587     for(p=zParam; *p; p++){
   117588       if( *p==',' ) nIndex++;
   117589     }
   117590   }
   117591 
   117592   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   117593   *apIndex = aIndex;
   117594   *pnIndex = nIndex;
   117595   if( !aIndex ){
   117596     return SQLITE_NOMEM;
   117597   }
   117598 
   117599   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   117600   if( zParam ){
   117601     const char *p = zParam;
   117602     int i;
   117603     for(i=1; i<nIndex; i++){
   117604       int nPrefix;
   117605       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   117606       aIndex[i].nPrefix = nPrefix;
   117607       p++;
   117608     }
   117609   }
   117610 
   117611   return SQLITE_OK;
   117612 }
   117613 
   117614 /*
   117615 ** This function is called when initializing an FTS4 table that uses the
   117616 ** content=xxx option. It determines the number of and names of the columns
   117617 ** of the new FTS4 table.
   117618 **
   117619 ** The third argument passed to this function is the value passed to the
   117620 ** config=xxx option (i.e. "xxx"). This function queries the database for
   117621 ** a table of that name. If found, the output variables are populated
   117622 ** as follows:
   117623 **
   117624 **   *pnCol:   Set to the number of columns table xxx has,
   117625 **
   117626 **   *pnStr:   Set to the total amount of space required to store a copy
   117627 **             of each columns name, including the nul-terminator.
   117628 **
   117629 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
   117630 **             the name of the corresponding column in table xxx. The array
   117631 **             and its contents are allocated using a single allocation. It
   117632 **             is the responsibility of the caller to free this allocation
   117633 **             by eventually passing the *pazCol value to sqlite3_free().
   117634 **
   117635 ** If the table cannot be found, an error code is returned and the output
   117636 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
   117637 ** returned (and the output variables are undefined).
   117638 */
   117639 static int fts3ContentColumns(
   117640   sqlite3 *db,                    /* Database handle */
   117641   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   117642   const char *zTbl,               /* Name of content table */
   117643   const char ***pazCol,           /* OUT: Malloc'd array of column names */
   117644   int *pnCol,                     /* OUT: Size of array *pazCol */
   117645   int *pnStr                      /* OUT: Bytes of string content */
   117646 ){
   117647   int rc = SQLITE_OK;             /* Return code */
   117648   char *zSql;                     /* "SELECT *" statement on zTbl */
   117649   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   117650 
   117651   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   117652   if( !zSql ){
   117653     rc = SQLITE_NOMEM;
   117654   }else{
   117655     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   117656   }
   117657   sqlite3_free(zSql);
   117658 
   117659   if( rc==SQLITE_OK ){
   117660     const char **azCol;           /* Output array */
   117661     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   117662     int nCol;                     /* Number of table columns */
   117663     int i;                        /* Used to iterate through columns */
   117664 
   117665     /* Loop through the returned columns. Set nStr to the number of bytes of
   117666     ** space required to store a copy of each column name, including the
   117667     ** nul-terminator byte.  */
   117668     nCol = sqlite3_column_count(pStmt);
   117669     for(i=0; i<nCol; i++){
   117670       const char *zCol = sqlite3_column_name(pStmt, i);
   117671       nStr += (int)strlen(zCol) + 1;
   117672     }
   117673 
   117674     /* Allocate and populate the array to return. */
   117675     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
   117676     if( azCol==0 ){
   117677       rc = SQLITE_NOMEM;
   117678     }else{
   117679       char *p = (char *)&azCol[nCol];
   117680       for(i=0; i<nCol; i++){
   117681         const char *zCol = sqlite3_column_name(pStmt, i);
   117682         int n = (int)strlen(zCol)+1;
   117683         memcpy(p, zCol, n);
   117684         azCol[i] = p;
   117685         p += n;
   117686       }
   117687     }
   117688     sqlite3_finalize(pStmt);
   117689 
   117690     /* Set the output variables. */
   117691     *pnCol = nCol;
   117692     *pnStr = nStr;
   117693     *pazCol = azCol;
   117694   }
   117695 
   117696   return rc;
   117697 }
   117698 
   117699 /*
   117700 ** This function is the implementation of both the xConnect and xCreate
   117701 ** methods of the FTS3 virtual table.
   117702 **
   117703 ** The argv[] array contains the following:
   117704 **
   117705 **   argv[0]   -> module name  ("fts3" or "fts4")
   117706 **   argv[1]   -> database name
   117707 **   argv[2]   -> table name
   117708 **   argv[...] -> "column name" and other module argument fields.
   117709 */
   117710 static int fts3InitVtab(
   117711   int isCreate,                   /* True for xCreate, false for xConnect */
   117712   sqlite3 *db,                    /* The SQLite database connection */
   117713   void *pAux,                     /* Hash table containing tokenizers */
   117714   int argc,                       /* Number of elements in argv array */
   117715   const char * const *argv,       /* xCreate/xConnect argument array */
   117716   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   117717   char **pzErr                    /* Write any error message here */
   117718 ){
   117719   Fts3Hash *pHash = (Fts3Hash *)pAux;
   117720   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   117721   int rc = SQLITE_OK;             /* Return code */
   117722   int i;                          /* Iterator variable */
   117723   int nByte;                      /* Size of allocation used for *p */
   117724   int iCol;                       /* Column index */
   117725   int nString = 0;                /* Bytes required to hold all column names */
   117726   int nCol = 0;                   /* Number of columns in the FTS table */
   117727   char *zCsr;                     /* Space for holding column names */
   117728   int nDb;                        /* Bytes required to hold database name */
   117729   int nName;                      /* Bytes required to hold table name */
   117730   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   117731   const char **aCol;              /* Array of column names */
   117732   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   117733 
   117734   int nIndex;                     /* Size of aIndex[] array */
   117735   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
   117736 
   117737   /* The results of parsing supported FTS4 key=value options: */
   117738   int bNoDocsize = 0;             /* True to omit %_docsize table */
   117739   int bDescIdx = 0;               /* True to store descending indexes */
   117740   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
   117741   char *zCompress = 0;            /* compress=? parameter (or NULL) */
   117742   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
   117743   char *zContent = 0;             /* content=? parameter (or NULL) */
   117744   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
   117745 
   117746   assert( strlen(argv[0])==4 );
   117747   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   117748        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   117749   );
   117750 
   117751   nDb = (int)strlen(argv[1]) + 1;
   117752   nName = (int)strlen(argv[2]) + 1;
   117753 
   117754   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
   117755   if( !aCol ) return SQLITE_NOMEM;
   117756   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
   117757 
   117758   /* Loop through all of the arguments passed by the user to the FTS3/4
   117759   ** module (i.e. all the column names and special arguments). This loop
   117760   ** does the following:
   117761   **
   117762   **   + Figures out the number of columns the FTSX table will have, and
   117763   **     the number of bytes of space that must be allocated to store copies
   117764   **     of the column names.
   117765   **
   117766   **   + If there is a tokenizer specification included in the arguments,
   117767   **     initializes the tokenizer pTokenizer.
   117768   */
   117769   for(i=3; rc==SQLITE_OK && i<argc; i++){
   117770     char const *z = argv[i];
   117771     int nKey;
   117772     char *zVal;
   117773 
   117774     /* Check if this is a tokenizer specification */
   117775     if( !pTokenizer
   117776      && strlen(z)>8
   117777      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   117778      && 0==sqlite3Fts3IsIdChar(z[8])
   117779     ){
   117780       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   117781     }
   117782 
   117783     /* Check if it is an FTS4 special argument. */
   117784     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   117785       struct Fts4Option {
   117786         const char *zOpt;
   117787         int nOpt;
   117788       } aFts4Opt[] = {
   117789         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
   117790         { "prefix",      6 },     /* 1 -> PREFIX */
   117791         { "compress",    8 },     /* 2 -> COMPRESS */
   117792         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
   117793         { "order",       5 },     /* 4 -> ORDER */
   117794         { "content",     7 },     /* 5 -> CONTENT */
   117795         { "languageid", 10 }      /* 6 -> LANGUAGEID */
   117796       };
   117797 
   117798       int iOpt;
   117799       if( !zVal ){
   117800         rc = SQLITE_NOMEM;
   117801       }else{
   117802         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
   117803           struct Fts4Option *pOp = &aFts4Opt[iOpt];
   117804           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
   117805             break;
   117806           }
   117807         }
   117808         if( iOpt==SizeofArray(aFts4Opt) ){
   117809           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
   117810           rc = SQLITE_ERROR;
   117811         }else{
   117812           switch( iOpt ){
   117813             case 0:               /* MATCHINFO */
   117814               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
   117815                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
   117816                 rc = SQLITE_ERROR;
   117817               }
   117818               bNoDocsize = 1;
   117819               break;
   117820 
   117821             case 1:               /* PREFIX */
   117822               sqlite3_free(zPrefix);
   117823               zPrefix = zVal;
   117824               zVal = 0;
   117825               break;
   117826 
   117827             case 2:               /* COMPRESS */
   117828               sqlite3_free(zCompress);
   117829               zCompress = zVal;
   117830               zVal = 0;
   117831               break;
   117832 
   117833             case 3:               /* UNCOMPRESS */
   117834               sqlite3_free(zUncompress);
   117835               zUncompress = zVal;
   117836               zVal = 0;
   117837               break;
   117838 
   117839             case 4:               /* ORDER */
   117840               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
   117841                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
   117842               ){
   117843                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
   117844                 rc = SQLITE_ERROR;
   117845               }
   117846               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
   117847               break;
   117848 
   117849             case 5:              /* CONTENT */
   117850               sqlite3_free(zContent);
   117851               zContent = zVal;
   117852               zVal = 0;
   117853               break;
   117854 
   117855             case 6:              /* LANGUAGEID */
   117856               assert( iOpt==6 );
   117857               sqlite3_free(zLanguageid);
   117858               zLanguageid = zVal;
   117859               zVal = 0;
   117860               break;
   117861           }
   117862         }
   117863         sqlite3_free(zVal);
   117864       }
   117865     }
   117866 
   117867     /* Otherwise, the argument is a column name. */
   117868     else {
   117869       nString += (int)(strlen(z) + 1);
   117870       aCol[nCol++] = z;
   117871     }
   117872   }
   117873 
   117874   /* If a content=xxx option was specified, the following:
   117875   **
   117876   **   1. Ignore any compress= and uncompress= options.
   117877   **
   117878   **   2. If no column names were specified as part of the CREATE VIRTUAL
   117879   **      TABLE statement, use all columns from the content table.
   117880   */
   117881   if( rc==SQLITE_OK && zContent ){
   117882     sqlite3_free(zCompress);
   117883     sqlite3_free(zUncompress);
   117884     zCompress = 0;
   117885     zUncompress = 0;
   117886     if( nCol==0 ){
   117887       sqlite3_free((void*)aCol);
   117888       aCol = 0;
   117889       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
   117890 
   117891       /* If a languageid= option was specified, remove the language id
   117892       ** column from the aCol[] array. */
   117893       if( rc==SQLITE_OK && zLanguageid ){
   117894         int j;
   117895         for(j=0; j<nCol; j++){
   117896           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
   117897             int k;
   117898             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
   117899             nCol--;
   117900             break;
   117901           }
   117902         }
   117903       }
   117904     }
   117905   }
   117906   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117907 
   117908   if( nCol==0 ){
   117909     assert( nString==0 );
   117910     aCol[0] = "content";
   117911     nString = 8;
   117912     nCol = 1;
   117913   }
   117914 
   117915   if( pTokenizer==0 ){
   117916     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   117917     if( rc!=SQLITE_OK ) goto fts3_init_out;
   117918   }
   117919   assert( pTokenizer );
   117920 
   117921   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
   117922   if( rc==SQLITE_ERROR ){
   117923     assert( zPrefix );
   117924     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
   117925   }
   117926   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117927 
   117928   /* Allocate and populate the Fts3Table structure. */
   117929   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
   117930           nCol * sizeof(char *) +              /* azColumn */
   117931           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
   117932           nName +                              /* zName */
   117933           nDb +                                /* zDb */
   117934           nString;                             /* Space for azColumn strings */
   117935   p = (Fts3Table*)sqlite3_malloc(nByte);
   117936   if( p==0 ){
   117937     rc = SQLITE_NOMEM;
   117938     goto fts3_init_out;
   117939   }
   117940   memset(p, 0, nByte);
   117941   p->db = db;
   117942   p->nColumn = nCol;
   117943   p->nPendingData = 0;
   117944   p->azColumn = (char **)&p[1];
   117945   p->pTokenizer = pTokenizer;
   117946   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   117947   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   117948   p->bHasStat = isFts4;
   117949   p->bDescIdx = bDescIdx;
   117950   p->zContentTbl = zContent;
   117951   p->zLanguageid = zLanguageid;
   117952   zContent = 0;
   117953   zLanguageid = 0;
   117954   TESTONLY( p->inTransaction = -1 );
   117955   TESTONLY( p->mxSavepoint = -1 );
   117956 
   117957   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
   117958   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
   117959   p->nIndex = nIndex;
   117960   for(i=0; i<nIndex; i++){
   117961     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
   117962   }
   117963 
   117964   /* Fill in the zName and zDb fields of the vtab structure. */
   117965   zCsr = (char *)&p->aIndex[nIndex];
   117966   p->zName = zCsr;
   117967   memcpy(zCsr, argv[2], nName);
   117968   zCsr += nName;
   117969   p->zDb = zCsr;
   117970   memcpy(zCsr, argv[1], nDb);
   117971   zCsr += nDb;
   117972 
   117973   /* Fill in the azColumn array */
   117974   for(iCol=0; iCol<nCol; iCol++){
   117975     char *z;
   117976     int n = 0;
   117977     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   117978     memcpy(zCsr, z, n);
   117979     zCsr[n] = '\0';
   117980     sqlite3Fts3Dequote(zCsr);
   117981     p->azColumn[iCol] = zCsr;
   117982     zCsr += n+1;
   117983     assert( zCsr <= &((char *)p)[nByte] );
   117984   }
   117985 
   117986   if( (zCompress==0)!=(zUncompress==0) ){
   117987     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
   117988     rc = SQLITE_ERROR;
   117989     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
   117990   }
   117991   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
   117992   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   117993   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117994 
   117995   /* If this is an xCreate call, create the underlying tables in the
   117996   ** database. TODO: For xConnect(), it could verify that said tables exist.
   117997   */
   117998   if( isCreate ){
   117999     rc = fts3CreateTables(p);
   118000   }
   118001 
   118002   /* Figure out the page-size for the database. This is required in order to
   118003   ** estimate the cost of loading large doclists from the database.  */
   118004   fts3DatabasePageSize(&rc, p);
   118005   p->nNodeSize = p->nPgsz-35;
   118006 
   118007   /* Declare the table schema to SQLite. */
   118008   fts3DeclareVtab(&rc, p);
   118009 
   118010 fts3_init_out:
   118011   sqlite3_free(zPrefix);
   118012   sqlite3_free(aIndex);
   118013   sqlite3_free(zCompress);
   118014   sqlite3_free(zUncompress);
   118015   sqlite3_free(zContent);
   118016   sqlite3_free(zLanguageid);
   118017   sqlite3_free((void *)aCol);
   118018   if( rc!=SQLITE_OK ){
   118019     if( p ){
   118020       fts3DisconnectMethod((sqlite3_vtab *)p);
   118021     }else if( pTokenizer ){
   118022       pTokenizer->pModule->xDestroy(pTokenizer);
   118023     }
   118024   }else{
   118025     assert( p->pSegments==0 );
   118026     *ppVTab = &p->base;
   118027   }
   118028   return rc;
   118029 }
   118030 
   118031 /*
   118032 ** The xConnect() and xCreate() methods for the virtual table. All the
   118033 ** work is done in function fts3InitVtab().
   118034 */
   118035 static int fts3ConnectMethod(
   118036   sqlite3 *db,                    /* Database connection */
   118037   void *pAux,                     /* Pointer to tokenizer hash table */
   118038   int argc,                       /* Number of elements in argv array */
   118039   const char * const *argv,       /* xCreate/xConnect argument array */
   118040   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   118041   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   118042 ){
   118043   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   118044 }
   118045 static int fts3CreateMethod(
   118046   sqlite3 *db,                    /* Database connection */
   118047   void *pAux,                     /* Pointer to tokenizer hash table */
   118048   int argc,                       /* Number of elements in argv array */
   118049   const char * const *argv,       /* xCreate/xConnect argument array */
   118050   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   118051   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   118052 ){
   118053   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   118054 }
   118055 
   118056 /*
   118057 ** Implementation of the xBestIndex method for FTS3 tables. There
   118058 ** are three possible strategies, in order of preference:
   118059 **
   118060 **   1. Direct lookup by rowid or docid.
   118061 **   2. Full-text search using a MATCH operator on a non-docid column.
   118062 **   3. Linear scan of %_content table.
   118063 */
   118064 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   118065   Fts3Table *p = (Fts3Table *)pVTab;
   118066   int i;                          /* Iterator variable */
   118067   int iCons = -1;                 /* Index of constraint to use */
   118068   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
   118069 
   118070   /* By default use a full table scan. This is an expensive option,
   118071   ** so search through the constraints to see if a more efficient
   118072   ** strategy is possible.
   118073   */
   118074   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   118075   pInfo->estimatedCost = 500000;
   118076   for(i=0; i<pInfo->nConstraint; i++){
   118077     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   118078     if( pCons->usable==0 ) continue;
   118079 
   118080     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   118081     if( iCons<0
   118082      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   118083      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
   118084     ){
   118085       pInfo->idxNum = FTS3_DOCID_SEARCH;
   118086       pInfo->estimatedCost = 1.0;
   118087       iCons = i;
   118088     }
   118089 
   118090     /* A MATCH constraint. Use a full-text search.
   118091     **
   118092     ** If there is more than one MATCH constraint available, use the first
   118093     ** one encountered. If there is both a MATCH constraint and a direct
   118094     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   118095     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   118096     ** it would lead to an "unable to use function MATCH in the requested
   118097     ** context" error.
   118098     */
   118099     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   118100      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   118101     ){
   118102       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   118103       pInfo->estimatedCost = 2.0;
   118104       iCons = i;
   118105     }
   118106 
   118107     /* Equality constraint on the langid column */
   118108     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   118109      && pCons->iColumn==p->nColumn + 2
   118110     ){
   118111       iLangidCons = i;
   118112     }
   118113   }
   118114 
   118115   if( iCons>=0 ){
   118116     pInfo->aConstraintUsage[iCons].argvIndex = 1;
   118117     pInfo->aConstraintUsage[iCons].omit = 1;
   118118   }
   118119   if( iLangidCons>=0 ){
   118120     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
   118121   }
   118122 
   118123   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
   118124   ** docid) order. Both ascending and descending are possible.
   118125   */
   118126   if( pInfo->nOrderBy==1 ){
   118127     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
   118128     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
   118129       if( pOrder->desc ){
   118130         pInfo->idxStr = "DESC";
   118131       }else{
   118132         pInfo->idxStr = "ASC";
   118133       }
   118134       pInfo->orderByConsumed = 1;
   118135     }
   118136   }
   118137 
   118138   assert( p->pSegments==0 );
   118139   return SQLITE_OK;
   118140 }
   118141 
   118142 /*
   118143 ** Implementation of xOpen method.
   118144 */
   118145 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   118146   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   118147 
   118148   UNUSED_PARAMETER(pVTab);
   118149 
   118150   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   118151   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   118152   ** if the allocation fails, return SQLITE_NOMEM.
   118153   */
   118154   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   118155   if( !pCsr ){
   118156     return SQLITE_NOMEM;
   118157   }
   118158   memset(pCsr, 0, sizeof(Fts3Cursor));
   118159   return SQLITE_OK;
   118160 }
   118161 
   118162 /*
   118163 ** Close the cursor.  For additional information see the documentation
   118164 ** on the xClose method of the virtual table interface.
   118165 */
   118166 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   118167   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   118168   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   118169   sqlite3_finalize(pCsr->pStmt);
   118170   sqlite3Fts3ExprFree(pCsr->pExpr);
   118171   sqlite3Fts3FreeDeferredTokens(pCsr);
   118172   sqlite3_free(pCsr->aDoclist);
   118173   sqlite3_free(pCsr->aMatchinfo);
   118174   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   118175   sqlite3_free(pCsr);
   118176   return SQLITE_OK;
   118177 }
   118178 
   118179 /*
   118180 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
   118181 ** compose and prepare an SQL statement of the form:
   118182 **
   118183 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
   118184 **
   118185 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
   118186 ** it. If an error occurs, return an SQLite error code.
   118187 **
   118188 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
   118189 */
   118190 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
   118191   int rc = SQLITE_OK;
   118192   if( pCsr->pStmt==0 ){
   118193     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   118194     char *zSql;
   118195     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
   118196     if( !zSql ) return SQLITE_NOMEM;
   118197     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   118198     sqlite3_free(zSql);
   118199   }
   118200   *ppStmt = pCsr->pStmt;
   118201   return rc;
   118202 }
   118203 
   118204 /*
   118205 ** Position the pCsr->pStmt statement so that it is on the row
   118206 ** of the %_content table that contains the last match.  Return
   118207 ** SQLITE_OK on success.
   118208 */
   118209 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   118210   int rc = SQLITE_OK;
   118211   if( pCsr->isRequireSeek ){
   118212     sqlite3_stmt *pStmt = 0;
   118213 
   118214     rc = fts3CursorSeekStmt(pCsr, &pStmt);
   118215     if( rc==SQLITE_OK ){
   118216       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   118217       pCsr->isRequireSeek = 0;
   118218       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   118219         return SQLITE_OK;
   118220       }else{
   118221         rc = sqlite3_reset(pCsr->pStmt);
   118222         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
   118223           /* If no row was found and no error has occured, then the %_content
   118224           ** table is missing a row that is present in the full-text index.
   118225           ** The data structures are corrupt.  */
   118226           rc = FTS_CORRUPT_VTAB;
   118227           pCsr->isEof = 1;
   118228         }
   118229       }
   118230     }
   118231   }
   118232 
   118233   if( rc!=SQLITE_OK && pContext ){
   118234     sqlite3_result_error_code(pContext, rc);
   118235   }
   118236   return rc;
   118237 }
   118238 
   118239 /*
   118240 ** This function is used to process a single interior node when searching
   118241 ** a b-tree for a term or term prefix. The node data is passed to this
   118242 ** function via the zNode/nNode parameters. The term to search for is
   118243 ** passed in zTerm/nTerm.
   118244 **
   118245 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   118246 ** of the child node that heads the sub-tree that may contain the term.
   118247 **
   118248 ** If piLast is not NULL, then *piLast is set to the right-most child node
   118249 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   118250 ** a prefix.
   118251 **
   118252 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   118253 */
   118254 static int fts3ScanInteriorNode(
   118255   const char *zTerm,              /* Term to select leaves for */
   118256   int nTerm,                      /* Size of term zTerm in bytes */
   118257   const char *zNode,              /* Buffer containing segment interior node */
   118258   int nNode,                      /* Size of buffer at zNode */
   118259   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   118260   sqlite3_int64 *piLast           /* OUT: Selected child node */
   118261 ){
   118262   int rc = SQLITE_OK;             /* Return code */
   118263   const char *zCsr = zNode;       /* Cursor to iterate through node */
   118264   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   118265   char *zBuffer = 0;              /* Buffer to load terms into */
   118266   int nAlloc = 0;                 /* Size of allocated buffer */
   118267   int isFirstTerm = 1;            /* True when processing first term on page */
   118268   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   118269 
   118270   /* Skip over the 'height' varint that occurs at the start of every
   118271   ** interior node. Then load the blockid of the left-child of the b-tree
   118272   ** node into variable iChild.
   118273   **
   118274   ** Even if the data structure on disk is corrupted, this (reading two
   118275   ** varints from the buffer) does not risk an overread. If zNode is a
   118276   ** root node, then the buffer comes from a SELECT statement. SQLite does
   118277   ** not make this guarantee explicitly, but in practice there are always
   118278   ** either more than 20 bytes of allocated space following the nNode bytes of
   118279   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   118280   ** table, then there are always 20 bytes of zeroed padding following the
   118281   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   118282   */
   118283   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   118284   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   118285   if( zCsr>zEnd ){
   118286     return FTS_CORRUPT_VTAB;
   118287   }
   118288 
   118289   while( zCsr<zEnd && (piFirst || piLast) ){
   118290     int cmp;                      /* memcmp() result */
   118291     int nSuffix;                  /* Size of term suffix */
   118292     int nPrefix = 0;              /* Size of term prefix */
   118293     int nBuffer;                  /* Total term size */
   118294 
   118295     /* Load the next term on the node into zBuffer. Use realloc() to expand
   118296     ** the size of zBuffer if required.  */
   118297     if( !isFirstTerm ){
   118298       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
   118299     }
   118300     isFirstTerm = 0;
   118301     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
   118302 
   118303     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
   118304       rc = FTS_CORRUPT_VTAB;
   118305       goto finish_scan;
   118306     }
   118307     if( nPrefix+nSuffix>nAlloc ){
   118308       char *zNew;
   118309       nAlloc = (nPrefix+nSuffix) * 2;
   118310       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   118311       if( !zNew ){
   118312         rc = SQLITE_NOMEM;
   118313         goto finish_scan;
   118314       }
   118315       zBuffer = zNew;
   118316     }
   118317     assert( zBuffer );
   118318     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   118319     nBuffer = nPrefix + nSuffix;
   118320     zCsr += nSuffix;
   118321 
   118322     /* Compare the term we are searching for with the term just loaded from
   118323     ** the interior node. If the specified term is greater than or equal
   118324     ** to the term from the interior node, then all terms on the sub-tree
   118325     ** headed by node iChild are smaller than zTerm. No need to search
   118326     ** iChild.
   118327     **
   118328     ** If the interior node term is larger than the specified term, then
   118329     ** the tree headed by iChild may contain the specified term.
   118330     */
   118331     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   118332     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   118333       *piFirst = iChild;
   118334       piFirst = 0;
   118335     }
   118336 
   118337     if( piLast && cmp<0 ){
   118338       *piLast = iChild;
   118339       piLast = 0;
   118340     }
   118341 
   118342     iChild++;
   118343   };
   118344 
   118345   if( piFirst ) *piFirst = iChild;
   118346   if( piLast ) *piLast = iChild;
   118347 
   118348  finish_scan:
   118349   sqlite3_free(zBuffer);
   118350   return rc;
   118351 }
   118352 
   118353 
   118354 /*
   118355 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   118356 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   118357 ** contains a term. This function searches the sub-tree headed by the zNode
   118358 ** node for the range of leaf nodes that may contain the specified term
   118359 ** or terms for which the specified term is a prefix.
   118360 **
   118361 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   118362 ** left-most leaf node in the tree that may contain the specified term.
   118363 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   118364 ** right-most leaf node that may contain a term for which the specified
   118365 ** term is a prefix.
   118366 **
   118367 ** It is possible that the range of returned leaf nodes does not contain
   118368 ** the specified term or any terms for which it is a prefix. However, if the
   118369 ** segment does contain any such terms, they are stored within the identified
   118370 ** range. Because this function only inspects interior segment nodes (and
   118371 ** never loads leaf nodes into memory), it is not possible to be sure.
   118372 **
   118373 ** If an error occurs, an error code other than SQLITE_OK is returned.
   118374 */
   118375 static int fts3SelectLeaf(
   118376   Fts3Table *p,                   /* Virtual table handle */
   118377   const char *zTerm,              /* Term to select leaves for */
   118378   int nTerm,                      /* Size of term zTerm in bytes */
   118379   const char *zNode,              /* Buffer containing segment interior node */
   118380   int nNode,                      /* Size of buffer at zNode */
   118381   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   118382   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   118383 ){
   118384   int rc;                         /* Return code */
   118385   int iHeight;                    /* Height of this node in tree */
   118386 
   118387   assert( piLeaf || piLeaf2 );
   118388 
   118389   sqlite3Fts3GetVarint32(zNode, &iHeight);
   118390   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   118391   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   118392 
   118393   if( rc==SQLITE_OK && iHeight>1 ){
   118394     char *zBlob = 0;              /* Blob read from %_segments table */
   118395     int nBlob;                    /* Size of zBlob in bytes */
   118396 
   118397     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   118398       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
   118399       if( rc==SQLITE_OK ){
   118400         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   118401       }
   118402       sqlite3_free(zBlob);
   118403       piLeaf = 0;
   118404       zBlob = 0;
   118405     }
   118406 
   118407     if( rc==SQLITE_OK ){
   118408       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
   118409     }
   118410     if( rc==SQLITE_OK ){
   118411       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   118412     }
   118413     sqlite3_free(zBlob);
   118414   }
   118415 
   118416   return rc;
   118417 }
   118418 
   118419 /*
   118420 ** This function is used to create delta-encoded serialized lists of FTS3
   118421 ** varints. Each call to this function appends a single varint to a list.
   118422 */
   118423 static void fts3PutDeltaVarint(
   118424   char **pp,                      /* IN/OUT: Output pointer */
   118425   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   118426   sqlite3_int64 iVal              /* Write this value to the list */
   118427 ){
   118428   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   118429   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   118430   *piPrev = iVal;
   118431 }
   118432 
   118433 /*
   118434 ** When this function is called, *ppPoslist is assumed to point to the
   118435 ** start of a position-list. After it returns, *ppPoslist points to the
   118436 ** first byte after the position-list.
   118437 **
   118438 ** A position list is list of positions (delta encoded) and columns for
   118439 ** a single document record of a doclist.  So, in other words, this
   118440 ** routine advances *ppPoslist so that it points to the next docid in
   118441 ** the doclist, or to the first byte past the end of the doclist.
   118442 **
   118443 ** If pp is not NULL, then the contents of the position list are copied
   118444 ** to *pp. *pp is set to point to the first byte past the last byte copied
   118445 ** before this function returns.
   118446 */
   118447 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   118448   char *pEnd = *ppPoslist;
   118449   char c = 0;
   118450 
   118451   /* The end of a position list is marked by a zero encoded as an FTS3
   118452   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   118453   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   118454   ** of some other, multi-byte, value.
   118455   **
   118456   ** The following while-loop moves pEnd to point to the first byte that is not
   118457   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   118458   ** pEnd once more so that it points to the byte immediately following the
   118459   ** last byte in the position-list.
   118460   */
   118461   while( *pEnd | c ){
   118462     c = *pEnd++ & 0x80;
   118463     testcase( c!=0 && (*pEnd)==0 );
   118464   }
   118465   pEnd++;  /* Advance past the POS_END terminator byte */
   118466 
   118467   if( pp ){
   118468     int n = (int)(pEnd - *ppPoslist);
   118469     char *p = *pp;
   118470     memcpy(p, *ppPoslist, n);
   118471     p += n;
   118472     *pp = p;
   118473   }
   118474   *ppPoslist = pEnd;
   118475 }
   118476 
   118477 /*
   118478 ** When this function is called, *ppPoslist is assumed to point to the
   118479 ** start of a column-list. After it returns, *ppPoslist points to the
   118480 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   118481 **
   118482 ** A column-list is list of delta-encoded positions for a single column
   118483 ** within a single document within a doclist.
   118484 **
   118485 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   118486 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   118487 ** the POS_COLUMN or POS_END that terminates the column-list.
   118488 **
   118489 ** If pp is not NULL, then the contents of the column-list are copied
   118490 ** to *pp. *pp is set to point to the first byte past the last byte copied
   118491 ** before this function returns.  The POS_COLUMN or POS_END terminator
   118492 ** is not copied into *pp.
   118493 */
   118494 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   118495   char *pEnd = *ppPoslist;
   118496   char c = 0;
   118497 
   118498   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   118499   ** not part of a multi-byte varint.
   118500   */
   118501   while( 0xFE & (*pEnd | c) ){
   118502     c = *pEnd++ & 0x80;
   118503     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   118504   }
   118505   if( pp ){
   118506     int n = (int)(pEnd - *ppPoslist);
   118507     char *p = *pp;
   118508     memcpy(p, *ppPoslist, n);
   118509     p += n;
   118510     *pp = p;
   118511   }
   118512   *ppPoslist = pEnd;
   118513 }
   118514 
   118515 /*
   118516 ** Value used to signify the end of an position-list. This is safe because
   118517 ** it is not possible to have a document with 2^31 terms.
   118518 */
   118519 #define POSITION_LIST_END 0x7fffffff
   118520 
   118521 /*
   118522 ** This function is used to help parse position-lists. When this function is
   118523 ** called, *pp may point to the start of the next varint in the position-list
   118524 ** being parsed, or it may point to 1 byte past the end of the position-list
   118525 ** (in which case **pp will be a terminator bytes POS_END (0) or
   118526 ** (1)).
   118527 **
   118528 ** If *pp points past the end of the current position-list, set *pi to
   118529 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   118530 ** increment the current value of *pi by the value read, and set *pp to
   118531 ** point to the next value before returning.
   118532 **
   118533 ** Before calling this routine *pi must be initialized to the value of
   118534 ** the previous position, or zero if we are reading the first position
   118535 ** in the position-list.  Because positions are delta-encoded, the value
   118536 ** of the previous position is needed in order to compute the value of
   118537 ** the next position.
   118538 */
   118539 static void fts3ReadNextPos(
   118540   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   118541   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   118542 ){
   118543   if( (**pp)&0xFE ){
   118544     fts3GetDeltaVarint(pp, pi);
   118545     *pi -= 2;
   118546   }else{
   118547     *pi = POSITION_LIST_END;
   118548   }
   118549 }
   118550 
   118551 /*
   118552 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   118553 ** the value of iCol encoded as a varint to *pp.   This will start a new
   118554 ** column list.
   118555 **
   118556 ** Set *pp to point to the byte just after the last byte written before
   118557 ** returning (do not modify it if iCol==0). Return the total number of bytes
   118558 ** written (0 if iCol==0).
   118559 */
   118560 static int fts3PutColNumber(char **pp, int iCol){
   118561   int n = 0;                      /* Number of bytes written */
   118562   if( iCol ){
   118563     char *p = *pp;                /* Output pointer */
   118564     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   118565     *p = 0x01;
   118566     *pp = &p[n];
   118567   }
   118568   return n;
   118569 }
   118570 
   118571 /*
   118572 ** Compute the union of two position lists.  The output written
   118573 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   118574 ** order and with any duplicates removed.  All pointers are
   118575 ** updated appropriately.   The caller is responsible for insuring
   118576 ** that there is enough space in *pp to hold the complete output.
   118577 */
   118578 static void fts3PoslistMerge(
   118579   char **pp,                      /* Output buffer */
   118580   char **pp1,                     /* Left input list */
   118581   char **pp2                      /* Right input list */
   118582 ){
   118583   char *p = *pp;
   118584   char *p1 = *pp1;
   118585   char *p2 = *pp2;
   118586 
   118587   while( *p1 || *p2 ){
   118588     int iCol1;         /* The current column index in pp1 */
   118589     int iCol2;         /* The current column index in pp2 */
   118590 
   118591     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
   118592     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   118593     else iCol1 = 0;
   118594 
   118595     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
   118596     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   118597     else iCol2 = 0;
   118598 
   118599     if( iCol1==iCol2 ){
   118600       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   118601       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   118602       sqlite3_int64 iPrev = 0;
   118603       int n = fts3PutColNumber(&p, iCol1);
   118604       p1 += n;
   118605       p2 += n;
   118606 
   118607       /* At this point, both p1 and p2 point to the start of column-lists
   118608       ** for the same column (the column with index iCol1 and iCol2).
   118609       ** A column-list is a list of non-negative delta-encoded varints, each
   118610       ** incremented by 2 before being stored. Each list is terminated by a
   118611       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   118612       ** and writes the results to buffer p. p is left pointing to the byte
   118613       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   118614       ** written to the output.
   118615       */
   118616       fts3GetDeltaVarint(&p1, &i1);
   118617       fts3GetDeltaVarint(&p2, &i2);
   118618       do {
   118619         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   118620         iPrev -= 2;
   118621         if( i1==i2 ){
   118622           fts3ReadNextPos(&p1, &i1);
   118623           fts3ReadNextPos(&p2, &i2);
   118624         }else if( i1<i2 ){
   118625           fts3ReadNextPos(&p1, &i1);
   118626         }else{
   118627           fts3ReadNextPos(&p2, &i2);
   118628         }
   118629       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   118630     }else if( iCol1<iCol2 ){
   118631       p1 += fts3PutColNumber(&p, iCol1);
   118632       fts3ColumnlistCopy(&p, &p1);
   118633     }else{
   118634       p2 += fts3PutColNumber(&p, iCol2);
   118635       fts3ColumnlistCopy(&p, &p2);
   118636     }
   118637   }
   118638 
   118639   *p++ = POS_END;
   118640   *pp = p;
   118641   *pp1 = p1 + 1;
   118642   *pp2 = p2 + 1;
   118643 }
   118644 
   118645 /*
   118646 ** This function is used to merge two position lists into one. When it is
   118647 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   118648 ** the part of a doclist that follows each document id. For example, if a row
   118649 ** contains:
   118650 **
   118651 **     'a b c'|'x y z'|'a b b a'
   118652 **
   118653 ** Then the position list for this row for token 'b' would consist of:
   118654 **
   118655 **     0x02 0x01 0x02 0x03 0x03 0x00
   118656 **
   118657 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   118658 ** byte following the 0x00 terminator of their respective position lists.
   118659 **
   118660 ** If isSaveLeft is 0, an entry is added to the output position list for
   118661 ** each position in *pp2 for which there exists one or more positions in
   118662 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   118663 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   118664 ** slots before it.
   118665 **
   118666 ** e.g. nToken==1 searches for adjacent positions.
   118667 */
   118668 static int fts3PoslistPhraseMerge(
   118669   char **pp,                      /* IN/OUT: Preallocated output buffer */
   118670   int nToken,                     /* Maximum difference in token positions */
   118671   int isSaveLeft,                 /* Save the left position */
   118672   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   118673   char **pp1,                     /* IN/OUT: Left input list */
   118674   char **pp2                      /* IN/OUT: Right input list */
   118675 ){
   118676   char *p = *pp;
   118677   char *p1 = *pp1;
   118678   char *p2 = *pp2;
   118679   int iCol1 = 0;
   118680   int iCol2 = 0;
   118681 
   118682   /* Never set both isSaveLeft and isExact for the same invocation. */
   118683   assert( isSaveLeft==0 || isExact==0 );
   118684 
   118685   assert( p!=0 && *p1!=0 && *p2!=0 );
   118686   if( *p1==POS_COLUMN ){
   118687     p1++;
   118688     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118689   }
   118690   if( *p2==POS_COLUMN ){
   118691     p2++;
   118692     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118693   }
   118694 
   118695   while( 1 ){
   118696     if( iCol1==iCol2 ){
   118697       char *pSave = p;
   118698       sqlite3_int64 iPrev = 0;
   118699       sqlite3_int64 iPos1 = 0;
   118700       sqlite3_int64 iPos2 = 0;
   118701 
   118702       if( iCol1 ){
   118703         *p++ = POS_COLUMN;
   118704         p += sqlite3Fts3PutVarint(p, iCol1);
   118705       }
   118706 
   118707       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   118708       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   118709       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   118710       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   118711 
   118712       while( 1 ){
   118713         if( iPos2==iPos1+nToken
   118714          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   118715         ){
   118716           sqlite3_int64 iSave;
   118717           iSave = isSaveLeft ? iPos1 : iPos2;
   118718           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   118719           pSave = 0;
   118720           assert( p );
   118721         }
   118722         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   118723           if( (*p2&0xFE)==0 ) break;
   118724           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   118725         }else{
   118726           if( (*p1&0xFE)==0 ) break;
   118727           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   118728         }
   118729       }
   118730 
   118731       if( pSave ){
   118732         assert( pp && p );
   118733         p = pSave;
   118734       }
   118735 
   118736       fts3ColumnlistCopy(0, &p1);
   118737       fts3ColumnlistCopy(0, &p2);
   118738       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   118739       if( 0==*p1 || 0==*p2 ) break;
   118740 
   118741       p1++;
   118742       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118743       p2++;
   118744       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118745     }
   118746 
   118747     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   118748     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   118749     ** end of the position list, or the 0x01 that precedes the next
   118750     ** column-number in the position list.
   118751     */
   118752     else if( iCol1<iCol2 ){
   118753       fts3ColumnlistCopy(0, &p1);
   118754       if( 0==*p1 ) break;
   118755       p1++;
   118756       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118757     }else{
   118758       fts3ColumnlistCopy(0, &p2);
   118759       if( 0==*p2 ) break;
   118760       p2++;
   118761       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118762     }
   118763   }
   118764 
   118765   fts3PoslistCopy(0, &p2);
   118766   fts3PoslistCopy(0, &p1);
   118767   *pp1 = p1;
   118768   *pp2 = p2;
   118769   if( *pp==p ){
   118770     return 0;
   118771   }
   118772   *p++ = 0x00;
   118773   *pp = p;
   118774   return 1;
   118775 }
   118776 
   118777 /*
   118778 ** Merge two position-lists as required by the NEAR operator. The argument
   118779 ** position lists correspond to the left and right phrases of an expression
   118780 ** like:
   118781 **
   118782 **     "phrase 1" NEAR "phrase number 2"
   118783 **
   118784 ** Position list *pp1 corresponds to the left-hand side of the NEAR
   118785 ** expression and *pp2 to the right. As usual, the indexes in the position
   118786 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
   118787 ** in the example above).
   118788 **
   118789 ** The output position list - written to *pp - is a copy of *pp2 with those
   118790 ** entries that are not sufficiently NEAR entries in *pp1 removed.
   118791 */
   118792 static int fts3PoslistNearMerge(
   118793   char **pp,                      /* Output buffer */
   118794   char *aTmp,                     /* Temporary buffer space */
   118795   int nRight,                     /* Maximum difference in token positions */
   118796   int nLeft,                      /* Maximum difference in token positions */
   118797   char **pp1,                     /* IN/OUT: Left input list */
   118798   char **pp2                      /* IN/OUT: Right input list */
   118799 ){
   118800   char *p1 = *pp1;
   118801   char *p2 = *pp2;
   118802 
   118803   char *pTmp1 = aTmp;
   118804   char *pTmp2;
   118805   char *aTmp2;
   118806   int res = 1;
   118807 
   118808   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   118809   aTmp2 = pTmp2 = pTmp1;
   118810   *pp1 = p1;
   118811   *pp2 = p2;
   118812   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   118813   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   118814     fts3PoslistMerge(pp, &aTmp, &aTmp2);
   118815   }else if( pTmp1!=aTmp ){
   118816     fts3PoslistCopy(pp, &aTmp);
   118817   }else if( pTmp2!=aTmp2 ){
   118818     fts3PoslistCopy(pp, &aTmp2);
   118819   }else{
   118820     res = 0;
   118821   }
   118822 
   118823   return res;
   118824 }
   118825 
   118826 /*
   118827 ** An instance of this function is used to merge together the (potentially
   118828 ** large number of) doclists for each term that matches a prefix query.
   118829 ** See function fts3TermSelectMerge() for details.
   118830 */
   118831 typedef struct TermSelect TermSelect;
   118832 struct TermSelect {
   118833   char *aaOutput[16];             /* Malloc'd output buffers */
   118834   int anOutput[16];               /* Size each output buffer in bytes */
   118835 };
   118836 
   118837 /*
   118838 ** This function is used to read a single varint from a buffer. Parameter
   118839 ** pEnd points 1 byte past the end of the buffer. When this function is
   118840 ** called, if *pp points to pEnd or greater, then the end of the buffer
   118841 ** has been reached. In this case *pp is set to 0 and the function returns.
   118842 **
   118843 ** If *pp does not point to or past pEnd, then a single varint is read
   118844 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
   118845 **
   118846 ** If bDescIdx is false, the value read is added to *pVal before returning.
   118847 ** If it is true, the value read is subtracted from *pVal before this
   118848 ** function returns.
   118849 */
   118850 static void fts3GetDeltaVarint3(
   118851   char **pp,                      /* IN/OUT: Point to read varint from */
   118852   char *pEnd,                     /* End of buffer */
   118853   int bDescIdx,                   /* True if docids are descending */
   118854   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
   118855 ){
   118856   if( *pp>=pEnd ){
   118857     *pp = 0;
   118858   }else{
   118859     sqlite3_int64 iVal;
   118860     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   118861     if( bDescIdx ){
   118862       *pVal -= iVal;
   118863     }else{
   118864       *pVal += iVal;
   118865     }
   118866   }
   118867 }
   118868 
   118869 /*
   118870 ** This function is used to write a single varint to a buffer. The varint
   118871 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
   118872 ** end of the value written.
   118873 **
   118874 ** If *pbFirst is zero when this function is called, the value written to
   118875 ** the buffer is that of parameter iVal.
   118876 **
   118877 ** If *pbFirst is non-zero when this function is called, then the value
   118878 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
   118879 ** (if bDescIdx is non-zero).
   118880 **
   118881 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
   118882 ** to the value of parameter iVal.
   118883 */
   118884 static void fts3PutDeltaVarint3(
   118885   char **pp,                      /* IN/OUT: Output pointer */
   118886   int bDescIdx,                   /* True for descending docids */
   118887   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   118888   int *pbFirst,                   /* IN/OUT: True after first int written */
   118889   sqlite3_int64 iVal              /* Write this value to the list */
   118890 ){
   118891   sqlite3_int64 iWrite;
   118892   if( bDescIdx==0 || *pbFirst==0 ){
   118893     iWrite = iVal - *piPrev;
   118894   }else{
   118895     iWrite = *piPrev - iVal;
   118896   }
   118897   assert( *pbFirst || *piPrev==0 );
   118898   assert( *pbFirst==0 || iWrite>0 );
   118899   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   118900   *piPrev = iVal;
   118901   *pbFirst = 1;
   118902 }
   118903 
   118904 
   118905 /*
   118906 ** This macro is used by various functions that merge doclists. The two
   118907 ** arguments are 64-bit docid values. If the value of the stack variable
   118908 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
   118909 ** Otherwise, (i2-i1).
   118910 **
   118911 ** Using this makes it easier to write code that can merge doclists that are
   118912 ** sorted in either ascending or descending order.
   118913 */
   118914 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
   118915 
   118916 /*
   118917 ** This function does an "OR" merge of two doclists (output contains all
   118918 ** positions contained in either argument doclist). If the docids in the
   118919 ** input doclists are sorted in ascending order, parameter bDescDoclist
   118920 ** should be false. If they are sorted in ascending order, it should be
   118921 ** passed a non-zero value.
   118922 **
   118923 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
   118924 ** containing the output doclist and SQLITE_OK is returned. In this case
   118925 ** *pnOut is set to the number of bytes in the output doclist.
   118926 **
   118927 ** If an error occurs, an SQLite error code is returned. The output values
   118928 ** are undefined in this case.
   118929 */
   118930 static int fts3DoclistOrMerge(
   118931   int bDescDoclist,               /* True if arguments are desc */
   118932   char *a1, int n1,               /* First doclist */
   118933   char *a2, int n2,               /* Second doclist */
   118934   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
   118935 ){
   118936   sqlite3_int64 i1 = 0;
   118937   sqlite3_int64 i2 = 0;
   118938   sqlite3_int64 iPrev = 0;
   118939   char *pEnd1 = &a1[n1];
   118940   char *pEnd2 = &a2[n2];
   118941   char *p1 = a1;
   118942   char *p2 = a2;
   118943   char *p;
   118944   char *aOut;
   118945   int bFirstOut = 0;
   118946 
   118947   *paOut = 0;
   118948   *pnOut = 0;
   118949 
   118950   /* Allocate space for the output. Both the input and output doclists
   118951   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
   118952   ** then the first docid in each list is simply encoded as a varint. For
   118953   ** each subsequent docid, the varint stored is the difference between the
   118954   ** current and previous docid (a positive number - since the list is in
   118955   ** ascending order).
   118956   **
   118957   ** The first docid written to the output is therefore encoded using the
   118958   ** same number of bytes as it is in whichever of the input lists it is
   118959   ** read from. And each subsequent docid read from the same input list
   118960   ** consumes either the same or less bytes as it did in the input (since
   118961   ** the difference between it and the previous value in the output must
   118962   ** be a positive value less than or equal to the delta value read from
   118963   ** the input list). The same argument applies to all but the first docid
   118964   ** read from the 'other' list. And to the contents of all position lists
   118965   ** that will be copied and merged from the input to the output.
   118966   **
   118967   ** However, if the first docid copied to the output is a negative number,
   118968   ** then the encoding of the first docid from the 'other' input list may
   118969   ** be larger in the output than it was in the input (since the delta value
   118970   ** may be a larger positive integer than the actual docid).
   118971   **
   118972   ** The space required to store the output is therefore the sum of the
   118973   ** sizes of the two inputs, plus enough space for exactly one of the input
   118974   ** docids to grow.
   118975   **
   118976   ** A symetric argument may be made if the doclists are in descending
   118977   ** order.
   118978   */
   118979   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
   118980   if( !aOut ) return SQLITE_NOMEM;
   118981 
   118982   p = aOut;
   118983   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   118984   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   118985   while( p1 || p2 ){
   118986     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   118987 
   118988     if( p2 && p1 && iDiff==0 ){
   118989       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   118990       fts3PoslistMerge(&p, &p1, &p2);
   118991       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   118992       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   118993     }else if( !p2 || (p1 && iDiff<0) ){
   118994       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   118995       fts3PoslistCopy(&p, &p1);
   118996       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   118997     }else{
   118998       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
   118999       fts3PoslistCopy(&p, &p2);
   119000       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   119001     }
   119002   }
   119003 
   119004   *paOut = aOut;
   119005   *pnOut = (int)(p-aOut);
   119006   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
   119007   return SQLITE_OK;
   119008 }
   119009 
   119010 /*
   119011 ** This function does a "phrase" merge of two doclists. In a phrase merge,
   119012 ** the output contains a copy of each position from the right-hand input
   119013 ** doclist for which there is a position in the left-hand input doclist
   119014 ** exactly nDist tokens before it.
   119015 **
   119016 ** If the docids in the input doclists are sorted in ascending order,
   119017 ** parameter bDescDoclist should be false. If they are sorted in ascending
   119018 ** order, it should be passed a non-zero value.
   119019 **
   119020 ** The right-hand input doclist is overwritten by this function.
   119021 */
   119022 static void fts3DoclistPhraseMerge(
   119023   int bDescDoclist,               /* True if arguments are desc */
   119024   int nDist,                      /* Distance from left to right (1=adjacent) */
   119025   char *aLeft, int nLeft,         /* Left doclist */
   119026   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
   119027 ){
   119028   sqlite3_int64 i1 = 0;
   119029   sqlite3_int64 i2 = 0;
   119030   sqlite3_int64 iPrev = 0;
   119031   char *pEnd1 = &aLeft[nLeft];
   119032   char *pEnd2 = &aRight[*pnRight];
   119033   char *p1 = aLeft;
   119034   char *p2 = aRight;
   119035   char *p;
   119036   int bFirstOut = 0;
   119037   char *aOut = aRight;
   119038 
   119039   assert( nDist>0 );
   119040 
   119041   p = aOut;
   119042   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   119043   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   119044 
   119045   while( p1 && p2 ){
   119046     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   119047     if( iDiff==0 ){
   119048       char *pSave = p;
   119049       sqlite3_int64 iPrevSave = iPrev;
   119050       int bFirstOutSave = bFirstOut;
   119051 
   119052       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   119053       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
   119054         p = pSave;
   119055         iPrev = iPrevSave;
   119056         bFirstOut = bFirstOutSave;
   119057       }
   119058       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   119059       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   119060     }else if( iDiff<0 ){
   119061       fts3PoslistCopy(0, &p1);
   119062       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   119063     }else{
   119064       fts3PoslistCopy(0, &p2);
   119065       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   119066     }
   119067   }
   119068 
   119069   *pnRight = (int)(p - aOut);
   119070 }
   119071 
   119072 /*
   119073 ** Argument pList points to a position list nList bytes in size. This
   119074 ** function checks to see if the position list contains any entries for
   119075 ** a token in position 0 (of any column). If so, it writes argument iDelta
   119076 ** to the output buffer pOut, followed by a position list consisting only
   119077 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
   119078 ** The value returned is the number of bytes written to pOut (if any).
   119079 */
   119080 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
   119081   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
   119082   char *pList,                    /* Position list (no 0x00 term) */
   119083   int nList,                      /* Size of pList in bytes */
   119084   char *pOut                      /* Write output here */
   119085 ){
   119086   int nOut = 0;
   119087   int bWritten = 0;               /* True once iDelta has been written */
   119088   char *p = pList;
   119089   char *pEnd = &pList[nList];
   119090 
   119091   if( *p!=0x01 ){
   119092     if( *p==0x02 ){
   119093       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   119094       pOut[nOut++] = 0x02;
   119095       bWritten = 1;
   119096     }
   119097     fts3ColumnlistCopy(0, &p);
   119098   }
   119099 
   119100   while( p<pEnd && *p==0x01 ){
   119101     sqlite3_int64 iCol;
   119102     p++;
   119103     p += sqlite3Fts3GetVarint(p, &iCol);
   119104     if( *p==0x02 ){
   119105       if( bWritten==0 ){
   119106         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   119107         bWritten = 1;
   119108       }
   119109       pOut[nOut++] = 0x01;
   119110       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
   119111       pOut[nOut++] = 0x02;
   119112     }
   119113     fts3ColumnlistCopy(0, &p);
   119114   }
   119115   if( bWritten ){
   119116     pOut[nOut++] = 0x00;
   119117   }
   119118 
   119119   return nOut;
   119120 }
   119121 
   119122 
   119123 /*
   119124 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   119125 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   119126 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   119127 **
   119128 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   119129 ** the responsibility of the caller to free any doclists left in the
   119130 ** TermSelect.aaOutput[] array.
   119131 */
   119132 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
   119133   char *aOut = 0;
   119134   int nOut = 0;
   119135   int i;
   119136 
   119137   /* Loop through the doclists in the aaOutput[] array. Merge them all
   119138   ** into a single doclist.
   119139   */
   119140   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   119141     if( pTS->aaOutput[i] ){
   119142       if( !aOut ){
   119143         aOut = pTS->aaOutput[i];
   119144         nOut = pTS->anOutput[i];
   119145         pTS->aaOutput[i] = 0;
   119146       }else{
   119147         int nNew;
   119148         char *aNew;
   119149 
   119150         int rc = fts3DoclistOrMerge(p->bDescIdx,
   119151             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
   119152         );
   119153         if( rc!=SQLITE_OK ){
   119154           sqlite3_free(aOut);
   119155           return rc;
   119156         }
   119157 
   119158         sqlite3_free(pTS->aaOutput[i]);
   119159         sqlite3_free(aOut);
   119160         pTS->aaOutput[i] = 0;
   119161         aOut = aNew;
   119162         nOut = nNew;
   119163       }
   119164     }
   119165   }
   119166 
   119167   pTS->aaOutput[0] = aOut;
   119168   pTS->anOutput[0] = nOut;
   119169   return SQLITE_OK;
   119170 }
   119171 
   119172 /*
   119173 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
   119174 ** as the first argument. The merge is an "OR" merge (see function
   119175 ** fts3DoclistOrMerge() for details).
   119176 **
   119177 ** This function is called with the doclist for each term that matches
   119178 ** a queried prefix. It merges all these doclists into one, the doclist
   119179 ** for the specified prefix. Since there can be a very large number of
   119180 ** doclists to merge, the merging is done pair-wise using the TermSelect
   119181 ** object.
   119182 **
   119183 ** This function returns SQLITE_OK if the merge is successful, or an
   119184 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
   119185 */
   119186 static int fts3TermSelectMerge(
   119187   Fts3Table *p,                   /* FTS table handle */
   119188   TermSelect *pTS,                /* TermSelect object to merge into */
   119189   char *aDoclist,                 /* Pointer to doclist */
   119190   int nDoclist                    /* Size of aDoclist in bytes */
   119191 ){
   119192   if( pTS->aaOutput[0]==0 ){
   119193     /* If this is the first term selected, copy the doclist to the output
   119194     ** buffer using memcpy(). */
   119195     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
   119196     pTS->anOutput[0] = nDoclist;
   119197     if( pTS->aaOutput[0] ){
   119198       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   119199     }else{
   119200       return SQLITE_NOMEM;
   119201     }
   119202   }else{
   119203     char *aMerge = aDoclist;
   119204     int nMerge = nDoclist;
   119205     int iOut;
   119206 
   119207     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   119208       if( pTS->aaOutput[iOut]==0 ){
   119209         assert( iOut>0 );
   119210         pTS->aaOutput[iOut] = aMerge;
   119211         pTS->anOutput[iOut] = nMerge;
   119212         break;
   119213       }else{
   119214         char *aNew;
   119215         int nNew;
   119216 
   119217         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
   119218             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
   119219         );
   119220         if( rc!=SQLITE_OK ){
   119221           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   119222           return rc;
   119223         }
   119224 
   119225         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   119226         sqlite3_free(pTS->aaOutput[iOut]);
   119227         pTS->aaOutput[iOut] = 0;
   119228 
   119229         aMerge = aNew;
   119230         nMerge = nNew;
   119231         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   119232           pTS->aaOutput[iOut] = aMerge;
   119233           pTS->anOutput[iOut] = nMerge;
   119234         }
   119235       }
   119236     }
   119237   }
   119238   return SQLITE_OK;
   119239 }
   119240 
   119241 /*
   119242 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
   119243 */
   119244 static int fts3SegReaderCursorAppend(
   119245   Fts3MultiSegReader *pCsr,
   119246   Fts3SegReader *pNew
   119247 ){
   119248   if( (pCsr->nSegment%16)==0 ){
   119249     Fts3SegReader **apNew;
   119250     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
   119251     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
   119252     if( !apNew ){
   119253       sqlite3Fts3SegReaderFree(pNew);
   119254       return SQLITE_NOMEM;
   119255     }
   119256     pCsr->apSegment = apNew;
   119257   }
   119258   pCsr->apSegment[pCsr->nSegment++] = pNew;
   119259   return SQLITE_OK;
   119260 }
   119261 
   119262 /*
   119263 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
   119264 ** 8th argument.
   119265 **
   119266 ** This function returns SQLITE_OK if successful, or an SQLite error code
   119267 ** otherwise.
   119268 */
   119269 static int fts3SegReaderCursor(
   119270   Fts3Table *p,                   /* FTS3 table handle */
   119271   int iLangid,                    /* Language id */
   119272   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   119273   int iLevel,                     /* Level of segments to scan */
   119274   const char *zTerm,              /* Term to query for */
   119275   int nTerm,                      /* Size of zTerm in bytes */
   119276   int isPrefix,                   /* True for a prefix search */
   119277   int isScan,                     /* True to scan from zTerm to EOF */
   119278   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   119279 ){
   119280   int rc = SQLITE_OK;             /* Error code */
   119281   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   119282   int rc2;                        /* Result of sqlite3_reset() */
   119283 
   119284   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   119285   ** for the pending-terms. If this is a scan, then this call must be being
   119286   ** made by an fts4aux module, not an FTS table. In this case calling
   119287   ** Fts3SegReaderPending might segfault, as the data structures used by
   119288   ** fts4aux are not completely populated. So it's easiest to filter these
   119289   ** calls out here.  */
   119290   if( iLevel<0 && p->aIndex ){
   119291     Fts3SegReader *pSeg = 0;
   119292     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
   119293     if( rc==SQLITE_OK && pSeg ){
   119294       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   119295     }
   119296   }
   119297 
   119298   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   119299     if( rc==SQLITE_OK ){
   119300       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
   119301     }
   119302 
   119303     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   119304       Fts3SegReader *pSeg = 0;
   119305 
   119306       /* Read the values returned by the SELECT into local variables. */
   119307       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
   119308       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
   119309       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
   119310       int nRoot = sqlite3_column_bytes(pStmt, 4);
   119311       char const *zRoot = sqlite3_column_blob(pStmt, 4);
   119312 
   119313       /* If zTerm is not NULL, and this segment is not stored entirely on its
   119314       ** root node, the range of leaves scanned can be reduced. Do this. */
   119315       if( iStartBlock && zTerm ){
   119316         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
   119317         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
   119318         if( rc!=SQLITE_OK ) goto finished;
   119319         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
   119320       }
   119321 
   119322       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
   119323           (isPrefix==0 && isScan==0),
   119324           iStartBlock, iLeavesEndBlock,
   119325           iEndBlock, zRoot, nRoot, &pSeg
   119326       );
   119327       if( rc!=SQLITE_OK ) goto finished;
   119328       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   119329     }
   119330   }
   119331 
   119332  finished:
   119333   rc2 = sqlite3_reset(pStmt);
   119334   if( rc==SQLITE_DONE ) rc = rc2;
   119335 
   119336   return rc;
   119337 }
   119338 
   119339 /*
   119340 ** Set up a cursor object for iterating through a full-text index or a
   119341 ** single level therein.
   119342 */
   119343 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
   119344   Fts3Table *p,                   /* FTS3 table handle */
   119345   int iLangid,
   119346   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   119347   int iLevel,                     /* Level of segments to scan */
   119348   const char *zTerm,              /* Term to query for */
   119349   int nTerm,                      /* Size of zTerm in bytes */
   119350   int isPrefix,                   /* True for a prefix search */
   119351   int isScan,                     /* True to scan from zTerm to EOF */
   119352   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
   119353 ){
   119354   assert( iIndex>=0 && iIndex<p->nIndex );
   119355   assert( iLevel==FTS3_SEGCURSOR_ALL
   119356       ||  iLevel==FTS3_SEGCURSOR_PENDING
   119357       ||  iLevel>=0
   119358   );
   119359   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   119360   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
   119361   assert( isPrefix==0 || isScan==0 );
   119362 
   119363   /* "isScan" is only set to true by the ft4aux module, an ordinary
   119364   ** full-text tables. */
   119365   assert( isScan==0 || p->aIndex==0 );
   119366 
   119367   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
   119368 
   119369   return fts3SegReaderCursor(
   119370       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
   119371   );
   119372 }
   119373 
   119374 /*
   119375 ** In addition to its current configuration, have the Fts3MultiSegReader
   119376 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
   119377 **
   119378 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   119379 */
   119380 static int fts3SegReaderCursorAddZero(
   119381   Fts3Table *p,                   /* FTS virtual table handle */
   119382   int iLangid,
   119383   const char *zTerm,              /* Term to scan doclist of */
   119384   int nTerm,                      /* Number of bytes in zTerm */
   119385   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
   119386 ){
   119387   return fts3SegReaderCursor(p,
   119388       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   119389   );
   119390 }
   119391 
   119392 /*
   119393 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
   119394 ** if isPrefix is true, to scan the doclist for all terms for which
   119395 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
   119396 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
   119397 ** an SQLite error code.
   119398 **
   119399 ** It is the responsibility of the caller to free this object by eventually
   119400 ** passing it to fts3SegReaderCursorFree()
   119401 **
   119402 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   119403 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
   119404 */
   119405 static int fts3TermSegReaderCursor(
   119406   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   119407   const char *zTerm,              /* Term to query for */
   119408   int nTerm,                      /* Size of zTerm in bytes */
   119409   int isPrefix,                   /* True for a prefix search */
   119410   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
   119411 ){
   119412   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
   119413   int rc = SQLITE_NOMEM;          /* Return code */
   119414 
   119415   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
   119416   if( pSegcsr ){
   119417     int i;
   119418     int bFound = 0;               /* True once an index has been found */
   119419     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   119420 
   119421     if( isPrefix ){
   119422       for(i=1; bFound==0 && i<p->nIndex; i++){
   119423         if( p->aIndex[i].nPrefix==nTerm ){
   119424           bFound = 1;
   119425           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119426               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
   119427           );
   119428           pSegcsr->bLookup = 1;
   119429         }
   119430       }
   119431 
   119432       for(i=1; bFound==0 && i<p->nIndex; i++){
   119433         if( p->aIndex[i].nPrefix==nTerm+1 ){
   119434           bFound = 1;
   119435           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119436               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
   119437           );
   119438           if( rc==SQLITE_OK ){
   119439             rc = fts3SegReaderCursorAddZero(
   119440                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
   119441             );
   119442           }
   119443         }
   119444       }
   119445     }
   119446 
   119447     if( bFound==0 ){
   119448       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119449           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
   119450       );
   119451       pSegcsr->bLookup = !isPrefix;
   119452     }
   119453   }
   119454 
   119455   *ppSegcsr = pSegcsr;
   119456   return rc;
   119457 }
   119458 
   119459 /*
   119460 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
   119461 */
   119462 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
   119463   sqlite3Fts3SegReaderFinish(pSegcsr);
   119464   sqlite3_free(pSegcsr);
   119465 }
   119466 
   119467 /*
   119468 ** This function retreives the doclist for the specified term (or term
   119469 ** prefix) from the database.
   119470 */
   119471 static int fts3TermSelect(
   119472   Fts3Table *p,                   /* Virtual table handle */
   119473   Fts3PhraseToken *pTok,          /* Token to query for */
   119474   int iColumn,                    /* Column to query (or -ve for all columns) */
   119475   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   119476   char **ppOut                    /* OUT: Malloced result buffer */
   119477 ){
   119478   int rc;                         /* Return code */
   119479   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
   119480   TermSelect tsc;                 /* Object for pair-wise doclist merging */
   119481   Fts3SegFilter filter;           /* Segment term filter configuration */
   119482 
   119483   pSegcsr = pTok->pSegcsr;
   119484   memset(&tsc, 0, sizeof(TermSelect));
   119485 
   119486   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
   119487         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   119488         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
   119489         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   119490   filter.iCol = iColumn;
   119491   filter.zTerm = pTok->z;
   119492   filter.nTerm = pTok->n;
   119493 
   119494   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   119495   while( SQLITE_OK==rc
   119496       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   119497   ){
   119498     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   119499   }
   119500 
   119501   if( rc==SQLITE_OK ){
   119502     rc = fts3TermSelectFinishMerge(p, &tsc);
   119503   }
   119504   if( rc==SQLITE_OK ){
   119505     *ppOut = tsc.aaOutput[0];
   119506     *pnOut = tsc.anOutput[0];
   119507   }else{
   119508     int i;
   119509     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   119510       sqlite3_free(tsc.aaOutput[i]);
   119511     }
   119512   }
   119513 
   119514   fts3SegReaderCursorFree(pSegcsr);
   119515   pTok->pSegcsr = 0;
   119516   return rc;
   119517 }
   119518 
   119519 /*
   119520 ** This function counts the total number of docids in the doclist stored
   119521 ** in buffer aList[], size nList bytes.
   119522 **
   119523 ** If the isPoslist argument is true, then it is assumed that the doclist
   119524 ** contains a position-list following each docid. Otherwise, it is assumed
   119525 ** that the doclist is simply a list of docids stored as delta encoded
   119526 ** varints.
   119527 */
   119528 static int fts3DoclistCountDocids(char *aList, int nList){
   119529   int nDoc = 0;                   /* Return value */
   119530   if( aList ){
   119531     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   119532     char *p = aList;              /* Cursor */
   119533     while( p<aEnd ){
   119534       nDoc++;
   119535       while( (*p++)&0x80 );     /* Skip docid varint */
   119536       fts3PoslistCopy(0, &p);   /* Skip over position list */
   119537     }
   119538   }
   119539 
   119540   return nDoc;
   119541 }
   119542 
   119543 /*
   119544 ** Advance the cursor to the next row in the %_content table that
   119545 ** matches the search criteria.  For a MATCH search, this will be
   119546 ** the next row that matches. For a full-table scan, this will be
   119547 ** simply the next row in the %_content table.  For a docid lookup,
   119548 ** this routine simply sets the EOF flag.
   119549 **
   119550 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   119551 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   119552 ** subsequently to determine whether or not an EOF was hit.
   119553 */
   119554 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   119555   int rc;
   119556   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   119557   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
   119558     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   119559       pCsr->isEof = 1;
   119560       rc = sqlite3_reset(pCsr->pStmt);
   119561     }else{
   119562       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   119563       rc = SQLITE_OK;
   119564     }
   119565   }else{
   119566     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   119567   }
   119568   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   119569   return rc;
   119570 }
   119571 
   119572 /*
   119573 ** This is the xFilter interface for the virtual table.  See
   119574 ** the virtual table xFilter method documentation for additional
   119575 ** information.
   119576 **
   119577 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   119578 ** the %_content table.
   119579 **
   119580 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   119581 ** in the %_content table.
   119582 **
   119583 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   119584 ** column on the left-hand side of the MATCH operator is column
   119585 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   119586 ** side of the MATCH operator.
   119587 */
   119588 static int fts3FilterMethod(
   119589   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   119590   int idxNum,                     /* Strategy index */
   119591   const char *idxStr,             /* Unused */
   119592   int nVal,                       /* Number of elements in apVal */
   119593   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   119594 ){
   119595   int rc;
   119596   char *zSql;                     /* SQL statement used to access %_content */
   119597   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   119598   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   119599 
   119600   UNUSED_PARAMETER(idxStr);
   119601   UNUSED_PARAMETER(nVal);
   119602 
   119603   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   119604   assert( nVal==0 || nVal==1 || nVal==2 );
   119605   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
   119606   assert( p->pSegments==0 );
   119607 
   119608   /* In case the cursor has been used before, clear it now. */
   119609   sqlite3_finalize(pCsr->pStmt);
   119610   sqlite3_free(pCsr->aDoclist);
   119611   sqlite3Fts3ExprFree(pCsr->pExpr);
   119612   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   119613 
   119614   if( idxStr ){
   119615     pCsr->bDesc = (idxStr[0]=='D');
   119616   }else{
   119617     pCsr->bDesc = p->bDescIdx;
   119618   }
   119619   pCsr->eSearch = (i16)idxNum;
   119620 
   119621   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
   119622     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
   119623     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
   119624 
   119625     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   119626       return SQLITE_NOMEM;
   119627     }
   119628 
   119629     pCsr->iLangid = 0;
   119630     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
   119631 
   119632     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
   119633         p->azColumn, p->bHasStat, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
   119634     );
   119635     if( rc!=SQLITE_OK ){
   119636       if( rc==SQLITE_ERROR ){
   119637         static const char *zErr = "malformed MATCH expression: [%s]";
   119638         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
   119639       }
   119640       return rc;
   119641     }
   119642 
   119643     rc = sqlite3Fts3ReadLock(p);
   119644     if( rc!=SQLITE_OK ) return rc;
   119645 
   119646     rc = fts3EvalStart(pCsr);
   119647 
   119648     sqlite3Fts3SegmentsClose(p);
   119649     if( rc!=SQLITE_OK ) return rc;
   119650     pCsr->pNextId = pCsr->aDoclist;
   119651     pCsr->iPrevId = 0;
   119652   }
   119653 
   119654   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   119655   ** statement loops through all rows of the %_content table. For a
   119656   ** full-text query or docid lookup, the statement retrieves a single
   119657   ** row by docid.
   119658   */
   119659   if( idxNum==FTS3_FULLSCAN_SEARCH ){
   119660     zSql = sqlite3_mprintf(
   119661         "SELECT %s ORDER BY rowid %s",
   119662         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
   119663     );
   119664     if( zSql ){
   119665       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   119666       sqlite3_free(zSql);
   119667     }else{
   119668       rc = SQLITE_NOMEM;
   119669     }
   119670   }else if( idxNum==FTS3_DOCID_SEARCH ){
   119671     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
   119672     if( rc==SQLITE_OK ){
   119673       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
   119674     }
   119675   }
   119676   if( rc!=SQLITE_OK ) return rc;
   119677 
   119678   return fts3NextMethod(pCursor);
   119679 }
   119680 
   119681 /*
   119682 ** This is the xEof method of the virtual table. SQLite calls this
   119683 ** routine to find out if it has reached the end of a result set.
   119684 */
   119685 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   119686   return ((Fts3Cursor *)pCursor)->isEof;
   119687 }
   119688 
   119689 /*
   119690 ** This is the xRowid method. The SQLite core calls this routine to
   119691 ** retrieve the rowid for the current row of the result set. fts3
   119692 ** exposes %_content.docid as the rowid for the virtual table. The
   119693 ** rowid should be written to *pRowid.
   119694 */
   119695 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   119696   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   119697   *pRowid = pCsr->iPrevId;
   119698   return SQLITE_OK;
   119699 }
   119700 
   119701 /*
   119702 ** This is the xColumn method, called by SQLite to request a value from
   119703 ** the row that the supplied cursor currently points to.
   119704 **
   119705 ** If:
   119706 **
   119707 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
   119708 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
   119709 **   (iCol == p->nColumn+1) -> Docid column
   119710 **   (iCol == p->nColumn+2) -> Langid column
   119711 */
   119712 static int fts3ColumnMethod(
   119713   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   119714   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   119715   int iCol                        /* Index of column to read value from */
   119716 ){
   119717   int rc = SQLITE_OK;             /* Return Code */
   119718   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   119719   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   119720 
   119721   /* The column value supplied by SQLite must be in range. */
   119722   assert( iCol>=0 && iCol<=p->nColumn+2 );
   119723 
   119724   if( iCol==p->nColumn+1 ){
   119725     /* This call is a request for the "docid" column. Since "docid" is an
   119726     ** alias for "rowid", use the xRowid() method to obtain the value.
   119727     */
   119728     sqlite3_result_int64(pCtx, pCsr->iPrevId);
   119729   }else if( iCol==p->nColumn ){
   119730     /* The extra column whose name is the same as the table.
   119731     ** Return a blob which is a pointer to the cursor.  */
   119732     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   119733   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
   119734     sqlite3_result_int64(pCtx, pCsr->iLangid);
   119735   }else{
   119736     /* The requested column is either a user column (one that contains
   119737     ** indexed data), or the language-id column.  */
   119738     rc = fts3CursorSeek(0, pCsr);
   119739 
   119740     if( rc==SQLITE_OK ){
   119741       if( iCol==p->nColumn+2 ){
   119742         int iLangid = 0;
   119743         if( p->zLanguageid ){
   119744           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
   119745         }
   119746         sqlite3_result_int(pCtx, iLangid);
   119747       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
   119748         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   119749       }
   119750     }
   119751   }
   119752 
   119753   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   119754   return rc;
   119755 }
   119756 
   119757 /*
   119758 ** This function is the implementation of the xUpdate callback used by
   119759 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   119760 ** inserted, updated or deleted.
   119761 */
   119762 static int fts3UpdateMethod(
   119763   sqlite3_vtab *pVtab,            /* Virtual table handle */
   119764   int nArg,                       /* Size of argument array */
   119765   sqlite3_value **apVal,          /* Array of arguments */
   119766   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   119767 ){
   119768   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   119769 }
   119770 
   119771 /*
   119772 ** Implementation of xSync() method. Flush the contents of the pending-terms
   119773 ** hash-table to the database.
   119774 */
   119775 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   119776   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
   119777   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
   119778   return rc;
   119779 }
   119780 
   119781 /*
   119782 ** Implementation of xBegin() method. This is a no-op.
   119783 */
   119784 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   119785   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   119786   UNUSED_PARAMETER(pVtab);
   119787   assert( p->pSegments==0 );
   119788   assert( p->nPendingData==0 );
   119789   assert( p->inTransaction!=1 );
   119790   TESTONLY( p->inTransaction = 1 );
   119791   TESTONLY( p->mxSavepoint = -1; );
   119792   return SQLITE_OK;
   119793 }
   119794 
   119795 /*
   119796 ** Implementation of xCommit() method. This is a no-op. The contents of
   119797 ** the pending-terms hash-table have already been flushed into the database
   119798 ** by fts3SyncMethod().
   119799 */
   119800 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   119801   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   119802   UNUSED_PARAMETER(pVtab);
   119803   assert( p->nPendingData==0 );
   119804   assert( p->inTransaction!=0 );
   119805   assert( p->pSegments==0 );
   119806   TESTONLY( p->inTransaction = 0 );
   119807   TESTONLY( p->mxSavepoint = -1; );
   119808   return SQLITE_OK;
   119809 }
   119810 
   119811 /*
   119812 ** Implementation of xRollback(). Discard the contents of the pending-terms
   119813 ** hash-table. Any changes made to the database are reverted by SQLite.
   119814 */
   119815 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   119816   Fts3Table *p = (Fts3Table*)pVtab;
   119817   sqlite3Fts3PendingTermsClear(p);
   119818   assert( p->inTransaction!=0 );
   119819   TESTONLY( p->inTransaction = 0 );
   119820   TESTONLY( p->mxSavepoint = -1; );
   119821   return SQLITE_OK;
   119822 }
   119823 
   119824 /*
   119825 ** When called, *ppPoslist must point to the byte immediately following the
   119826 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
   119827 ** moves *ppPoslist so that it instead points to the first byte of the
   119828 ** same position list.
   119829 */
   119830 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   119831   char *p = &(*ppPoslist)[-2];
   119832   char c = 0;
   119833 
   119834   while( p>pStart && (c=*p--)==0 );
   119835   while( p>pStart && (*p & 0x80) | c ){
   119836     c = *p--;
   119837   }
   119838   if( p>pStart ){ p = &p[2]; }
   119839   while( *p++&0x80 );
   119840   *ppPoslist = p;
   119841 }
   119842 
   119843 /*
   119844 ** Helper function used by the implementation of the overloaded snippet(),
   119845 ** offsets() and optimize() SQL functions.
   119846 **
   119847 ** If the value passed as the third argument is a blob of size
   119848 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   119849 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   119850 ** message is written to context pContext and SQLITE_ERROR returned. The
   119851 ** string passed via zFunc is used as part of the error message.
   119852 */
   119853 static int fts3FunctionArg(
   119854   sqlite3_context *pContext,      /* SQL function call context */
   119855   const char *zFunc,              /* Function name */
   119856   sqlite3_value *pVal,            /* argv[0] passed to function */
   119857   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   119858 ){
   119859   Fts3Cursor *pRet;
   119860   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   119861    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   119862   ){
   119863     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   119864     sqlite3_result_error(pContext, zErr, -1);
   119865     sqlite3_free(zErr);
   119866     return SQLITE_ERROR;
   119867   }
   119868   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   119869   *ppCsr = pRet;
   119870   return SQLITE_OK;
   119871 }
   119872 
   119873 /*
   119874 ** Implementation of the snippet() function for FTS3
   119875 */
   119876 static void fts3SnippetFunc(
   119877   sqlite3_context *pContext,      /* SQLite function call context */
   119878   int nVal,                       /* Size of apVal[] array */
   119879   sqlite3_value **apVal           /* Array of arguments */
   119880 ){
   119881   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119882   const char *zStart = "<b>";
   119883   const char *zEnd = "</b>";
   119884   const char *zEllipsis = "<b>...</b>";
   119885   int iCol = -1;
   119886   int nToken = 15;                /* Default number of tokens in snippet */
   119887 
   119888   /* There must be at least one argument passed to this function (otherwise
   119889   ** the non-overloaded version would have been called instead of this one).
   119890   */
   119891   assert( nVal>=1 );
   119892 
   119893   if( nVal>6 ){
   119894     sqlite3_result_error(pContext,
   119895         "wrong number of arguments to function snippet()", -1);
   119896     return;
   119897   }
   119898   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   119899 
   119900   switch( nVal ){
   119901     case 6: nToken = sqlite3_value_int(apVal[5]);
   119902     case 5: iCol = sqlite3_value_int(apVal[4]);
   119903     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   119904     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   119905     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   119906   }
   119907   if( !zEllipsis || !zEnd || !zStart ){
   119908     sqlite3_result_error_nomem(pContext);
   119909   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   119910     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   119911   }
   119912 }
   119913 
   119914 /*
   119915 ** Implementation of the offsets() function for FTS3
   119916 */
   119917 static void fts3OffsetsFunc(
   119918   sqlite3_context *pContext,      /* SQLite function call context */
   119919   int nVal,                       /* Size of argument array */
   119920   sqlite3_value **apVal           /* Array of arguments */
   119921 ){
   119922   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119923 
   119924   UNUSED_PARAMETER(nVal);
   119925 
   119926   assert( nVal==1 );
   119927   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   119928   assert( pCsr );
   119929   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   119930     sqlite3Fts3Offsets(pContext, pCsr);
   119931   }
   119932 }
   119933 
   119934 /*
   119935 ** Implementation of the special optimize() function for FTS3. This
   119936 ** function merges all segments in the database to a single segment.
   119937 ** Example usage is:
   119938 **
   119939 **   SELECT optimize(t) FROM t LIMIT 1;
   119940 **
   119941 ** where 't' is the name of an FTS3 table.
   119942 */
   119943 static void fts3OptimizeFunc(
   119944   sqlite3_context *pContext,      /* SQLite function call context */
   119945   int nVal,                       /* Size of argument array */
   119946   sqlite3_value **apVal           /* Array of arguments */
   119947 ){
   119948   int rc;                         /* Return code */
   119949   Fts3Table *p;                   /* Virtual table handle */
   119950   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   119951 
   119952   UNUSED_PARAMETER(nVal);
   119953 
   119954   assert( nVal==1 );
   119955   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   119956   p = (Fts3Table *)pCursor->base.pVtab;
   119957   assert( p );
   119958 
   119959   rc = sqlite3Fts3Optimize(p);
   119960 
   119961   switch( rc ){
   119962     case SQLITE_OK:
   119963       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   119964       break;
   119965     case SQLITE_DONE:
   119966       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   119967       break;
   119968     default:
   119969       sqlite3_result_error_code(pContext, rc);
   119970       break;
   119971   }
   119972 }
   119973 
   119974 /*
   119975 ** Implementation of the matchinfo() function for FTS3
   119976 */
   119977 static void fts3MatchinfoFunc(
   119978   sqlite3_context *pContext,      /* SQLite function call context */
   119979   int nVal,                       /* Size of argument array */
   119980   sqlite3_value **apVal           /* Array of arguments */
   119981 ){
   119982   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119983   assert( nVal==1 || nVal==2 );
   119984   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   119985     const char *zArg = 0;
   119986     if( nVal>1 ){
   119987       zArg = (const char *)sqlite3_value_text(apVal[1]);
   119988     }
   119989     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   119990   }
   119991 }
   119992 
   119993 /*
   119994 ** This routine implements the xFindFunction method for the FTS3
   119995 ** virtual table.
   119996 */
   119997 static int fts3FindFunctionMethod(
   119998   sqlite3_vtab *pVtab,            /* Virtual table handle */
   119999   int nArg,                       /* Number of SQL function arguments */
   120000   const char *zName,              /* Name of SQL function */
   120001   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   120002   void **ppArg                    /* Unused */
   120003 ){
   120004   struct Overloaded {
   120005     const char *zName;
   120006     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   120007   } aOverload[] = {
   120008     { "snippet", fts3SnippetFunc },
   120009     { "offsets", fts3OffsetsFunc },
   120010     { "optimize", fts3OptimizeFunc },
   120011     { "matchinfo", fts3MatchinfoFunc },
   120012   };
   120013   int i;                          /* Iterator variable */
   120014 
   120015   UNUSED_PARAMETER(pVtab);
   120016   UNUSED_PARAMETER(nArg);
   120017   UNUSED_PARAMETER(ppArg);
   120018 
   120019   for(i=0; i<SizeofArray(aOverload); i++){
   120020     if( strcmp(zName, aOverload[i].zName)==0 ){
   120021       *pxFunc = aOverload[i].xFunc;
   120022       return 1;
   120023     }
   120024   }
   120025 
   120026   /* No function of the specified name was found. Return 0. */
   120027   return 0;
   120028 }
   120029 
   120030 /*
   120031 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   120032 */
   120033 static int fts3RenameMethod(
   120034   sqlite3_vtab *pVtab,            /* Virtual table handle */
   120035   const char *zName               /* New name of table */
   120036 ){
   120037   Fts3Table *p = (Fts3Table *)pVtab;
   120038   sqlite3 *db = p->db;            /* Database connection */
   120039   int rc;                         /* Return Code */
   120040 
   120041   /* As it happens, the pending terms table is always empty here. This is
   120042   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
   120043   ** always opens a savepoint transaction. And the xSavepoint() method
   120044   ** flushes the pending terms table. But leave the (no-op) call to
   120045   ** PendingTermsFlush() in in case that changes.
   120046   */
   120047   assert( p->nPendingData==0 );
   120048   rc = sqlite3Fts3PendingTermsFlush(p);
   120049 
   120050   if( p->zContentTbl==0 ){
   120051     fts3DbExec(&rc, db,
   120052       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   120053       p->zDb, p->zName, zName
   120054     );
   120055   }
   120056 
   120057   if( p->bHasDocsize ){
   120058     fts3DbExec(&rc, db,
   120059       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   120060       p->zDb, p->zName, zName
   120061     );
   120062   }
   120063   if( p->bHasStat ){
   120064     fts3DbExec(&rc, db,
   120065       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   120066       p->zDb, p->zName, zName
   120067     );
   120068   }
   120069   fts3DbExec(&rc, db,
   120070     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   120071     p->zDb, p->zName, zName
   120072   );
   120073   fts3DbExec(&rc, db,
   120074     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   120075     p->zDb, p->zName, zName
   120076   );
   120077   return rc;
   120078 }
   120079 
   120080 /*
   120081 ** The xSavepoint() method.
   120082 **
   120083 ** Flush the contents of the pending-terms table to disk.
   120084 */
   120085 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120086   UNUSED_PARAMETER(iSavepoint);
   120087   assert( ((Fts3Table *)pVtab)->inTransaction );
   120088   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
   120089   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
   120090   return fts3SyncMethod(pVtab);
   120091 }
   120092 
   120093 /*
   120094 ** The xRelease() method.
   120095 **
   120096 ** This is a no-op.
   120097 */
   120098 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120099   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   120100   UNUSED_PARAMETER(iSavepoint);
   120101   UNUSED_PARAMETER(pVtab);
   120102   assert( p->inTransaction );
   120103   assert( p->mxSavepoint >= iSavepoint );
   120104   TESTONLY( p->mxSavepoint = iSavepoint-1 );
   120105   return SQLITE_OK;
   120106 }
   120107 
   120108 /*
   120109 ** The xRollbackTo() method.
   120110 **
   120111 ** Discard the contents of the pending terms table.
   120112 */
   120113 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120114   Fts3Table *p = (Fts3Table*)pVtab;
   120115   UNUSED_PARAMETER(iSavepoint);
   120116   assert( p->inTransaction );
   120117   assert( p->mxSavepoint >= iSavepoint );
   120118   TESTONLY( p->mxSavepoint = iSavepoint );
   120119   sqlite3Fts3PendingTermsClear(p);
   120120   return SQLITE_OK;
   120121 }
   120122 
   120123 static const sqlite3_module fts3Module = {
   120124   /* iVersion      */ 2,
   120125   /* xCreate       */ fts3CreateMethod,
   120126   /* xConnect      */ fts3ConnectMethod,
   120127   /* xBestIndex    */ fts3BestIndexMethod,
   120128   /* xDisconnect   */ fts3DisconnectMethod,
   120129   /* xDestroy      */ fts3DestroyMethod,
   120130   /* xOpen         */ fts3OpenMethod,
   120131   /* xClose        */ fts3CloseMethod,
   120132   /* xFilter       */ fts3FilterMethod,
   120133   /* xNext         */ fts3NextMethod,
   120134   /* xEof          */ fts3EofMethod,
   120135   /* xColumn       */ fts3ColumnMethod,
   120136   /* xRowid        */ fts3RowidMethod,
   120137   /* xUpdate       */ fts3UpdateMethod,
   120138   /* xBegin        */ fts3BeginMethod,
   120139   /* xSync         */ fts3SyncMethod,
   120140   /* xCommit       */ fts3CommitMethod,
   120141   /* xRollback     */ fts3RollbackMethod,
   120142   /* xFindFunction */ fts3FindFunctionMethod,
   120143   /* xRename */       fts3RenameMethod,
   120144   /* xSavepoint    */ fts3SavepointMethod,
   120145   /* xRelease      */ fts3ReleaseMethod,
   120146   /* xRollbackTo   */ fts3RollbackToMethod,
   120147 };
   120148 
   120149 /*
   120150 ** This function is registered as the module destructor (called when an
   120151 ** FTS3 enabled database connection is closed). It frees the memory
   120152 ** allocated for the tokenizer hash table.
   120153 */
   120154 static void hashDestroy(void *p){
   120155   Fts3Hash *pHash = (Fts3Hash *)p;
   120156   sqlite3Fts3HashClear(pHash);
   120157   sqlite3_free(pHash);
   120158 }
   120159 
   120160 /*
   120161 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   120162 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   120163 ** respectively. The following three forward declarations are for functions
   120164 ** declared in these files used to retrieve the respective implementations.
   120165 **
   120166 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   120167 ** to by the argument to point to the "simple" tokenizer implementation.
   120168 ** And so on.
   120169 */
   120170 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120171 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120172 #ifdef SQLITE_ENABLE_ICU
   120173 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120174 #endif
   120175 
   120176 /*
   120177 ** Initialise the fts3 extension. If this extension is built as part
   120178 ** of the sqlite library, then this function is called directly by
   120179 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   120180 ** function is called by the sqlite3_extension_init() entry point.
   120181 */
   120182 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   120183   int rc = SQLITE_OK;
   120184   Fts3Hash *pHash = 0;
   120185   const sqlite3_tokenizer_module *pSimple = 0;
   120186   const sqlite3_tokenizer_module *pPorter = 0;
   120187 
   120188 #ifdef SQLITE_ENABLE_ICU
   120189   const sqlite3_tokenizer_module *pIcu = 0;
   120190   sqlite3Fts3IcuTokenizerModule(&pIcu);
   120191 #endif
   120192 
   120193 #ifdef SQLITE_TEST
   120194   rc = sqlite3Fts3InitTerm(db);
   120195   if( rc!=SQLITE_OK ) return rc;
   120196 #endif
   120197 
   120198   rc = sqlite3Fts3InitAux(db);
   120199   if( rc!=SQLITE_OK ) return rc;
   120200 
   120201   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   120202   sqlite3Fts3PorterTokenizerModule(&pPorter);
   120203 
   120204   /* Allocate and initialise the hash-table used to store tokenizers. */
   120205   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   120206   if( !pHash ){
   120207     rc = SQLITE_NOMEM;
   120208   }else{
   120209     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   120210   }
   120211 
   120212   /* Load the built-in tokenizers into the hash table */
   120213   if( rc==SQLITE_OK ){
   120214     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   120215      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   120216 #ifdef SQLITE_ENABLE_ICU
   120217      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   120218 #endif
   120219     ){
   120220       rc = SQLITE_NOMEM;
   120221     }
   120222   }
   120223 
   120224 #ifdef SQLITE_TEST
   120225   if( rc==SQLITE_OK ){
   120226     rc = sqlite3Fts3ExprInitTestInterface(db);
   120227   }
   120228 #endif
   120229 
   120230   /* Create the virtual table wrapper around the hash-table and overload
   120231   ** the two scalar functions. If this is successful, register the
   120232   ** module with sqlite.
   120233   */
   120234   if( SQLITE_OK==rc
   120235    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   120236    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   120237    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   120238    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   120239    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   120240    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   120241   ){
   120242 #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
   120243     rc = sqlite3_create_module_v2(
   120244         db, "fts1", &fts3Module, (void *)pHash, 0
   120245         );
   120246     if(rc) return rc;
   120247     rc = sqlite3_create_module_v2(
   120248         db, "fts2", &fts3Module, (void *)pHash, 0
   120249         );
   120250     if(rc) return rc;
   120251 #endif
   120252     rc = sqlite3_create_module_v2(
   120253         db, "fts3", &fts3Module, (void *)pHash, 0
   120254         );
   120255     if( rc==SQLITE_OK ){
   120256       rc = sqlite3_create_module_v2(
   120257           db, "fts4", &fts3Module, (void *)pHash, 0
   120258       );
   120259     }
   120260     return rc;
   120261   }
   120262 
   120263   /* An error has occurred. Delete the hash table and return the error code. */
   120264   assert( rc!=SQLITE_OK );
   120265   if( pHash ){
   120266     sqlite3Fts3HashClear(pHash);
   120267     sqlite3_free(pHash);
   120268   }
   120269   return rc;
   120270 }
   120271 
   120272 /*
   120273 ** Allocate an Fts3MultiSegReader for each token in the expression headed
   120274 ** by pExpr.
   120275 **
   120276 ** An Fts3SegReader object is a cursor that can seek or scan a range of
   120277 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
   120278 ** Fts3SegReader objects internally to provide an interface to seek or scan
   120279 ** within the union of all segments of a b-tree. Hence the name.
   120280 **
   120281 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
   120282 ** segment b-tree (if the term is not a prefix or it is a prefix for which
   120283 ** there exists prefix b-tree of the right length) then it may be traversed
   120284 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
   120285 ** doclist and then traversed.
   120286 */
   120287 static void fts3EvalAllocateReaders(
   120288   Fts3Cursor *pCsr,               /* FTS cursor handle */
   120289   Fts3Expr *pExpr,                /* Allocate readers for this expression */
   120290   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
   120291   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
   120292   int *pRc                        /* IN/OUT: Error code */
   120293 ){
   120294   if( pExpr && SQLITE_OK==*pRc ){
   120295     if( pExpr->eType==FTSQUERY_PHRASE ){
   120296       int i;
   120297       int nToken = pExpr->pPhrase->nToken;
   120298       *pnToken += nToken;
   120299       for(i=0; i<nToken; i++){
   120300         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   120301         int rc = fts3TermSegReaderCursor(pCsr,
   120302             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
   120303         );
   120304         if( rc!=SQLITE_OK ){
   120305           *pRc = rc;
   120306           return;
   120307         }
   120308       }
   120309       assert( pExpr->pPhrase->iDoclistToken==0 );
   120310       pExpr->pPhrase->iDoclistToken = -1;
   120311     }else{
   120312       *pnOr += (pExpr->eType==FTSQUERY_OR);
   120313       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
   120314       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
   120315     }
   120316   }
   120317 }
   120318 
   120319 /*
   120320 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
   120321 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
   120322 **
   120323 ** This function assumes that pList points to a buffer allocated using
   120324 ** sqlite3_malloc(). This function takes responsibility for eventually
   120325 ** freeing the buffer.
   120326 */
   120327 static void fts3EvalPhraseMergeToken(
   120328   Fts3Table *pTab,                /* FTS Table pointer */
   120329   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
   120330   int iToken,                     /* Token pList/nList corresponds to */
   120331   char *pList,                    /* Pointer to doclist */
   120332   int nList                       /* Number of bytes in pList */
   120333 ){
   120334   assert( iToken!=p->iDoclistToken );
   120335 
   120336   if( pList==0 ){
   120337     sqlite3_free(p->doclist.aAll);
   120338     p->doclist.aAll = 0;
   120339     p->doclist.nAll = 0;
   120340   }
   120341 
   120342   else if( p->iDoclistToken<0 ){
   120343     p->doclist.aAll = pList;
   120344     p->doclist.nAll = nList;
   120345   }
   120346 
   120347   else if( p->doclist.aAll==0 ){
   120348     sqlite3_free(pList);
   120349   }
   120350 
   120351   else {
   120352     char *pLeft;
   120353     char *pRight;
   120354     int nLeft;
   120355     int nRight;
   120356     int nDiff;
   120357 
   120358     if( p->iDoclistToken<iToken ){
   120359       pLeft = p->doclist.aAll;
   120360       nLeft = p->doclist.nAll;
   120361       pRight = pList;
   120362       nRight = nList;
   120363       nDiff = iToken - p->iDoclistToken;
   120364     }else{
   120365       pRight = p->doclist.aAll;
   120366       nRight = p->doclist.nAll;
   120367       pLeft = pList;
   120368       nLeft = nList;
   120369       nDiff = p->iDoclistToken - iToken;
   120370     }
   120371 
   120372     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
   120373     sqlite3_free(pLeft);
   120374     p->doclist.aAll = pRight;
   120375     p->doclist.nAll = nRight;
   120376   }
   120377 
   120378   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
   120379 }
   120380 
   120381 /*
   120382 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
   120383 ** does not take deferred tokens into account.
   120384 **
   120385 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120386 */
   120387 static int fts3EvalPhraseLoad(
   120388   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120389   Fts3Phrase *p                   /* Phrase object */
   120390 ){
   120391   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120392   int iToken;
   120393   int rc = SQLITE_OK;
   120394 
   120395   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
   120396     Fts3PhraseToken *pToken = &p->aToken[iToken];
   120397     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
   120398 
   120399     if( pToken->pSegcsr ){
   120400       int nThis = 0;
   120401       char *pThis = 0;
   120402       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
   120403       if( rc==SQLITE_OK ){
   120404         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
   120405       }
   120406     }
   120407     assert( pToken->pSegcsr==0 );
   120408   }
   120409 
   120410   return rc;
   120411 }
   120412 
   120413 /*
   120414 ** This function is called on each phrase after the position lists for
   120415 ** any deferred tokens have been loaded into memory. It updates the phrases
   120416 ** current position list to include only those positions that are really
   120417 ** instances of the phrase (after considering deferred tokens). If this
   120418 ** means that the phrase does not appear in the current row, doclist.pList
   120419 ** and doclist.nList are both zeroed.
   120420 **
   120421 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120422 */
   120423 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
   120424   int iToken;                     /* Used to iterate through phrase tokens */
   120425   char *aPoslist = 0;             /* Position list for deferred tokens */
   120426   int nPoslist = 0;               /* Number of bytes in aPoslist */
   120427   int iPrev = -1;                 /* Token number of previous deferred token */
   120428 
   120429   assert( pPhrase->doclist.bFreeList==0 );
   120430 
   120431   for(iToken=0; iToken<pPhrase->nToken; iToken++){
   120432     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   120433     Fts3DeferredToken *pDeferred = pToken->pDeferred;
   120434 
   120435     if( pDeferred ){
   120436       char *pList;
   120437       int nList;
   120438       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
   120439       if( rc!=SQLITE_OK ) return rc;
   120440 
   120441       if( pList==0 ){
   120442         sqlite3_free(aPoslist);
   120443         pPhrase->doclist.pList = 0;
   120444         pPhrase->doclist.nList = 0;
   120445         return SQLITE_OK;
   120446 
   120447       }else if( aPoslist==0 ){
   120448         aPoslist = pList;
   120449         nPoslist = nList;
   120450 
   120451       }else{
   120452         char *aOut = pList;
   120453         char *p1 = aPoslist;
   120454         char *p2 = aOut;
   120455 
   120456         assert( iPrev>=0 );
   120457         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
   120458         sqlite3_free(aPoslist);
   120459         aPoslist = pList;
   120460         nPoslist = (int)(aOut - aPoslist);
   120461         if( nPoslist==0 ){
   120462           sqlite3_free(aPoslist);
   120463           pPhrase->doclist.pList = 0;
   120464           pPhrase->doclist.nList = 0;
   120465           return SQLITE_OK;
   120466         }
   120467       }
   120468       iPrev = iToken;
   120469     }
   120470   }
   120471 
   120472   if( iPrev>=0 ){
   120473     int nMaxUndeferred = pPhrase->iDoclistToken;
   120474     if( nMaxUndeferred<0 ){
   120475       pPhrase->doclist.pList = aPoslist;
   120476       pPhrase->doclist.nList = nPoslist;
   120477       pPhrase->doclist.iDocid = pCsr->iPrevId;
   120478       pPhrase->doclist.bFreeList = 1;
   120479     }else{
   120480       int nDistance;
   120481       char *p1;
   120482       char *p2;
   120483       char *aOut;
   120484 
   120485       if( nMaxUndeferred>iPrev ){
   120486         p1 = aPoslist;
   120487         p2 = pPhrase->doclist.pList;
   120488         nDistance = nMaxUndeferred - iPrev;
   120489       }else{
   120490         p1 = pPhrase->doclist.pList;
   120491         p2 = aPoslist;
   120492         nDistance = iPrev - nMaxUndeferred;
   120493       }
   120494 
   120495       aOut = (char *)sqlite3_malloc(nPoslist+8);
   120496       if( !aOut ){
   120497         sqlite3_free(aPoslist);
   120498         return SQLITE_NOMEM;
   120499       }
   120500 
   120501       pPhrase->doclist.pList = aOut;
   120502       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
   120503         pPhrase->doclist.bFreeList = 1;
   120504         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
   120505       }else{
   120506         sqlite3_free(aOut);
   120507         pPhrase->doclist.pList = 0;
   120508         pPhrase->doclist.nList = 0;
   120509       }
   120510       sqlite3_free(aPoslist);
   120511     }
   120512   }
   120513 
   120514   return SQLITE_OK;
   120515 }
   120516 
   120517 /*
   120518 ** This function is called for each Fts3Phrase in a full-text query
   120519 ** expression to initialize the mechanism for returning rows. Once this
   120520 ** function has been called successfully on an Fts3Phrase, it may be
   120521 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
   120522 **
   120523 ** If parameter bOptOk is true, then the phrase may (or may not) use the
   120524 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
   120525 ** memory within this call.
   120526 **
   120527 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120528 */
   120529 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
   120530   int rc;                         /* Error code */
   120531   Fts3PhraseToken *pFirst = &p->aToken[0];
   120532   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120533 
   120534   if( pCsr->bDesc==pTab->bDescIdx
   120535    && bOptOk==1
   120536    && p->nToken==1
   120537    && pFirst->pSegcsr
   120538    && pFirst->pSegcsr->bLookup
   120539    && pFirst->bFirst==0
   120540   ){
   120541     /* Use the incremental approach. */
   120542     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
   120543     rc = sqlite3Fts3MsrIncrStart(
   120544         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
   120545     p->bIncr = 1;
   120546 
   120547   }else{
   120548     /* Load the full doclist for the phrase into memory. */
   120549     rc = fts3EvalPhraseLoad(pCsr, p);
   120550     p->bIncr = 0;
   120551   }
   120552 
   120553   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
   120554   return rc;
   120555 }
   120556 
   120557 /*
   120558 ** This function is used to iterate backwards (from the end to start)
   120559 ** through doclists. It is used by this module to iterate through phrase
   120560 ** doclists in reverse and by the fts3_write.c module to iterate through
   120561 ** pending-terms lists when writing to databases with "order=desc".
   120562 **
   120563 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
   120564 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
   120565 ** function iterates from the end of the doclist to the beginning.
   120566 */
   120567 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
   120568   int bDescIdx,                   /* True if the doclist is desc */
   120569   char *aDoclist,                 /* Pointer to entire doclist */
   120570   int nDoclist,                   /* Length of aDoclist in bytes */
   120571   char **ppIter,                  /* IN/OUT: Iterator pointer */
   120572   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   120573   int *pnList,                    /* IN/OUT: List length pointer */
   120574   u8 *pbEof                       /* OUT: End-of-file flag */
   120575 ){
   120576   char *p = *ppIter;
   120577 
   120578   assert( nDoclist>0 );
   120579   assert( *pbEof==0 );
   120580   assert( p || *piDocid==0 );
   120581   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
   120582 
   120583   if( p==0 ){
   120584     sqlite3_int64 iDocid = 0;
   120585     char *pNext = 0;
   120586     char *pDocid = aDoclist;
   120587     char *pEnd = &aDoclist[nDoclist];
   120588     int iMul = 1;
   120589 
   120590     while( pDocid<pEnd ){
   120591       sqlite3_int64 iDelta;
   120592       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
   120593       iDocid += (iMul * iDelta);
   120594       pNext = pDocid;
   120595       fts3PoslistCopy(0, &pDocid);
   120596       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
   120597       iMul = (bDescIdx ? -1 : 1);
   120598     }
   120599 
   120600     *pnList = (int)(pEnd - pNext);
   120601     *ppIter = pNext;
   120602     *piDocid = iDocid;
   120603   }else{
   120604     int iMul = (bDescIdx ? -1 : 1);
   120605     sqlite3_int64 iDelta;
   120606     fts3GetReverseVarint(&p, aDoclist, &iDelta);
   120607     *piDocid -= (iMul * iDelta);
   120608 
   120609     if( p==aDoclist ){
   120610       *pbEof = 1;
   120611     }else{
   120612       char *pSave = p;
   120613       fts3ReversePoslist(aDoclist, &p);
   120614       *pnList = (int)(pSave - p);
   120615     }
   120616     *ppIter = p;
   120617   }
   120618 }
   120619 
   120620 /*
   120621 ** Attempt to move the phrase iterator to point to the next matching docid.
   120622 ** If an error occurs, return an SQLite error code. Otherwise, return
   120623 ** SQLITE_OK.
   120624 **
   120625 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   120626 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   120627 ** successfully advanced, *pbEof is set to 0.
   120628 */
   120629 static int fts3EvalPhraseNext(
   120630   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120631   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   120632   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   120633 ){
   120634   int rc = SQLITE_OK;
   120635   Fts3Doclist *pDL = &p->doclist;
   120636   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120637 
   120638   if( p->bIncr ){
   120639     assert( p->nToken==1 );
   120640     assert( pDL->pNextDocid==0 );
   120641     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
   120642         &pDL->iDocid, &pDL->pList, &pDL->nList
   120643     );
   120644     if( rc==SQLITE_OK && !pDL->pList ){
   120645       *pbEof = 1;
   120646     }
   120647   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
   120648     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
   120649         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
   120650     );
   120651     pDL->pList = pDL->pNextDocid;
   120652   }else{
   120653     char *pIter;                            /* Used to iterate through aAll */
   120654     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
   120655     if( pDL->pNextDocid ){
   120656       pIter = pDL->pNextDocid;
   120657     }else{
   120658       pIter = pDL->aAll;
   120659     }
   120660 
   120661     if( pIter>=pEnd ){
   120662       /* We have already reached the end of this doclist. EOF. */
   120663       *pbEof = 1;
   120664     }else{
   120665       sqlite3_int64 iDelta;
   120666       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
   120667       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
   120668         pDL->iDocid += iDelta;
   120669       }else{
   120670         pDL->iDocid -= iDelta;
   120671       }
   120672       pDL->pList = pIter;
   120673       fts3PoslistCopy(0, &pIter);
   120674       pDL->nList = (int)(pIter - pDL->pList);
   120675 
   120676       /* pIter now points just past the 0x00 that terminates the position-
   120677       ** list for document pDL->iDocid. However, if this position-list was
   120678       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
   120679       ** point to the start of the next docid value. The following line deals
   120680       ** with this case by advancing pIter past the zero-padding added by
   120681       ** fts3EvalNearTrim().  */
   120682       while( pIter<pEnd && *pIter==0 ) pIter++;
   120683 
   120684       pDL->pNextDocid = pIter;
   120685       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
   120686       *pbEof = 0;
   120687     }
   120688   }
   120689 
   120690   return rc;
   120691 }
   120692 
   120693 /*
   120694 **
   120695 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   120696 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
   120697 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
   120698 ** expressions for which all descendent tokens are deferred.
   120699 **
   120700 ** If parameter bOptOk is zero, then it is guaranteed that the
   120701 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
   120702 ** each phrase in the expression (subject to deferred token processing).
   120703 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
   120704 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
   120705 **
   120706 ** If an error occurs within this function, *pRc is set to an SQLite error
   120707 ** code before returning.
   120708 */
   120709 static void fts3EvalStartReaders(
   120710   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120711   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
   120712   int bOptOk,                     /* True to enable incremental loading */
   120713   int *pRc                        /* IN/OUT: Error code */
   120714 ){
   120715   if( pExpr && SQLITE_OK==*pRc ){
   120716     if( pExpr->eType==FTSQUERY_PHRASE ){
   120717       int i;
   120718       int nToken = pExpr->pPhrase->nToken;
   120719       for(i=0; i<nToken; i++){
   120720         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
   120721       }
   120722       pExpr->bDeferred = (i==nToken);
   120723       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
   120724     }else{
   120725       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
   120726       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
   120727       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
   120728     }
   120729   }
   120730 }
   120731 
   120732 /*
   120733 ** An array of the following structures is assembled as part of the process
   120734 ** of selecting tokens to defer before the query starts executing (as part
   120735 ** of the xFilter() method). There is one element in the array for each
   120736 ** token in the FTS expression.
   120737 **
   120738 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
   120739 ** to phrases that are connected only by AND and NEAR operators (not OR or
   120740 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
   120741 ** separately. The root of a tokens AND/NEAR cluster is stored in
   120742 ** Fts3TokenAndCost.pRoot.
   120743 */
   120744 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
   120745 struct Fts3TokenAndCost {
   120746   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
   120747   int iToken;                     /* Position of token in phrase */
   120748   Fts3PhraseToken *pToken;        /* The token itself */
   120749   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
   120750   int nOvfl;                      /* Number of overflow pages to load doclist */
   120751   int iCol;                       /* The column the token must match */
   120752 };
   120753 
   120754 /*
   120755 ** This function is used to populate an allocated Fts3TokenAndCost array.
   120756 **
   120757 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   120758 ** Otherwise, if an error occurs during execution, *pRc is set to an
   120759 ** SQLite error code.
   120760 */
   120761 static void fts3EvalTokenCosts(
   120762   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120763   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
   120764   Fts3Expr *pExpr,                /* Expression to consider */
   120765   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
   120766   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
   120767   int *pRc                        /* IN/OUT: Error code */
   120768 ){
   120769   if( *pRc==SQLITE_OK ){
   120770     if( pExpr->eType==FTSQUERY_PHRASE ){
   120771       Fts3Phrase *pPhrase = pExpr->pPhrase;
   120772       int i;
   120773       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
   120774         Fts3TokenAndCost *pTC = (*ppTC)++;
   120775         pTC->pPhrase = pPhrase;
   120776         pTC->iToken = i;
   120777         pTC->pRoot = pRoot;
   120778         pTC->pToken = &pPhrase->aToken[i];
   120779         pTC->iCol = pPhrase->iColumn;
   120780         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
   120781       }
   120782     }else if( pExpr->eType!=FTSQUERY_NOT ){
   120783       assert( pExpr->eType==FTSQUERY_OR
   120784            || pExpr->eType==FTSQUERY_AND
   120785            || pExpr->eType==FTSQUERY_NEAR
   120786       );
   120787       assert( pExpr->pLeft && pExpr->pRight );
   120788       if( pExpr->eType==FTSQUERY_OR ){
   120789         pRoot = pExpr->pLeft;
   120790         **ppOr = pRoot;
   120791         (*ppOr)++;
   120792       }
   120793       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
   120794       if( pExpr->eType==FTSQUERY_OR ){
   120795         pRoot = pExpr->pRight;
   120796         **ppOr = pRoot;
   120797         (*ppOr)++;
   120798       }
   120799       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
   120800     }
   120801   }
   120802 }
   120803 
   120804 /*
   120805 ** Determine the average document (row) size in pages. If successful,
   120806 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
   120807 ** an SQLite error code.
   120808 **
   120809 ** The average document size in pages is calculated by first calculating
   120810 ** determining the average size in bytes, B. If B is less than the amount
   120811 ** of data that will fit on a single leaf page of an intkey table in
   120812 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
   120813 ** the number of overflow pages consumed by a record B bytes in size.
   120814 */
   120815 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   120816   if( pCsr->nRowAvg==0 ){
   120817     /* The average document size, which is required to calculate the cost
   120818     ** of each doclist, has not yet been determined. Read the required
   120819     ** data from the %_stat table to calculate it.
   120820     **
   120821     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   120822     ** varints, where nCol is the number of columns in the FTS3 table.
   120823     ** The first varint is the number of documents currently stored in
   120824     ** the table. The following nCol varints contain the total amount of
   120825     ** data stored in all rows of each column of the table, from left
   120826     ** to right.
   120827     */
   120828     int rc;
   120829     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   120830     sqlite3_stmt *pStmt;
   120831     sqlite3_int64 nDoc = 0;
   120832     sqlite3_int64 nByte = 0;
   120833     const char *pEnd;
   120834     const char *a;
   120835 
   120836     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
   120837     if( rc!=SQLITE_OK ) return rc;
   120838     a = sqlite3_column_blob(pStmt, 0);
   120839     assert( a );
   120840 
   120841     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   120842     a += sqlite3Fts3GetVarint(a, &nDoc);
   120843     while( a<pEnd ){
   120844       a += sqlite3Fts3GetVarint(a, &nByte);
   120845     }
   120846     if( nDoc==0 || nByte==0 ){
   120847       sqlite3_reset(pStmt);
   120848       return FTS_CORRUPT_VTAB;
   120849     }
   120850 
   120851     pCsr->nDoc = nDoc;
   120852     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
   120853     assert( pCsr->nRowAvg>0 );
   120854     rc = sqlite3_reset(pStmt);
   120855     if( rc!=SQLITE_OK ) return rc;
   120856   }
   120857 
   120858   *pnPage = pCsr->nRowAvg;
   120859   return SQLITE_OK;
   120860 }
   120861 
   120862 /*
   120863 ** This function is called to select the tokens (if any) that will be
   120864 ** deferred. The array aTC[] has already been populated when this is
   120865 ** called.
   120866 **
   120867 ** This function is called once for each AND/NEAR cluster in the
   120868 ** expression. Each invocation determines which tokens to defer within
   120869 ** the cluster with root node pRoot. See comments above the definition
   120870 ** of struct Fts3TokenAndCost for more details.
   120871 **
   120872 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
   120873 ** called on each token to defer. Otherwise, an SQLite error code is
   120874 ** returned.
   120875 */
   120876 static int fts3EvalSelectDeferred(
   120877   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120878   Fts3Expr *pRoot,                /* Consider tokens with this root node */
   120879   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
   120880   int nTC                         /* Number of entries in aTC[] */
   120881 ){
   120882   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120883   int nDocSize = 0;               /* Number of pages per doc loaded */
   120884   int rc = SQLITE_OK;             /* Return code */
   120885   int ii;                         /* Iterator variable for various purposes */
   120886   int nOvfl = 0;                  /* Total overflow pages used by doclists */
   120887   int nToken = 0;                 /* Total number of tokens in cluster */
   120888 
   120889   int nMinEst = 0;                /* The minimum count for any phrase so far. */
   120890   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
   120891 
   120892   /* Tokens are never deferred for FTS tables created using the content=xxx
   120893   ** option. The reason being that it is not guaranteed that the content
   120894   ** table actually contains the same data as the index. To prevent this from
   120895   ** causing any problems, the deferred token optimization is completely
   120896   ** disabled for content=xxx tables. */
   120897   if( pTab->zContentTbl ){
   120898     return SQLITE_OK;
   120899   }
   120900 
   120901   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
   120902   ** associated with the tokens spill onto overflow pages, or if there is
   120903   ** only 1 token, exit early. No tokens to defer in this case. */
   120904   for(ii=0; ii<nTC; ii++){
   120905     if( aTC[ii].pRoot==pRoot ){
   120906       nOvfl += aTC[ii].nOvfl;
   120907       nToken++;
   120908     }
   120909   }
   120910   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
   120911 
   120912   /* Obtain the average docsize (in pages). */
   120913   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
   120914   assert( rc!=SQLITE_OK || nDocSize>0 );
   120915 
   120916 
   120917   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
   120918   ** of the number of overflow pages that will be loaded by the pager layer
   120919   ** to retrieve the entire doclist for the token from the full-text index.
   120920   ** Load the doclists for tokens that are either:
   120921   **
   120922   **   a. The cheapest token in the entire query (i.e. the one visited by the
   120923   **      first iteration of this loop), or
   120924   **
   120925   **   b. Part of a multi-token phrase.
   120926   **
   120927   ** After each token doclist is loaded, merge it with the others from the
   120928   ** same phrase and count the number of documents that the merged doclist
   120929   ** contains. Set variable "nMinEst" to the smallest number of documents in
   120930   ** any phrase doclist for which 1 or more token doclists have been loaded.
   120931   ** Let nOther be the number of other phrases for which it is certain that
   120932   ** one or more tokens will not be deferred.
   120933   **
   120934   ** Then, for each token, defer it if loading the doclist would result in
   120935   ** loading N or more overflow pages into memory, where N is computed as:
   120936   **
   120937   **    (nMinEst + 4^nOther - 1) / (4^nOther)
   120938   */
   120939   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
   120940     int iTC;                      /* Used to iterate through aTC[] array. */
   120941     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
   120942 
   120943     /* Set pTC to point to the cheapest remaining token. */
   120944     for(iTC=0; iTC<nTC; iTC++){
   120945       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
   120946        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
   120947       ){
   120948         pTC = &aTC[iTC];
   120949       }
   120950     }
   120951     assert( pTC );
   120952 
   120953     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
   120954       /* The number of overflow pages to load for this (and therefore all
   120955       ** subsequent) tokens is greater than the estimated number of pages
   120956       ** that will be loaded if all subsequent tokens are deferred.
   120957       */
   120958       Fts3PhraseToken *pToken = pTC->pToken;
   120959       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
   120960       fts3SegReaderCursorFree(pToken->pSegcsr);
   120961       pToken->pSegcsr = 0;
   120962     }else{
   120963       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
   120964       ** for-loop. Except, limit the value to 2^24 to prevent it from
   120965       ** overflowing the 32-bit integer it is stored in. */
   120966       if( ii<12 ) nLoad4 = nLoad4*4;
   120967 
   120968       if( ii==0 || pTC->pPhrase->nToken>1 ){
   120969         /* Either this is the cheapest token in the entire query, or it is
   120970         ** part of a multi-token phrase. Either way, the entire doclist will
   120971         ** (eventually) be loaded into memory. It may as well be now. */
   120972         Fts3PhraseToken *pToken = pTC->pToken;
   120973         int nList = 0;
   120974         char *pList = 0;
   120975         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
   120976         assert( rc==SQLITE_OK || pList==0 );
   120977         if( rc==SQLITE_OK ){
   120978           int nCount;
   120979           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
   120980           nCount = fts3DoclistCountDocids(
   120981               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
   120982           );
   120983           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
   120984         }
   120985       }
   120986     }
   120987     pTC->pToken = 0;
   120988   }
   120989 
   120990   return rc;
   120991 }
   120992 
   120993 /*
   120994 ** This function is called from within the xFilter method. It initializes
   120995 ** the full-text query currently stored in pCsr->pExpr. To iterate through
   120996 ** the results of a query, the caller does:
   120997 **
   120998 **    fts3EvalStart(pCsr);
   120999 **    while( 1 ){
   121000 **      fts3EvalNext(pCsr);
   121001 **      if( pCsr->bEof ) break;
   121002 **      ... return row pCsr->iPrevId to the caller ...
   121003 **    }
   121004 */
   121005 static int fts3EvalStart(Fts3Cursor *pCsr){
   121006   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121007   int rc = SQLITE_OK;
   121008   int nToken = 0;
   121009   int nOr = 0;
   121010 
   121011   /* Allocate a MultiSegReader for each token in the expression. */
   121012   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
   121013 
   121014   /* Determine which, if any, tokens in the expression should be deferred. */
   121015   if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
   121016     Fts3TokenAndCost *aTC;
   121017     Fts3Expr **apOr;
   121018     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
   121019         sizeof(Fts3TokenAndCost) * nToken
   121020       + sizeof(Fts3Expr *) * nOr * 2
   121021     );
   121022     apOr = (Fts3Expr **)&aTC[nToken];
   121023 
   121024     if( !aTC ){
   121025       rc = SQLITE_NOMEM;
   121026     }else{
   121027       int ii;
   121028       Fts3TokenAndCost *pTC = aTC;
   121029       Fts3Expr **ppOr = apOr;
   121030 
   121031       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
   121032       nToken = (int)(pTC-aTC);
   121033       nOr = (int)(ppOr-apOr);
   121034 
   121035       if( rc==SQLITE_OK ){
   121036         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
   121037         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
   121038           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
   121039         }
   121040       }
   121041 
   121042       sqlite3_free(aTC);
   121043     }
   121044   }
   121045 
   121046   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
   121047   return rc;
   121048 }
   121049 
   121050 /*
   121051 ** Invalidate the current position list for phrase pPhrase.
   121052 */
   121053 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
   121054   if( pPhrase->doclist.bFreeList ){
   121055     sqlite3_free(pPhrase->doclist.pList);
   121056   }
   121057   pPhrase->doclist.pList = 0;
   121058   pPhrase->doclist.nList = 0;
   121059   pPhrase->doclist.bFreeList = 0;
   121060 }
   121061 
   121062 /*
   121063 ** This function is called to edit the position list associated with
   121064 ** the phrase object passed as the fifth argument according to a NEAR
   121065 ** condition. For example:
   121066 **
   121067 **     abc NEAR/5 "def ghi"
   121068 **
   121069 ** Parameter nNear is passed the NEAR distance of the expression (5 in
   121070 ** the example above). When this function is called, *paPoslist points to
   121071 ** the position list, and *pnToken is the number of phrase tokens in, the
   121072 ** phrase on the other side of the NEAR operator to pPhrase. For example,
   121073 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
   121074 ** the position list associated with phrase "abc".
   121075 **
   121076 ** All positions in the pPhrase position list that are not sufficiently
   121077 ** close to a position in the *paPoslist position list are removed. If this
   121078 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
   121079 **
   121080 ** Before returning, *paPoslist is set to point to the position lsit
   121081 ** associated with pPhrase. And *pnToken is set to the number of tokens in
   121082 ** pPhrase.
   121083 */
   121084 static int fts3EvalNearTrim(
   121085   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
   121086   char *aTmp,                     /* Temporary space to use */
   121087   char **paPoslist,               /* IN/OUT: Position list */
   121088   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
   121089   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
   121090 ){
   121091   int nParam1 = nNear + pPhrase->nToken;
   121092   int nParam2 = nNear + *pnToken;
   121093   int nNew;
   121094   char *p2;
   121095   char *pOut;
   121096   int res;
   121097 
   121098   assert( pPhrase->doclist.pList );
   121099 
   121100   p2 = pOut = pPhrase->doclist.pList;
   121101   res = fts3PoslistNearMerge(
   121102     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
   121103   );
   121104   if( res ){
   121105     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
   121106     assert( pPhrase->doclist.pList[nNew]=='\0' );
   121107     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
   121108     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
   121109     pPhrase->doclist.nList = nNew;
   121110     *paPoslist = pPhrase->doclist.pList;
   121111     *pnToken = pPhrase->nToken;
   121112   }
   121113 
   121114   return res;
   121115 }
   121116 
   121117 /*
   121118 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
   121119 ** Otherwise, it advances the expression passed as the second argument to
   121120 ** point to the next matching row in the database. Expressions iterate through
   121121 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
   121122 ** or descending if it is non-zero.
   121123 **
   121124 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
   121125 ** successful, the following variables in pExpr are set:
   121126 **
   121127 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
   121128 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
   121129 **
   121130 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
   121131 ** at EOF, then the following variables are populated with the position list
   121132 ** for the phrase for the visited row:
   121133 **
   121134 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
   121135 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
   121136 **
   121137 ** It says above that this function advances the expression to the next
   121138 ** matching row. This is usually true, but there are the following exceptions:
   121139 **
   121140 **   1. Deferred tokens are not taken into account. If a phrase consists
   121141 **      entirely of deferred tokens, it is assumed to match every row in
   121142 **      the db. In this case the position-list is not populated at all.
   121143 **
   121144 **      Or, if a phrase contains one or more deferred tokens and one or
   121145 **      more non-deferred tokens, then the expression is advanced to the
   121146 **      next possible match, considering only non-deferred tokens. In other
   121147 **      words, if the phrase is "A B C", and "B" is deferred, the expression
   121148 **      is advanced to the next row that contains an instance of "A * C",
   121149 **      where "*" may match any single token. The position list in this case
   121150 **      is populated as for "A * C" before returning.
   121151 **
   121152 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
   121153 **      advanced to point to the next row that matches "x AND y".
   121154 **
   121155 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
   121156 ** really a match, taking into account deferred tokens and NEAR operators.
   121157 */
   121158 static void fts3EvalNextRow(
   121159   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   121160   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
   121161   int *pRc                        /* IN/OUT: Error code */
   121162 ){
   121163   if( *pRc==SQLITE_OK ){
   121164     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
   121165     assert( pExpr->bEof==0 );
   121166     pExpr->bStart = 1;
   121167 
   121168     switch( pExpr->eType ){
   121169       case FTSQUERY_NEAR:
   121170       case FTSQUERY_AND: {
   121171         Fts3Expr *pLeft = pExpr->pLeft;
   121172         Fts3Expr *pRight = pExpr->pRight;
   121173         assert( !pLeft->bDeferred || !pRight->bDeferred );
   121174 
   121175         if( pLeft->bDeferred ){
   121176           /* LHS is entirely deferred. So we assume it matches every row.
   121177           ** Advance the RHS iterator to find the next row visited. */
   121178           fts3EvalNextRow(pCsr, pRight, pRc);
   121179           pExpr->iDocid = pRight->iDocid;
   121180           pExpr->bEof = pRight->bEof;
   121181         }else if( pRight->bDeferred ){
   121182           /* RHS is entirely deferred. So we assume it matches every row.
   121183           ** Advance the LHS iterator to find the next row visited. */
   121184           fts3EvalNextRow(pCsr, pLeft, pRc);
   121185           pExpr->iDocid = pLeft->iDocid;
   121186           pExpr->bEof = pLeft->bEof;
   121187         }else{
   121188           /* Neither the RHS or LHS are deferred. */
   121189           fts3EvalNextRow(pCsr, pLeft, pRc);
   121190           fts3EvalNextRow(pCsr, pRight, pRc);
   121191           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
   121192             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121193             if( iDiff==0 ) break;
   121194             if( iDiff<0 ){
   121195               fts3EvalNextRow(pCsr, pLeft, pRc);
   121196             }else{
   121197               fts3EvalNextRow(pCsr, pRight, pRc);
   121198             }
   121199           }
   121200           pExpr->iDocid = pLeft->iDocid;
   121201           pExpr->bEof = (pLeft->bEof || pRight->bEof);
   121202         }
   121203         break;
   121204       }
   121205 
   121206       case FTSQUERY_OR: {
   121207         Fts3Expr *pLeft = pExpr->pLeft;
   121208         Fts3Expr *pRight = pExpr->pRight;
   121209         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121210 
   121211         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
   121212         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
   121213 
   121214         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
   121215           fts3EvalNextRow(pCsr, pLeft, pRc);
   121216         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
   121217           fts3EvalNextRow(pCsr, pRight, pRc);
   121218         }else{
   121219           fts3EvalNextRow(pCsr, pLeft, pRc);
   121220           fts3EvalNextRow(pCsr, pRight, pRc);
   121221         }
   121222 
   121223         pExpr->bEof = (pLeft->bEof && pRight->bEof);
   121224         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121225         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
   121226           pExpr->iDocid = pLeft->iDocid;
   121227         }else{
   121228           pExpr->iDocid = pRight->iDocid;
   121229         }
   121230 
   121231         break;
   121232       }
   121233 
   121234       case FTSQUERY_NOT: {
   121235         Fts3Expr *pLeft = pExpr->pLeft;
   121236         Fts3Expr *pRight = pExpr->pRight;
   121237 
   121238         if( pRight->bStart==0 ){
   121239           fts3EvalNextRow(pCsr, pRight, pRc);
   121240           assert( *pRc!=SQLITE_OK || pRight->bStart );
   121241         }
   121242 
   121243         fts3EvalNextRow(pCsr, pLeft, pRc);
   121244         if( pLeft->bEof==0 ){
   121245           while( !*pRc
   121246               && !pRight->bEof
   121247               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
   121248           ){
   121249             fts3EvalNextRow(pCsr, pRight, pRc);
   121250           }
   121251         }
   121252         pExpr->iDocid = pLeft->iDocid;
   121253         pExpr->bEof = pLeft->bEof;
   121254         break;
   121255       }
   121256 
   121257       default: {
   121258         Fts3Phrase *pPhrase = pExpr->pPhrase;
   121259         fts3EvalInvalidatePoslist(pPhrase);
   121260         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
   121261         pExpr->iDocid = pPhrase->doclist.iDocid;
   121262         break;
   121263       }
   121264     }
   121265   }
   121266 }
   121267 
   121268 /*
   121269 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
   121270 ** cluster, then this function returns 1 immediately.
   121271 **
   121272 ** Otherwise, it checks if the current row really does match the NEAR
   121273 ** expression, using the data currently stored in the position lists
   121274 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
   121275 **
   121276 ** If the current row is a match, the position list associated with each
   121277 ** phrase in the NEAR expression is edited in place to contain only those
   121278 ** phrase instances sufficiently close to their peers to satisfy all NEAR
   121279 ** constraints. In this case it returns 1. If the NEAR expression does not
   121280 ** match the current row, 0 is returned. The position lists may or may not
   121281 ** be edited if 0 is returned.
   121282 */
   121283 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   121284   int res = 1;
   121285 
   121286   /* The following block runs if pExpr is the root of a NEAR query.
   121287   ** For example, the query:
   121288   **
   121289   **         "w" NEAR "x" NEAR "y" NEAR "z"
   121290   **
   121291   ** which is represented in tree form as:
   121292   **
   121293   **                               |
   121294   **                          +--NEAR--+      <-- root of NEAR query
   121295   **                          |        |
   121296   **                     +--NEAR--+   "z"
   121297   **                     |        |
   121298   **                +--NEAR--+   "y"
   121299   **                |        |
   121300   **               "w"      "x"
   121301   **
   121302   ** The right-hand child of a NEAR node is always a phrase. The
   121303   ** left-hand child may be either a phrase or a NEAR node. There are
   121304   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   121305   */
   121306   if( *pRc==SQLITE_OK
   121307    && pExpr->eType==FTSQUERY_NEAR
   121308    && pExpr->bEof==0
   121309    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   121310   ){
   121311     Fts3Expr *p;
   121312     int nTmp = 0;                 /* Bytes of temp space */
   121313     char *aTmp;                   /* Temp space for PoslistNearMerge() */
   121314 
   121315     /* Allocate temporary working space. */
   121316     for(p=pExpr; p->pLeft; p=p->pLeft){
   121317       nTmp += p->pRight->pPhrase->doclist.nList;
   121318     }
   121319     nTmp += p->pPhrase->doclist.nList;
   121320     aTmp = sqlite3_malloc(nTmp*2);
   121321     if( !aTmp ){
   121322       *pRc = SQLITE_NOMEM;
   121323       res = 0;
   121324     }else{
   121325       char *aPoslist = p->pPhrase->doclist.pList;
   121326       int nToken = p->pPhrase->nToken;
   121327 
   121328       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
   121329         Fts3Phrase *pPhrase = p->pRight->pPhrase;
   121330         int nNear = p->nNear;
   121331         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   121332       }
   121333 
   121334       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
   121335       nToken = pExpr->pRight->pPhrase->nToken;
   121336       for(p=pExpr->pLeft; p && res; p=p->pLeft){
   121337         int nNear;
   121338         Fts3Phrase *pPhrase;
   121339         assert( p->pParent && p->pParent->pLeft==p );
   121340         nNear = p->pParent->nNear;
   121341         pPhrase = (
   121342             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
   121343         );
   121344         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   121345       }
   121346     }
   121347 
   121348     sqlite3_free(aTmp);
   121349   }
   121350 
   121351   return res;
   121352 }
   121353 
   121354 /*
   121355 ** This function is a helper function for fts3EvalTestDeferredAndNear().
   121356 ** Assuming no error occurs or has occurred, It returns non-zero if the
   121357 ** expression passed as the second argument matches the row that pCsr
   121358 ** currently points to, or zero if it does not.
   121359 **
   121360 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   121361 ** If an error occurs during execution of this function, *pRc is set to
   121362 ** the appropriate SQLite error code. In this case the returned value is
   121363 ** undefined.
   121364 */
   121365 static int fts3EvalTestExpr(
   121366   Fts3Cursor *pCsr,               /* FTS cursor handle */
   121367   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
   121368   int *pRc                        /* IN/OUT: Error code */
   121369 ){
   121370   int bHit = 1;                   /* Return value */
   121371   if( *pRc==SQLITE_OK ){
   121372     switch( pExpr->eType ){
   121373       case FTSQUERY_NEAR:
   121374       case FTSQUERY_AND:
   121375         bHit = (
   121376             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   121377          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   121378          && fts3EvalNearTest(pExpr, pRc)
   121379         );
   121380 
   121381         /* If the NEAR expression does not match any rows, zero the doclist for
   121382         ** all phrases involved in the NEAR. This is because the snippet(),
   121383         ** offsets() and matchinfo() functions are not supposed to recognize
   121384         ** any instances of phrases that are part of unmatched NEAR queries.
   121385         ** For example if this expression:
   121386         **
   121387         **    ... MATCH 'a OR (b NEAR c)'
   121388         **
   121389         ** is matched against a row containing:
   121390         **
   121391         **        'a b d e'
   121392         **
   121393         ** then any snippet() should ony highlight the "a" term, not the "b"
   121394         ** (as "b" is part of a non-matching NEAR clause).
   121395         */
   121396         if( bHit==0
   121397          && pExpr->eType==FTSQUERY_NEAR
   121398          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   121399         ){
   121400           Fts3Expr *p;
   121401           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
   121402             if( p->pRight->iDocid==pCsr->iPrevId ){
   121403               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
   121404             }
   121405           }
   121406           if( p->iDocid==pCsr->iPrevId ){
   121407             fts3EvalInvalidatePoslist(p->pPhrase);
   121408           }
   121409         }
   121410 
   121411         break;
   121412 
   121413       case FTSQUERY_OR: {
   121414         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
   121415         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
   121416         bHit = bHit1 || bHit2;
   121417         break;
   121418       }
   121419 
   121420       case FTSQUERY_NOT:
   121421         bHit = (
   121422             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   121423          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   121424         );
   121425         break;
   121426 
   121427       default: {
   121428         if( pCsr->pDeferred
   121429          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
   121430         ){
   121431           Fts3Phrase *pPhrase = pExpr->pPhrase;
   121432           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
   121433           if( pExpr->bDeferred ){
   121434             fts3EvalInvalidatePoslist(pPhrase);
   121435           }
   121436           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
   121437           bHit = (pPhrase->doclist.pList!=0);
   121438           pExpr->iDocid = pCsr->iPrevId;
   121439         }else{
   121440           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
   121441         }
   121442         break;
   121443       }
   121444     }
   121445   }
   121446   return bHit;
   121447 }
   121448 
   121449 /*
   121450 ** This function is called as the second part of each xNext operation when
   121451 ** iterating through the results of a full-text query. At this point the
   121452 ** cursor points to a row that matches the query expression, with the
   121453 ** following caveats:
   121454 **
   121455 **   * Up until this point, "NEAR" operators in the expression have been
   121456 **     treated as "AND".
   121457 **
   121458 **   * Deferred tokens have not yet been considered.
   121459 **
   121460 ** If *pRc is not SQLITE_OK when this function is called, it immediately
   121461 ** returns 0. Otherwise, it tests whether or not after considering NEAR
   121462 ** operators and deferred tokens the current row is still a match for the
   121463 ** expression. It returns 1 if both of the following are true:
   121464 **
   121465 **   1. *pRc is SQLITE_OK when this function returns, and
   121466 **
   121467 **   2. After scanning the current FTS table row for the deferred tokens,
   121468 **      it is determined that the row does *not* match the query.
   121469 **
   121470 ** Or, if no error occurs and it seems the current row does match the FTS
   121471 ** query, return 0.
   121472 */
   121473 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
   121474   int rc = *pRc;
   121475   int bMiss = 0;
   121476   if( rc==SQLITE_OK ){
   121477 
   121478     /* If there are one or more deferred tokens, load the current row into
   121479     ** memory and scan it to determine the position list for each deferred
   121480     ** token. Then, see if this row is really a match, considering deferred
   121481     ** tokens and NEAR operators (neither of which were taken into account
   121482     ** earlier, by fts3EvalNextRow()).
   121483     */
   121484     if( pCsr->pDeferred ){
   121485       rc = fts3CursorSeek(0, pCsr);
   121486       if( rc==SQLITE_OK ){
   121487         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   121488       }
   121489     }
   121490     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
   121491 
   121492     /* Free the position-lists accumulated for each deferred token above. */
   121493     sqlite3Fts3FreeDeferredDoclists(pCsr);
   121494     *pRc = rc;
   121495   }
   121496   return (rc==SQLITE_OK && bMiss);
   121497 }
   121498 
   121499 /*
   121500 ** Advance to the next document that matches the FTS expression in
   121501 ** Fts3Cursor.pExpr.
   121502 */
   121503 static int fts3EvalNext(Fts3Cursor *pCsr){
   121504   int rc = SQLITE_OK;             /* Return Code */
   121505   Fts3Expr *pExpr = pCsr->pExpr;
   121506   assert( pCsr->isEof==0 );
   121507   if( pExpr==0 ){
   121508     pCsr->isEof = 1;
   121509   }else{
   121510     do {
   121511       if( pCsr->isRequireSeek==0 ){
   121512         sqlite3_reset(pCsr->pStmt);
   121513       }
   121514       assert( sqlite3_data_count(pCsr->pStmt)==0 );
   121515       fts3EvalNextRow(pCsr, pExpr, &rc);
   121516       pCsr->isEof = pExpr->bEof;
   121517       pCsr->isRequireSeek = 1;
   121518       pCsr->isMatchinfoNeeded = 1;
   121519       pCsr->iPrevId = pExpr->iDocid;
   121520     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
   121521   }
   121522   return rc;
   121523 }
   121524 
   121525 /*
   121526 ** Restart interation for expression pExpr so that the next call to
   121527 ** fts3EvalNext() visits the first row. Do not allow incremental
   121528 ** loading or merging of phrase doclists for this iteration.
   121529 **
   121530 ** If *pRc is other than SQLITE_OK when this function is called, it is
   121531 ** a no-op. If an error occurs within this function, *pRc is set to an
   121532 ** SQLite error code before returning.
   121533 */
   121534 static void fts3EvalRestart(
   121535   Fts3Cursor *pCsr,
   121536   Fts3Expr *pExpr,
   121537   int *pRc
   121538 ){
   121539   if( pExpr && *pRc==SQLITE_OK ){
   121540     Fts3Phrase *pPhrase = pExpr->pPhrase;
   121541 
   121542     if( pPhrase ){
   121543       fts3EvalInvalidatePoslist(pPhrase);
   121544       if( pPhrase->bIncr ){
   121545         assert( pPhrase->nToken==1 );
   121546         assert( pPhrase->aToken[0].pSegcsr );
   121547         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
   121548         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
   121549       }
   121550 
   121551       pPhrase->doclist.pNextDocid = 0;
   121552       pPhrase->doclist.iDocid = 0;
   121553     }
   121554 
   121555     pExpr->iDocid = 0;
   121556     pExpr->bEof = 0;
   121557     pExpr->bStart = 0;
   121558 
   121559     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
   121560     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
   121561   }
   121562 }
   121563 
   121564 /*
   121565 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
   121566 ** expression rooted at pExpr, the cursor iterates through all rows matched
   121567 ** by pExpr, calling this function for each row. This function increments
   121568 ** the values in Fts3Expr.aMI[] according to the position-list currently
   121569 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
   121570 ** expression nodes.
   121571 */
   121572 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
   121573   if( pExpr ){
   121574     Fts3Phrase *pPhrase = pExpr->pPhrase;
   121575     if( pPhrase && pPhrase->doclist.pList ){
   121576       int iCol = 0;
   121577       char *p = pPhrase->doclist.pList;
   121578 
   121579       assert( *p );
   121580       while( 1 ){
   121581         u8 c = 0;
   121582         int iCnt = 0;
   121583         while( 0xFE & (*p | c) ){
   121584           if( (c&0x80)==0 ) iCnt++;
   121585           c = *p++ & 0x80;
   121586         }
   121587 
   121588         /* aMI[iCol*3 + 1] = Number of occurrences
   121589         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
   121590         */
   121591         pExpr->aMI[iCol*3 + 1] += iCnt;
   121592         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
   121593         if( *p==0x00 ) break;
   121594         p++;
   121595         p += sqlite3Fts3GetVarint32(p, &iCol);
   121596       }
   121597     }
   121598 
   121599     fts3EvalUpdateCounts(pExpr->pLeft);
   121600     fts3EvalUpdateCounts(pExpr->pRight);
   121601   }
   121602 }
   121603 
   121604 /*
   121605 ** Expression pExpr must be of type FTSQUERY_PHRASE.
   121606 **
   121607 ** If it is not already allocated and populated, this function allocates and
   121608 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
   121609 ** of a NEAR expression, then it also allocates and populates the same array
   121610 ** for all other phrases that are part of the NEAR expression.
   121611 **
   121612 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
   121613 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
   121614 */
   121615 static int fts3EvalGatherStats(
   121616   Fts3Cursor *pCsr,               /* Cursor object */
   121617   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
   121618 ){
   121619   int rc = SQLITE_OK;             /* Return code */
   121620 
   121621   assert( pExpr->eType==FTSQUERY_PHRASE );
   121622   if( pExpr->aMI==0 ){
   121623     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121624     Fts3Expr *pRoot;                /* Root of NEAR expression */
   121625     Fts3Expr *p;                    /* Iterator used for several purposes */
   121626 
   121627     sqlite3_int64 iPrevId = pCsr->iPrevId;
   121628     sqlite3_int64 iDocid;
   121629     u8 bEof;
   121630 
   121631     /* Find the root of the NEAR expression */
   121632     pRoot = pExpr;
   121633     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
   121634       pRoot = pRoot->pParent;
   121635     }
   121636     iDocid = pRoot->iDocid;
   121637     bEof = pRoot->bEof;
   121638     assert( pRoot->bStart );
   121639 
   121640     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
   121641     for(p=pRoot; p; p=p->pLeft){
   121642       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
   121643       assert( pE->aMI==0 );
   121644       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
   121645       if( !pE->aMI ) return SQLITE_NOMEM;
   121646       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
   121647     }
   121648 
   121649     fts3EvalRestart(pCsr, pRoot, &rc);
   121650 
   121651     while( pCsr->isEof==0 && rc==SQLITE_OK ){
   121652 
   121653       do {
   121654         /* Ensure the %_content statement is reset. */
   121655         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
   121656         assert( sqlite3_data_count(pCsr->pStmt)==0 );
   121657 
   121658         /* Advance to the next document */
   121659         fts3EvalNextRow(pCsr, pRoot, &rc);
   121660         pCsr->isEof = pRoot->bEof;
   121661         pCsr->isRequireSeek = 1;
   121662         pCsr->isMatchinfoNeeded = 1;
   121663         pCsr->iPrevId = pRoot->iDocid;
   121664       }while( pCsr->isEof==0
   121665            && pRoot->eType==FTSQUERY_NEAR
   121666            && fts3EvalTestDeferredAndNear(pCsr, &rc)
   121667       );
   121668 
   121669       if( rc==SQLITE_OK && pCsr->isEof==0 ){
   121670         fts3EvalUpdateCounts(pRoot);
   121671       }
   121672     }
   121673 
   121674     pCsr->isEof = 0;
   121675     pCsr->iPrevId = iPrevId;
   121676 
   121677     if( bEof ){
   121678       pRoot->bEof = bEof;
   121679     }else{
   121680       /* Caution: pRoot may iterate through docids in ascending or descending
   121681       ** order. For this reason, even though it seems more defensive, the
   121682       ** do loop can not be written:
   121683       **
   121684       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
   121685       */
   121686       fts3EvalRestart(pCsr, pRoot, &rc);
   121687       do {
   121688         fts3EvalNextRow(pCsr, pRoot, &rc);
   121689         assert( pRoot->bEof==0 );
   121690       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
   121691       fts3EvalTestDeferredAndNear(pCsr, &rc);
   121692     }
   121693   }
   121694   return rc;
   121695 }
   121696 
   121697 /*
   121698 ** This function is used by the matchinfo() module to query a phrase
   121699 ** expression node for the following information:
   121700 **
   121701 **   1. The total number of occurrences of the phrase in each column of
   121702 **      the FTS table (considering all rows), and
   121703 **
   121704 **   2. For each column, the number of rows in the table for which the
   121705 **      column contains at least one instance of the phrase.
   121706 **
   121707 ** If no error occurs, SQLITE_OK is returned and the values for each column
   121708 ** written into the array aiOut as follows:
   121709 **
   121710 **   aiOut[iCol*3 + 1] = Number of occurrences
   121711 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
   121712 **
   121713 ** Caveats:
   121714 **
   121715 **   * If a phrase consists entirely of deferred tokens, then all output
   121716 **     values are set to the number of documents in the table. In other
   121717 **     words we assume that very common tokens occur exactly once in each
   121718 **     column of each row of the table.
   121719 **
   121720 **   * If a phrase contains some deferred tokens (and some non-deferred
   121721 **     tokens), count the potential occurrence identified by considering
   121722 **     the non-deferred tokens instead of actual phrase occurrences.
   121723 **
   121724 **   * If the phrase is part of a NEAR expression, then only phrase instances
   121725 **     that meet the NEAR constraint are included in the counts.
   121726 */
   121727 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
   121728   Fts3Cursor *pCsr,               /* FTS cursor handle */
   121729   Fts3Expr *pExpr,                /* Phrase expression */
   121730   u32 *aiOut                      /* Array to write results into (see above) */
   121731 ){
   121732   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121733   int rc = SQLITE_OK;
   121734   int iCol;
   121735 
   121736   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
   121737     assert( pCsr->nDoc>0 );
   121738     for(iCol=0; iCol<pTab->nColumn; iCol++){
   121739       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
   121740       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
   121741     }
   121742   }else{
   121743     rc = fts3EvalGatherStats(pCsr, pExpr);
   121744     if( rc==SQLITE_OK ){
   121745       assert( pExpr->aMI );
   121746       for(iCol=0; iCol<pTab->nColumn; iCol++){
   121747         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
   121748         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
   121749       }
   121750     }
   121751   }
   121752 
   121753   return rc;
   121754 }
   121755 
   121756 /*
   121757 ** The expression pExpr passed as the second argument to this function
   121758 ** must be of type FTSQUERY_PHRASE.
   121759 **
   121760 ** The returned value is either NULL or a pointer to a buffer containing
   121761 ** a position-list indicating the occurrences of the phrase in column iCol
   121762 ** of the current row.
   121763 **
   121764 ** More specifically, the returned buffer contains 1 varint for each
   121765 ** occurence of the phrase in the column, stored using the normal (delta+2)
   121766 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
   121767 ** if the requested column contains "a b X c d X X" and the position-list
   121768 ** for 'X' is requested, the buffer returned may contain:
   121769 **
   121770 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
   121771 **
   121772 ** This function works regardless of whether or not the phrase is deferred,
   121773 ** incremental, or neither.
   121774 */
   121775 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
   121776   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   121777   Fts3Expr *pExpr,                /* Phrase to return doclist for */
   121778   int iCol                        /* Column to return position list for */
   121779 ){
   121780   Fts3Phrase *pPhrase = pExpr->pPhrase;
   121781   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121782   char *pIter = pPhrase->doclist.pList;
   121783   int iThis;
   121784 
   121785   assert( iCol>=0 && iCol<pTab->nColumn );
   121786   if( !pIter
   121787    || pExpr->bEof
   121788    || pExpr->iDocid!=pCsr->iPrevId
   121789    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
   121790   ){
   121791     return 0;
   121792   }
   121793 
   121794   assert( pPhrase->doclist.nList>0 );
   121795   if( *pIter==0x01 ){
   121796     pIter++;
   121797     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
   121798   }else{
   121799     iThis = 0;
   121800   }
   121801   while( iThis<iCol ){
   121802     fts3ColumnlistCopy(0, &pIter);
   121803     if( *pIter==0x00 ) return 0;
   121804     pIter++;
   121805     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
   121806   }
   121807 
   121808   return ((iCol==iThis)?pIter:0);
   121809 }
   121810 
   121811 /*
   121812 ** Free all components of the Fts3Phrase structure that were allocated by
   121813 ** the eval module. Specifically, this means to free:
   121814 **
   121815 **   * the contents of pPhrase->doclist, and
   121816 **   * any Fts3MultiSegReader objects held by phrase tokens.
   121817 */
   121818 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
   121819   if( pPhrase ){
   121820     int i;
   121821     sqlite3_free(pPhrase->doclist.aAll);
   121822     fts3EvalInvalidatePoslist(pPhrase);
   121823     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
   121824     for(i=0; i<pPhrase->nToken; i++){
   121825       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
   121826       pPhrase->aToken[i].pSegcsr = 0;
   121827     }
   121828   }
   121829 }
   121830 
   121831 /*
   121832 ** Return SQLITE_CORRUPT_VTAB.
   121833 */
   121834 #ifdef SQLITE_DEBUG
   121835 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
   121836   return SQLITE_CORRUPT_VTAB;
   121837 }
   121838 #endif
   121839 
   121840 #if !SQLITE_CORE
   121841 /*
   121842 ** Initialize API pointer table, if required.
   121843 */
   121844 SQLITE_API int sqlite3_extension_init(
   121845   sqlite3 *db,
   121846   char **pzErrMsg,
   121847   const sqlite3_api_routines *pApi
   121848 ){
   121849   SQLITE_EXTENSION_INIT2(pApi)
   121850   return sqlite3Fts3Init(db);
   121851 }
   121852 #endif
   121853 
   121854 #endif
   121855 
   121856 /************** End of fts3.c ************************************************/
   121857 /************** Begin file fts3_aux.c ****************************************/
   121858 /*
   121859 ** 2011 Jan 27
   121860 **
   121861 ** The author disclaims copyright to this source code.  In place of
   121862 ** a legal notice, here is a blessing:
   121863 **
   121864 **    May you do good and not evil.
   121865 **    May you find forgiveness for yourself and forgive others.
   121866 **    May you share freely, never taking more than you give.
   121867 **
   121868 ******************************************************************************
   121869 **
   121870 */
   121871 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   121872 
   121873 /* #include <string.h> */
   121874 /* #include <assert.h> */
   121875 
   121876 typedef struct Fts3auxTable Fts3auxTable;
   121877 typedef struct Fts3auxCursor Fts3auxCursor;
   121878 
   121879 struct Fts3auxTable {
   121880   sqlite3_vtab base;              /* Base class used by SQLite core */
   121881   Fts3Table *pFts3Tab;
   121882 };
   121883 
   121884 struct Fts3auxCursor {
   121885   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   121886   Fts3MultiSegReader csr;        /* Must be right after "base" */
   121887   Fts3SegFilter filter;
   121888   char *zStop;
   121889   int nStop;                      /* Byte-length of string zStop */
   121890   int isEof;                      /* True if cursor is at EOF */
   121891   sqlite3_int64 iRowid;           /* Current rowid */
   121892 
   121893   int iCol;                       /* Current value of 'col' column */
   121894   int nStat;                      /* Size of aStat[] array */
   121895   struct Fts3auxColstats {
   121896     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
   121897     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
   121898   } *aStat;
   121899 };
   121900 
   121901 /*
   121902 ** Schema of the terms table.
   121903 */
   121904 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
   121905 
   121906 /*
   121907 ** This function does all the work for both the xConnect and xCreate methods.
   121908 ** These tables have no persistent representation of their own, so xConnect
   121909 ** and xCreate are identical operations.
   121910 */
   121911 static int fts3auxConnectMethod(
   121912   sqlite3 *db,                    /* Database connection */
   121913   void *pUnused,                  /* Unused */
   121914   int argc,                       /* Number of elements in argv array */
   121915   const char * const *argv,       /* xCreate/xConnect argument array */
   121916   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   121917   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   121918 ){
   121919   char const *zDb;                /* Name of database (e.g. "main") */
   121920   char const *zFts3;              /* Name of fts3 table */
   121921   int nDb;                        /* Result of strlen(zDb) */
   121922   int nFts3;                      /* Result of strlen(zFts3) */
   121923   int nByte;                      /* Bytes of space to allocate here */
   121924   int rc;                         /* value returned by declare_vtab() */
   121925   Fts3auxTable *p;                /* Virtual table object to return */
   121926 
   121927   UNUSED_PARAMETER(pUnused);
   121928 
   121929   /* The user should specify a single argument - the name of an fts3 table. */
   121930   if( argc!=4 ){
   121931     *pzErr = sqlite3_mprintf(
   121932         "wrong number of arguments to fts4aux constructor"
   121933     );
   121934     return SQLITE_ERROR;
   121935   }
   121936 
   121937   zDb = argv[1];
   121938   nDb = (int)strlen(zDb);
   121939   zFts3 = argv[3];
   121940   nFts3 = (int)strlen(zFts3);
   121941 
   121942   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
   121943   if( rc!=SQLITE_OK ) return rc;
   121944 
   121945   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
   121946   p = (Fts3auxTable *)sqlite3_malloc(nByte);
   121947   if( !p ) return SQLITE_NOMEM;
   121948   memset(p, 0, nByte);
   121949 
   121950   p->pFts3Tab = (Fts3Table *)&p[1];
   121951   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
   121952   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
   121953   p->pFts3Tab->db = db;
   121954   p->pFts3Tab->nIndex = 1;
   121955 
   121956   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
   121957   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
   121958   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
   121959 
   121960   *ppVtab = (sqlite3_vtab *)p;
   121961   return SQLITE_OK;
   121962 }
   121963 
   121964 /*
   121965 ** This function does the work for both the xDisconnect and xDestroy methods.
   121966 ** These tables have no persistent representation of their own, so xDisconnect
   121967 ** and xDestroy are identical operations.
   121968 */
   121969 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
   121970   Fts3auxTable *p = (Fts3auxTable *)pVtab;
   121971   Fts3Table *pFts3 = p->pFts3Tab;
   121972   int i;
   121973 
   121974   /* Free any prepared statements held */
   121975   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
   121976     sqlite3_finalize(pFts3->aStmt[i]);
   121977   }
   121978   sqlite3_free(pFts3->zSegmentsTbl);
   121979   sqlite3_free(p);
   121980   return SQLITE_OK;
   121981 }
   121982 
   121983 #define FTS4AUX_EQ_CONSTRAINT 1
   121984 #define FTS4AUX_GE_CONSTRAINT 2
   121985 #define FTS4AUX_LE_CONSTRAINT 4
   121986 
   121987 /*
   121988 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   121989 */
   121990 static int fts3auxBestIndexMethod(
   121991   sqlite3_vtab *pVTab,
   121992   sqlite3_index_info *pInfo
   121993 ){
   121994   int i;
   121995   int iEq = -1;
   121996   int iGe = -1;
   121997   int iLe = -1;
   121998 
   121999   UNUSED_PARAMETER(pVTab);
   122000 
   122001   /* This vtab delivers always results in "ORDER BY term ASC" order. */
   122002   if( pInfo->nOrderBy==1
   122003    && pInfo->aOrderBy[0].iColumn==0
   122004    && pInfo->aOrderBy[0].desc==0
   122005   ){
   122006     pInfo->orderByConsumed = 1;
   122007   }
   122008 
   122009   /* Search for equality and range constraints on the "term" column. */
   122010   for(i=0; i<pInfo->nConstraint; i++){
   122011     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
   122012       int op = pInfo->aConstraint[i].op;
   122013       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
   122014       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
   122015       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
   122016       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
   122017       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
   122018     }
   122019   }
   122020 
   122021   if( iEq>=0 ){
   122022     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
   122023     pInfo->aConstraintUsage[iEq].argvIndex = 1;
   122024     pInfo->estimatedCost = 5;
   122025   }else{
   122026     pInfo->idxNum = 0;
   122027     pInfo->estimatedCost = 20000;
   122028     if( iGe>=0 ){
   122029       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
   122030       pInfo->aConstraintUsage[iGe].argvIndex = 1;
   122031       pInfo->estimatedCost /= 2;
   122032     }
   122033     if( iLe>=0 ){
   122034       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
   122035       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
   122036       pInfo->estimatedCost /= 2;
   122037     }
   122038   }
   122039 
   122040   return SQLITE_OK;
   122041 }
   122042 
   122043 /*
   122044 ** xOpen - Open a cursor.
   122045 */
   122046 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   122047   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
   122048 
   122049   UNUSED_PARAMETER(pVTab);
   122050 
   122051   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
   122052   if( !pCsr ) return SQLITE_NOMEM;
   122053   memset(pCsr, 0, sizeof(Fts3auxCursor));
   122054 
   122055   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   122056   return SQLITE_OK;
   122057 }
   122058 
   122059 /*
   122060 ** xClose - Close a cursor.
   122061 */
   122062 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
   122063   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122064   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122065 
   122066   sqlite3Fts3SegmentsClose(pFts3);
   122067   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   122068   sqlite3_free((void *)pCsr->filter.zTerm);
   122069   sqlite3_free(pCsr->zStop);
   122070   sqlite3_free(pCsr->aStat);
   122071   sqlite3_free(pCsr);
   122072   return SQLITE_OK;
   122073 }
   122074 
   122075 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   122076   if( nSize>pCsr->nStat ){
   122077     struct Fts3auxColstats *aNew;
   122078     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
   122079         sizeof(struct Fts3auxColstats) * nSize
   122080     );
   122081     if( aNew==0 ) return SQLITE_NOMEM;
   122082     memset(&aNew[pCsr->nStat], 0,
   122083         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
   122084     );
   122085     pCsr->aStat = aNew;
   122086     pCsr->nStat = nSize;
   122087   }
   122088   return SQLITE_OK;
   122089 }
   122090 
   122091 /*
   122092 ** xNext - Advance the cursor to the next row, if any.
   122093 */
   122094 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
   122095   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122096   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122097   int rc;
   122098 
   122099   /* Increment our pretend rowid value. */
   122100   pCsr->iRowid++;
   122101 
   122102   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
   122103     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
   122104   }
   122105 
   122106   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
   122107   if( rc==SQLITE_ROW ){
   122108     int i = 0;
   122109     int nDoclist = pCsr->csr.nDoclist;
   122110     char *aDoclist = pCsr->csr.aDoclist;
   122111     int iCol;
   122112 
   122113     int eState = 0;
   122114 
   122115     if( pCsr->zStop ){
   122116       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
   122117       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
   122118       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
   122119         pCsr->isEof = 1;
   122120         return SQLITE_OK;
   122121       }
   122122     }
   122123 
   122124     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
   122125     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
   122126     iCol = 0;
   122127 
   122128     while( i<nDoclist ){
   122129       sqlite3_int64 v = 0;
   122130 
   122131       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
   122132       switch( eState ){
   122133         /* State 0. In this state the integer just read was a docid. */
   122134         case 0:
   122135           pCsr->aStat[0].nDoc++;
   122136           eState = 1;
   122137           iCol = 0;
   122138           break;
   122139 
   122140         /* State 1. In this state we are expecting either a 1, indicating
   122141         ** that the following integer will be a column number, or the
   122142         ** start of a position list for column 0.
   122143         **
   122144         ** The only difference between state 1 and state 2 is that if the
   122145         ** integer encountered in state 1 is not 0 or 1, then we need to
   122146         ** increment the column 0 "nDoc" count for this term.
   122147         */
   122148         case 1:
   122149           assert( iCol==0 );
   122150           if( v>1 ){
   122151             pCsr->aStat[1].nDoc++;
   122152           }
   122153           eState = 2;
   122154           /* fall through */
   122155 
   122156         case 2:
   122157           if( v==0 ){       /* 0x00. Next integer will be a docid. */
   122158             eState = 0;
   122159           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
   122160             eState = 3;
   122161           }else{            /* 2 or greater. A position. */
   122162             pCsr->aStat[iCol+1].nOcc++;
   122163             pCsr->aStat[0].nOcc++;
   122164           }
   122165           break;
   122166 
   122167         /* State 3. The integer just read is a column number. */
   122168         default: assert( eState==3 );
   122169           iCol = (int)v;
   122170           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
   122171           pCsr->aStat[iCol+1].nDoc++;
   122172           eState = 2;
   122173           break;
   122174       }
   122175     }
   122176 
   122177     pCsr->iCol = 0;
   122178     rc = SQLITE_OK;
   122179   }else{
   122180     pCsr->isEof = 1;
   122181   }
   122182   return rc;
   122183 }
   122184 
   122185 /*
   122186 ** xFilter - Initialize a cursor to point at the start of its data.
   122187 */
   122188 static int fts3auxFilterMethod(
   122189   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   122190   int idxNum,                     /* Strategy index */
   122191   const char *idxStr,             /* Unused */
   122192   int nVal,                       /* Number of elements in apVal */
   122193   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   122194 ){
   122195   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122196   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122197   int rc;
   122198   int isScan;
   122199 
   122200   UNUSED_PARAMETER(nVal);
   122201   UNUSED_PARAMETER(idxStr);
   122202 
   122203   assert( idxStr==0 );
   122204   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
   122205        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
   122206        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
   122207   );
   122208   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
   122209 
   122210   /* In case this cursor is being reused, close and zero it. */
   122211   testcase(pCsr->filter.zTerm);
   122212   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   122213   sqlite3_free((void *)pCsr->filter.zTerm);
   122214   sqlite3_free(pCsr->aStat);
   122215   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
   122216 
   122217   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   122218   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
   122219 
   122220   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
   122221     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
   122222     if( zStr ){
   122223       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
   122224       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
   122225       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
   122226     }
   122227   }
   122228   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
   122229     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
   122230     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
   122231     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
   122232     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
   122233   }
   122234 
   122235   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
   122236       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
   122237   );
   122238   if( rc==SQLITE_OK ){
   122239     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
   122240   }
   122241 
   122242   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
   122243   return rc;
   122244 }
   122245 
   122246 /*
   122247 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   122248 */
   122249 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
   122250   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122251   return pCsr->isEof;
   122252 }
   122253 
   122254 /*
   122255 ** xColumn - Return a column value.
   122256 */
   122257 static int fts3auxColumnMethod(
   122258   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   122259   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
   122260   int iCol                        /* Index of column to read value from */
   122261 ){
   122262   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
   122263 
   122264   assert( p->isEof==0 );
   122265   if( iCol==0 ){        /* Column "term" */
   122266     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
   122267   }else if( iCol==1 ){  /* Column "col" */
   122268     if( p->iCol ){
   122269       sqlite3_result_int(pContext, p->iCol-1);
   122270     }else{
   122271       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
   122272     }
   122273   }else if( iCol==2 ){  /* Column "documents" */
   122274     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
   122275   }else{                /* Column "occurrences" */
   122276     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
   122277   }
   122278 
   122279   return SQLITE_OK;
   122280 }
   122281 
   122282 /*
   122283 ** xRowid - Return the current rowid for the cursor.
   122284 */
   122285 static int fts3auxRowidMethod(
   122286   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   122287   sqlite_int64 *pRowid            /* OUT: Rowid value */
   122288 ){
   122289   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122290   *pRowid = pCsr->iRowid;
   122291   return SQLITE_OK;
   122292 }
   122293 
   122294 /*
   122295 ** Register the fts3aux module with database connection db. Return SQLITE_OK
   122296 ** if successful or an error code if sqlite3_create_module() fails.
   122297 */
   122298 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
   122299   static const sqlite3_module fts3aux_module = {
   122300      0,                           /* iVersion      */
   122301      fts3auxConnectMethod,        /* xCreate       */
   122302      fts3auxConnectMethod,        /* xConnect      */
   122303      fts3auxBestIndexMethod,      /* xBestIndex    */
   122304      fts3auxDisconnectMethod,     /* xDisconnect   */
   122305      fts3auxDisconnectMethod,     /* xDestroy      */
   122306      fts3auxOpenMethod,           /* xOpen         */
   122307      fts3auxCloseMethod,          /* xClose        */
   122308      fts3auxFilterMethod,         /* xFilter       */
   122309      fts3auxNextMethod,           /* xNext         */
   122310      fts3auxEofMethod,            /* xEof          */
   122311      fts3auxColumnMethod,         /* xColumn       */
   122312      fts3auxRowidMethod,          /* xRowid        */
   122313      0,                           /* xUpdate       */
   122314      0,                           /* xBegin        */
   122315      0,                           /* xSync         */
   122316      0,                           /* xCommit       */
   122317      0,                           /* xRollback     */
   122318      0,                           /* xFindFunction */
   122319      0,                           /* xRename       */
   122320      0,                           /* xSavepoint    */
   122321      0,                           /* xRelease      */
   122322      0                            /* xRollbackTo   */
   122323   };
   122324   int rc;                         /* Return code */
   122325 
   122326   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
   122327   return rc;
   122328 }
   122329 
   122330 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   122331 
   122332 /************** End of fts3_aux.c ********************************************/
   122333 /************** Begin file fts3_expr.c ***************************************/
   122334 /*
   122335 ** 2008 Nov 28
   122336 **
   122337 ** The author disclaims copyright to this source code.  In place of
   122338 ** a legal notice, here is a blessing:
   122339 **
   122340 **    May you do good and not evil.
   122341 **    May you find forgiveness for yourself and forgive others.
   122342 **    May you share freely, never taking more than you give.
   122343 **
   122344 ******************************************************************************
   122345 **
   122346 ** This module contains code that implements a parser for fts3 query strings
   122347 ** (the right-hand argument to the MATCH operator). Because the supported
   122348 ** syntax is relatively simple, the whole tokenizer/parser system is
   122349 ** hand-coded.
   122350 */
   122351 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   122352 
   122353 /*
   122354 ** By default, this module parses the legacy syntax that has been
   122355 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   122356 ** is defined, then it uses the new syntax. The differences between
   122357 ** the new and the old syntaxes are:
   122358 **
   122359 **  a) The new syntax supports parenthesis. The old does not.
   122360 **
   122361 **  b) The new syntax supports the AND and NOT operators. The old does not.
   122362 **
   122363 **  c) The old syntax supports the "-" token qualifier. This is not
   122364 **     supported by the new syntax (it is replaced by the NOT operator).
   122365 **
   122366 **  d) When using the old syntax, the OR operator has a greater precedence
   122367 **     than an implicit AND. When using the new, both implicity and explicit
   122368 **     AND operators have a higher precedence than OR.
   122369 **
   122370 ** If compiled with SQLITE_TEST defined, then this module exports the
   122371 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   122372 ** to zero causes the module to use the old syntax. If it is set to
   122373 ** non-zero the new syntax is activated. This is so both syntaxes can
   122374 ** be tested using a single build of testfixture.
   122375 **
   122376 ** The following describes the syntax supported by the fts3 MATCH
   122377 ** operator in a similar format to that used by the lemon parser
   122378 ** generator. This module does not use actually lemon, it uses a
   122379 ** custom parser.
   122380 **
   122381 **   query ::= andexpr (OR andexpr)*.
   122382 **
   122383 **   andexpr ::= notexpr (AND? notexpr)*.
   122384 **
   122385 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   122386 **   notexpr ::= LP query RP.
   122387 **
   122388 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   122389 **
   122390 **   distance_opt ::= .
   122391 **   distance_opt ::= / INTEGER.
   122392 **
   122393 **   phrase ::= TOKEN.
   122394 **   phrase ::= COLUMN:TOKEN.
   122395 **   phrase ::= "TOKEN TOKEN TOKEN...".
   122396 */
   122397 
   122398 #ifdef SQLITE_TEST
   122399 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   122400 #else
   122401 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   122402 #  define sqlite3_fts3_enable_parentheses 1
   122403 # else
   122404 #  define sqlite3_fts3_enable_parentheses 0
   122405 # endif
   122406 #endif
   122407 
   122408 /*
   122409 ** Default span for NEAR operators.
   122410 */
   122411 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   122412 
   122413 /* #include <string.h> */
   122414 /* #include <assert.h> */
   122415 
   122416 /*
   122417 ** isNot:
   122418 **   This variable is used by function getNextNode(). When getNextNode() is
   122419 **   called, it sets ParseContext.isNot to true if the 'next node' is a
   122420 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
   122421 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
   122422 **   zero.
   122423 */
   122424 typedef struct ParseContext ParseContext;
   122425 struct ParseContext {
   122426   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   122427   int iLangid;                        /* Language id used with tokenizer */
   122428   const char **azCol;                 /* Array of column names for fts3 table */
   122429   int bFts4;                          /* True to allow FTS4-only syntax */
   122430   int nCol;                           /* Number of entries in azCol[] */
   122431   int iDefaultCol;                    /* Default column to query */
   122432   int isNot;                          /* True if getNextNode() sees a unary - */
   122433   sqlite3_context *pCtx;              /* Write error message here */
   122434   int nNest;                          /* Number of nested brackets */
   122435 };
   122436 
   122437 /*
   122438 ** This function is equivalent to the standard isspace() function.
   122439 **
   122440 ** The standard isspace() can be awkward to use safely, because although it
   122441 ** is defined to accept an argument of type int, its behaviour when passed
   122442 ** an integer that falls outside of the range of the unsigned char type
   122443 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   122444 ** is defined to accept an argument of type char, and always returns 0 for
   122445 ** any values that fall outside of the range of the unsigned char type (i.e.
   122446 ** negative values).
   122447 */
   122448 static int fts3isspace(char c){
   122449   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   122450 }
   122451 
   122452 /*
   122453 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   122454 ** zero the memory before returning a pointer to it. If unsuccessful,
   122455 ** return NULL.
   122456 */
   122457 static void *fts3MallocZero(int nByte){
   122458   void *pRet = sqlite3_malloc(nByte);
   122459   if( pRet ) memset(pRet, 0, nByte);
   122460   return pRet;
   122461 }
   122462 
   122463 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
   122464   sqlite3_tokenizer *pTokenizer,
   122465   int iLangid,
   122466   const char *z,
   122467   int n,
   122468   sqlite3_tokenizer_cursor **ppCsr
   122469 ){
   122470   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122471   sqlite3_tokenizer_cursor *pCsr = 0;
   122472   int rc;
   122473 
   122474   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
   122475   assert( rc==SQLITE_OK || pCsr==0 );
   122476   if( rc==SQLITE_OK ){
   122477     pCsr->pTokenizer = pTokenizer;
   122478     if( pModule->iVersion>=1 ){
   122479       rc = pModule->xLanguageid(pCsr, iLangid);
   122480       if( rc!=SQLITE_OK ){
   122481         pModule->xClose(pCsr);
   122482         pCsr = 0;
   122483       }
   122484     }
   122485   }
   122486   *ppCsr = pCsr;
   122487   return rc;
   122488 }
   122489 
   122490 
   122491 /*
   122492 ** Extract the next token from buffer z (length n) using the tokenizer
   122493 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   122494 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   122495 ** single token and set *ppExpr to point to it. If the end of the buffer is
   122496 ** reached before a token is found, set *ppExpr to zero. It is the
   122497 ** responsibility of the caller to eventually deallocate the allocated
   122498 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   122499 **
   122500 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   122501 ** fails.
   122502 */
   122503 static int getNextToken(
   122504   ParseContext *pParse,                   /* fts3 query parse context */
   122505   int iCol,                               /* Value for Fts3Phrase.iColumn */
   122506   const char *z, int n,                   /* Input string */
   122507   Fts3Expr **ppExpr,                      /* OUT: expression */
   122508   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122509 ){
   122510   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   122511   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122512   int rc;
   122513   sqlite3_tokenizer_cursor *pCursor;
   122514   Fts3Expr *pRet = 0;
   122515   int nConsumed = 0;
   122516 
   122517   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
   122518   if( rc==SQLITE_OK ){
   122519     const char *zToken;
   122520     int nToken, iStart, iEnd, iPosition;
   122521     int nByte;                               /* total space to allocate */
   122522 
   122523     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   122524     if( rc==SQLITE_OK ){
   122525       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   122526       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   122527       if( !pRet ){
   122528         rc = SQLITE_NOMEM;
   122529       }else{
   122530         pRet->eType = FTSQUERY_PHRASE;
   122531         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   122532         pRet->pPhrase->nToken = 1;
   122533         pRet->pPhrase->iColumn = iCol;
   122534         pRet->pPhrase->aToken[0].n = nToken;
   122535         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   122536         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   122537 
   122538         if( iEnd<n && z[iEnd]=='*' ){
   122539           pRet->pPhrase->aToken[0].isPrefix = 1;
   122540           iEnd++;
   122541         }
   122542 
   122543         while( 1 ){
   122544           if( !sqlite3_fts3_enable_parentheses
   122545            && iStart>0 && z[iStart-1]=='-'
   122546           ){
   122547             pParse->isNot = 1;
   122548             iStart--;
   122549           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
   122550             pRet->pPhrase->aToken[0].bFirst = 1;
   122551             iStart--;
   122552           }else{
   122553             break;
   122554           }
   122555         }
   122556 
   122557       }
   122558       nConsumed = iEnd;
   122559     }
   122560 
   122561     pModule->xClose(pCursor);
   122562   }
   122563 
   122564   *pnConsumed = nConsumed;
   122565   *ppExpr = pRet;
   122566   return rc;
   122567 }
   122568 
   122569 
   122570 /*
   122571 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   122572 ** then free the old allocation.
   122573 */
   122574 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   122575   void *pRet = sqlite3_realloc(pOrig, nNew);
   122576   if( !pRet ){
   122577     sqlite3_free(pOrig);
   122578   }
   122579   return pRet;
   122580 }
   122581 
   122582 /*
   122583 ** Buffer zInput, length nInput, contains the contents of a quoted string
   122584 ** that appeared as part of an fts3 query expression. Neither quote character
   122585 ** is included in the buffer. This function attempts to tokenize the entire
   122586 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   122587 ** containing the results.
   122588 **
   122589 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   122590 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   122591 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   122592 ** to 0.
   122593 */
   122594 static int getNextString(
   122595   ParseContext *pParse,                   /* fts3 query parse context */
   122596   const char *zInput, int nInput,         /* Input string */
   122597   Fts3Expr **ppExpr                       /* OUT: expression */
   122598 ){
   122599   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   122600   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122601   int rc;
   122602   Fts3Expr *p = 0;
   122603   sqlite3_tokenizer_cursor *pCursor = 0;
   122604   char *zTemp = 0;
   122605   int nTemp = 0;
   122606 
   122607   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   122608   int nToken = 0;
   122609 
   122610   /* The final Fts3Expr data structure, including the Fts3Phrase,
   122611   ** Fts3PhraseToken structures token buffers are all stored as a single
   122612   ** allocation so that the expression can be freed with a single call to
   122613   ** sqlite3_free(). Setting this up requires a two pass approach.
   122614   **
   122615   ** The first pass, in the block below, uses a tokenizer cursor to iterate
   122616   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
   122617   ** to assemble data in two dynamic buffers:
   122618   **
   122619   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
   122620   **             structure, followed by the array of Fts3PhraseToken
   122621   **             structures. This pass only populates the Fts3PhraseToken array.
   122622   **
   122623   **   Buffer zTemp: Contains copies of all tokens.
   122624   **
   122625   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
   122626   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
   122627   ** structures.
   122628   */
   122629   rc = sqlite3Fts3OpenTokenizer(
   122630       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
   122631   if( rc==SQLITE_OK ){
   122632     int ii;
   122633     for(ii=0; rc==SQLITE_OK; ii++){
   122634       const char *zByte;
   122635       int nByte, iBegin, iEnd, iPos;
   122636       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
   122637       if( rc==SQLITE_OK ){
   122638         Fts3PhraseToken *pToken;
   122639 
   122640         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
   122641         if( !p ) goto no_mem;
   122642 
   122643         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
   122644         if( !zTemp ) goto no_mem;
   122645 
   122646         assert( nToken==ii );
   122647         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
   122648         memset(pToken, 0, sizeof(Fts3PhraseToken));
   122649 
   122650         memcpy(&zTemp[nTemp], zByte, nByte);
   122651         nTemp += nByte;
   122652 
   122653         pToken->n = nByte;
   122654         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
   122655         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
   122656         nToken = ii+1;
   122657       }
   122658     }
   122659 
   122660     pModule->xClose(pCursor);
   122661     pCursor = 0;
   122662   }
   122663 
   122664   if( rc==SQLITE_DONE ){
   122665     int jj;
   122666     char *zBuf = 0;
   122667 
   122668     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
   122669     if( !p ) goto no_mem;
   122670     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
   122671     p->eType = FTSQUERY_PHRASE;
   122672     p->pPhrase = (Fts3Phrase *)&p[1];
   122673     p->pPhrase->iColumn = pParse->iDefaultCol;
   122674     p->pPhrase->nToken = nToken;
   122675 
   122676     zBuf = (char *)&p->pPhrase->aToken[nToken];
   122677     if( zTemp ){
   122678       memcpy(zBuf, zTemp, nTemp);
   122679       sqlite3_free(zTemp);
   122680     }else{
   122681       assert( nTemp==0 );
   122682     }
   122683 
   122684     for(jj=0; jj<p->pPhrase->nToken; jj++){
   122685       p->pPhrase->aToken[jj].z = zBuf;
   122686       zBuf += p->pPhrase->aToken[jj].n;
   122687     }
   122688     rc = SQLITE_OK;
   122689   }
   122690 
   122691   *ppExpr = p;
   122692   return rc;
   122693 no_mem:
   122694 
   122695   if( pCursor ){
   122696     pModule->xClose(pCursor);
   122697   }
   122698   sqlite3_free(zTemp);
   122699   sqlite3_free(p);
   122700   *ppExpr = 0;
   122701   return SQLITE_NOMEM;
   122702 }
   122703 
   122704 /*
   122705 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   122706 ** call fts3ExprParse(). So this forward declaration is required.
   122707 */
   122708 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   122709 
   122710 /*
   122711 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   122712 ** structure, or set to 0 if the end of the input buffer is reached.
   122713 **
   122714 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   122715 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   122716 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   122717 */
   122718 static int getNextNode(
   122719   ParseContext *pParse,                   /* fts3 query parse context */
   122720   const char *z, int n,                   /* Input string */
   122721   Fts3Expr **ppExpr,                      /* OUT: expression */
   122722   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122723 ){
   122724   static const struct Fts3Keyword {
   122725     char *z;                              /* Keyword text */
   122726     unsigned char n;                      /* Length of the keyword */
   122727     unsigned char parenOnly;              /* Only valid in paren mode */
   122728     unsigned char eType;                  /* Keyword code */
   122729   } aKeyword[] = {
   122730     { "OR" ,  2, 0, FTSQUERY_OR   },
   122731     { "AND",  3, 1, FTSQUERY_AND  },
   122732     { "NOT",  3, 1, FTSQUERY_NOT  },
   122733     { "NEAR", 4, 0, FTSQUERY_NEAR }
   122734   };
   122735   int ii;
   122736   int iCol;
   122737   int iColLen;
   122738   int rc;
   122739   Fts3Expr *pRet = 0;
   122740 
   122741   const char *zInput = z;
   122742   int nInput = n;
   122743 
   122744   pParse->isNot = 0;
   122745 
   122746   /* Skip over any whitespace before checking for a keyword, an open or
   122747   ** close bracket, or a quoted string.
   122748   */
   122749   while( nInput>0 && fts3isspace(*zInput) ){
   122750     nInput--;
   122751     zInput++;
   122752   }
   122753   if( nInput==0 ){
   122754     return SQLITE_DONE;
   122755   }
   122756 
   122757   /* See if we are dealing with a keyword. */
   122758   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   122759     const struct Fts3Keyword *pKey = &aKeyword[ii];
   122760 
   122761     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   122762       continue;
   122763     }
   122764 
   122765     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   122766       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   122767       int nKey = pKey->n;
   122768       char cNext;
   122769 
   122770       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   122771       if( pKey->eType==FTSQUERY_NEAR ){
   122772         assert( nKey==4 );
   122773         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   122774           nNear = 0;
   122775           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   122776             nNear = nNear * 10 + (zInput[nKey] - '0');
   122777           }
   122778         }
   122779       }
   122780 
   122781       /* At this point this is probably a keyword. But for that to be true,
   122782       ** the next byte must contain either whitespace, an open or close
   122783       ** parenthesis, a quote character, or EOF.
   122784       */
   122785       cNext = zInput[nKey];
   122786       if( fts3isspace(cNext)
   122787        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   122788       ){
   122789         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   122790         if( !pRet ){
   122791           return SQLITE_NOMEM;
   122792         }
   122793         pRet->eType = pKey->eType;
   122794         pRet->nNear = nNear;
   122795         *ppExpr = pRet;
   122796         *pnConsumed = (int)((zInput - z) + nKey);
   122797         return SQLITE_OK;
   122798       }
   122799 
   122800       /* Turns out that wasn't a keyword after all. This happens if the
   122801       ** user has supplied a token such as "ORacle". Continue.
   122802       */
   122803     }
   122804   }
   122805 
   122806   /* Check for an open bracket. */
   122807   if( sqlite3_fts3_enable_parentheses ){
   122808     if( *zInput=='(' ){
   122809       int nConsumed;
   122810       pParse->nNest++;
   122811       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
   122812       if( rc==SQLITE_OK && !*ppExpr ){
   122813         rc = SQLITE_DONE;
   122814       }
   122815       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
   122816       return rc;
   122817     }
   122818 
   122819     /* Check for a close bracket. */
   122820     if( *zInput==')' ){
   122821       pParse->nNest--;
   122822       *pnConsumed = (int)((zInput - z) + 1);
   122823       return SQLITE_DONE;
   122824     }
   122825   }
   122826 
   122827   /* See if we are dealing with a quoted phrase. If this is the case, then
   122828   ** search for the closing quote and pass the whole string to getNextString()
   122829   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   122830   ** a quote character embedded in a string.
   122831   */
   122832   if( *zInput=='"' ){
   122833     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   122834     *pnConsumed = (int)((zInput - z) + ii + 1);
   122835     if( ii==nInput ){
   122836       return SQLITE_ERROR;
   122837     }
   122838     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   122839   }
   122840 
   122841 
   122842   /* If control flows to this point, this must be a regular token, or
   122843   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   122844   ** interface. Before doing so, figure out if there is an explicit
   122845   ** column specifier for the token.
   122846   **
   122847   ** TODO: Strangely, it is not possible to associate a column specifier
   122848   ** with a quoted phrase, only with a single token. Not sure if this was
   122849   ** an implementation artifact or an intentional decision when fts3 was
   122850   ** first implemented. Whichever it was, this module duplicates the
   122851   ** limitation.
   122852   */
   122853   iCol = pParse->iDefaultCol;
   122854   iColLen = 0;
   122855   for(ii=0; ii<pParse->nCol; ii++){
   122856     const char *zStr = pParse->azCol[ii];
   122857     int nStr = (int)strlen(zStr);
   122858     if( nInput>nStr && zInput[nStr]==':'
   122859      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   122860     ){
   122861       iCol = ii;
   122862       iColLen = (int)((zInput - z) + nStr + 1);
   122863       break;
   122864     }
   122865   }
   122866   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   122867   *pnConsumed += iColLen;
   122868   return rc;
   122869 }
   122870 
   122871 /*
   122872 ** The argument is an Fts3Expr structure for a binary operator (any type
   122873 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   122874 ** precedence of the operator. Lower values have a higher precedence (i.e.
   122875 ** group more tightly). For example, in the C language, the == operator
   122876 ** groups more tightly than ||, and would therefore have a higher precedence.
   122877 **
   122878 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   122879 ** is defined), the order of the operators in precedence from highest to
   122880 ** lowest is:
   122881 **
   122882 **   NEAR
   122883 **   NOT
   122884 **   AND (including implicit ANDs)
   122885 **   OR
   122886 **
   122887 ** Note that when using the old query syntax, the OR operator has a higher
   122888 ** precedence than the AND operator.
   122889 */
   122890 static int opPrecedence(Fts3Expr *p){
   122891   assert( p->eType!=FTSQUERY_PHRASE );
   122892   if( sqlite3_fts3_enable_parentheses ){
   122893     return p->eType;
   122894   }else if( p->eType==FTSQUERY_NEAR ){
   122895     return 1;
   122896   }else if( p->eType==FTSQUERY_OR ){
   122897     return 2;
   122898   }
   122899   assert( p->eType==FTSQUERY_AND );
   122900   return 3;
   122901 }
   122902 
   122903 /*
   122904 ** Argument ppHead contains a pointer to the current head of a query
   122905 ** expression tree being parsed. pPrev is the expression node most recently
   122906 ** inserted into the tree. This function adds pNew, which is always a binary
   122907 ** operator node, into the expression tree based on the relative precedence
   122908 ** of pNew and the existing nodes of the tree. This may result in the head
   122909 ** of the tree changing, in which case *ppHead is set to the new root node.
   122910 */
   122911 static void insertBinaryOperator(
   122912   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   122913   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   122914   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   122915 ){
   122916   Fts3Expr *pSplit = pPrev;
   122917   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   122918     pSplit = pSplit->pParent;
   122919   }
   122920 
   122921   if( pSplit->pParent ){
   122922     assert( pSplit->pParent->pRight==pSplit );
   122923     pSplit->pParent->pRight = pNew;
   122924     pNew->pParent = pSplit->pParent;
   122925   }else{
   122926     *ppHead = pNew;
   122927   }
   122928   pNew->pLeft = pSplit;
   122929   pSplit->pParent = pNew;
   122930 }
   122931 
   122932 /*
   122933 ** Parse the fts3 query expression found in buffer z, length n. This function
   122934 ** returns either when the end of the buffer is reached or an unmatched
   122935 ** closing bracket - ')' - is encountered.
   122936 **
   122937 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   122938 ** parsed form of the expression and *pnConsumed is set to the number of
   122939 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   122940 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   122941 */
   122942 static int fts3ExprParse(
   122943   ParseContext *pParse,                   /* fts3 query parse context */
   122944   const char *z, int n,                   /* Text of MATCH query */
   122945   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   122946   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122947 ){
   122948   Fts3Expr *pRet = 0;
   122949   Fts3Expr *pPrev = 0;
   122950   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   122951   int nIn = n;
   122952   const char *zIn = z;
   122953   int rc = SQLITE_OK;
   122954   int isRequirePhrase = 1;
   122955 
   122956   while( rc==SQLITE_OK ){
   122957     Fts3Expr *p = 0;
   122958     int nByte = 0;
   122959     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   122960     if( rc==SQLITE_OK ){
   122961       int isPhrase;
   122962 
   122963       if( !sqlite3_fts3_enable_parentheses
   122964        && p->eType==FTSQUERY_PHRASE && pParse->isNot
   122965       ){
   122966         /* Create an implicit NOT operator. */
   122967         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   122968         if( !pNot ){
   122969           sqlite3Fts3ExprFree(p);
   122970           rc = SQLITE_NOMEM;
   122971           goto exprparse_out;
   122972         }
   122973         pNot->eType = FTSQUERY_NOT;
   122974         pNot->pRight = p;
   122975         if( pNotBranch ){
   122976           pNot->pLeft = pNotBranch;
   122977         }
   122978         pNotBranch = pNot;
   122979         p = pPrev;
   122980       }else{
   122981         int eType = p->eType;
   122982         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   122983 
   122984         /* The isRequirePhrase variable is set to true if a phrase or
   122985         ** an expression contained in parenthesis is required. If a
   122986         ** binary operator (AND, OR, NOT or NEAR) is encounted when
   122987         ** isRequirePhrase is set, this is a syntax error.
   122988         */
   122989         if( !isPhrase && isRequirePhrase ){
   122990           sqlite3Fts3ExprFree(p);
   122991           rc = SQLITE_ERROR;
   122992           goto exprparse_out;
   122993         }
   122994 
   122995         if( isPhrase && !isRequirePhrase ){
   122996           /* Insert an implicit AND operator. */
   122997           Fts3Expr *pAnd;
   122998           assert( pRet && pPrev );
   122999           pAnd = fts3MallocZero(sizeof(Fts3Expr));
   123000           if( !pAnd ){
   123001             sqlite3Fts3ExprFree(p);
   123002             rc = SQLITE_NOMEM;
   123003             goto exprparse_out;
   123004           }
   123005           pAnd->eType = FTSQUERY_AND;
   123006           insertBinaryOperator(&pRet, pPrev, pAnd);
   123007           pPrev = pAnd;
   123008         }
   123009 
   123010         /* This test catches attempts to make either operand of a NEAR
   123011         ** operator something other than a phrase. For example, either of
   123012         ** the following:
   123013         **
   123014         **    (bracketed expression) NEAR phrase
   123015         **    phrase NEAR (bracketed expression)
   123016         **
   123017         ** Return an error in either case.
   123018         */
   123019         if( pPrev && (
   123020             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   123021          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   123022         )){
   123023           sqlite3Fts3ExprFree(p);
   123024           rc = SQLITE_ERROR;
   123025           goto exprparse_out;
   123026         }
   123027 
   123028         if( isPhrase ){
   123029           if( pRet ){
   123030             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   123031             pPrev->pRight = p;
   123032             p->pParent = pPrev;
   123033           }else{
   123034             pRet = p;
   123035           }
   123036         }else{
   123037           insertBinaryOperator(&pRet, pPrev, p);
   123038         }
   123039         isRequirePhrase = !isPhrase;
   123040       }
   123041       assert( nByte>0 );
   123042     }
   123043     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   123044     nIn -= nByte;
   123045     zIn += nByte;
   123046     pPrev = p;
   123047   }
   123048 
   123049   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   123050     rc = SQLITE_ERROR;
   123051   }
   123052 
   123053   if( rc==SQLITE_DONE ){
   123054     rc = SQLITE_OK;
   123055     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   123056       if( !pRet ){
   123057         rc = SQLITE_ERROR;
   123058       }else{
   123059         Fts3Expr *pIter = pNotBranch;
   123060         while( pIter->pLeft ){
   123061           pIter = pIter->pLeft;
   123062         }
   123063         pIter->pLeft = pRet;
   123064         pRet = pNotBranch;
   123065       }
   123066     }
   123067   }
   123068   *pnConsumed = n - nIn;
   123069 
   123070 exprparse_out:
   123071   if( rc!=SQLITE_OK ){
   123072     sqlite3Fts3ExprFree(pRet);
   123073     sqlite3Fts3ExprFree(pNotBranch);
   123074     pRet = 0;
   123075   }
   123076   *ppExpr = pRet;
   123077   return rc;
   123078 }
   123079 
   123080 /*
   123081 ** Parameters z and n contain a pointer to and length of a buffer containing
   123082 ** an fts3 query expression, respectively. This function attempts to parse the
   123083 ** query expression and create a tree of Fts3Expr structures representing the
   123084 ** parsed expression. If successful, *ppExpr is set to point to the head
   123085 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   123086 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   123087 ** error) is returned and *ppExpr is set to 0.
   123088 **
   123089 ** If parameter n is a negative number, then z is assumed to point to a
   123090 ** nul-terminated string and the length is determined using strlen().
   123091 **
   123092 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   123093 ** use to normalize query tokens while parsing the expression. The azCol[]
   123094 ** array, which is assumed to contain nCol entries, should contain the names
   123095 ** of each column in the target fts3 table, in order from left to right.
   123096 ** Column names must be nul-terminated strings.
   123097 **
   123098 ** The iDefaultCol parameter should be passed the index of the table column
   123099 ** that appears on the left-hand-side of the MATCH operator (the default
   123100 ** column to match against for tokens for which a column name is not explicitly
   123101 ** specified as part of the query string), or -1 if tokens may by default
   123102 ** match any table column.
   123103 */
   123104 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   123105   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   123106   int iLangid,                        /* Language id for tokenizer */
   123107   char **azCol,                       /* Array of column names for fts3 table */
   123108   int bFts4,                          /* True to allow FTS4-only syntax */
   123109   int nCol,                           /* Number of entries in azCol[] */
   123110   int iDefaultCol,                    /* Default column to query */
   123111   const char *z, int n,               /* Text of MATCH query */
   123112   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   123113 ){
   123114   int nParsed;
   123115   int rc;
   123116   ParseContext sParse;
   123117 
   123118   memset(&sParse, 0, sizeof(ParseContext));
   123119   sParse.pTokenizer = pTokenizer;
   123120   sParse.iLangid = iLangid;
   123121   sParse.azCol = (const char **)azCol;
   123122   sParse.nCol = nCol;
   123123   sParse.iDefaultCol = iDefaultCol;
   123124   sParse.bFts4 = bFts4;
   123125   if( z==0 ){
   123126     *ppExpr = 0;
   123127     return SQLITE_OK;
   123128   }
   123129   if( n<0 ){
   123130     n = (int)strlen(z);
   123131   }
   123132   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   123133 
   123134   /* Check for mismatched parenthesis */
   123135   if( rc==SQLITE_OK && sParse.nNest ){
   123136     rc = SQLITE_ERROR;
   123137     sqlite3Fts3ExprFree(*ppExpr);
   123138     *ppExpr = 0;
   123139   }
   123140 
   123141   return rc;
   123142 }
   123143 
   123144 /*
   123145 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   123146 */
   123147 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
   123148   if( p ){
   123149     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
   123150     sqlite3Fts3ExprFree(p->pLeft);
   123151     sqlite3Fts3ExprFree(p->pRight);
   123152     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
   123153     sqlite3_free(p->aMI);
   123154     sqlite3_free(p);
   123155   }
   123156 }
   123157 
   123158 /****************************************************************************
   123159 *****************************************************************************
   123160 ** Everything after this point is just test code.
   123161 */
   123162 
   123163 #ifdef SQLITE_TEST
   123164 
   123165 /* #include <stdio.h> */
   123166 
   123167 /*
   123168 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   123169 */
   123170 static int queryTestTokenizer(
   123171   sqlite3 *db,
   123172   const char *zName,
   123173   const sqlite3_tokenizer_module **pp
   123174 ){
   123175   int rc;
   123176   sqlite3_stmt *pStmt;
   123177   const char zSql[] = "SELECT fts3_tokenizer(?)";
   123178 
   123179   *pp = 0;
   123180   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   123181   if( rc!=SQLITE_OK ){
   123182     return rc;
   123183   }
   123184 
   123185   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   123186   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   123187     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   123188       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   123189     }
   123190   }
   123191 
   123192   return sqlite3_finalize(pStmt);
   123193 }
   123194 
   123195 /*
   123196 ** Return a pointer to a buffer containing a text representation of the
   123197 ** expression passed as the first argument. The buffer is obtained from
   123198 ** sqlite3_malloc(). It is the responsibility of the caller to use
   123199 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   123200 ** NULL is returned.
   123201 **
   123202 ** If the second argument is not NULL, then its contents are prepended to
   123203 ** the returned expression text and then freed using sqlite3_free().
   123204 */
   123205 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   123206   switch( pExpr->eType ){
   123207     case FTSQUERY_PHRASE: {
   123208       Fts3Phrase *pPhrase = pExpr->pPhrase;
   123209       int i;
   123210       zBuf = sqlite3_mprintf(
   123211           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
   123212       for(i=0; zBuf && i<pPhrase->nToken; i++){
   123213         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   123214             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   123215             (pPhrase->aToken[i].isPrefix?"+":"")
   123216         );
   123217       }
   123218       return zBuf;
   123219     }
   123220 
   123221     case FTSQUERY_NEAR:
   123222       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   123223       break;
   123224     case FTSQUERY_NOT:
   123225       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   123226       break;
   123227     case FTSQUERY_AND:
   123228       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   123229       break;
   123230     case FTSQUERY_OR:
   123231       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   123232       break;
   123233   }
   123234 
   123235   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   123236   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   123237   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   123238 
   123239   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   123240   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   123241 
   123242   return zBuf;
   123243 }
   123244 
   123245 /*
   123246 ** This is the implementation of a scalar SQL function used to test the
   123247 ** expression parser. It should be called as follows:
   123248 **
   123249 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   123250 **
   123251 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   123252 ** to parse the query expression (see README.tokenizers). The second argument
   123253 ** is the query expression to parse. Each subsequent argument is the name
   123254 ** of a column of the fts3 table that the query expression may refer to.
   123255 ** For example:
   123256 **
   123257 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   123258 */
   123259 static void fts3ExprTest(
   123260   sqlite3_context *context,
   123261   int argc,
   123262   sqlite3_value **argv
   123263 ){
   123264   sqlite3_tokenizer_module const *pModule = 0;
   123265   sqlite3_tokenizer *pTokenizer = 0;
   123266   int rc;
   123267   char **azCol = 0;
   123268   const char *zExpr;
   123269   int nExpr;
   123270   int nCol;
   123271   int ii;
   123272   Fts3Expr *pExpr;
   123273   char *zBuf = 0;
   123274   sqlite3 *db = sqlite3_context_db_handle(context);
   123275 
   123276   if( argc<3 ){
   123277     sqlite3_result_error(context,
   123278         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   123279     );
   123280     return;
   123281   }
   123282 
   123283   rc = queryTestTokenizer(db,
   123284                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   123285   if( rc==SQLITE_NOMEM ){
   123286     sqlite3_result_error_nomem(context);
   123287     goto exprtest_out;
   123288   }else if( !pModule ){
   123289     sqlite3_result_error(context, "No such tokenizer module", -1);
   123290     goto exprtest_out;
   123291   }
   123292 
   123293   rc = pModule->xCreate(0, 0, &pTokenizer);
   123294   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   123295   if( rc==SQLITE_NOMEM ){
   123296     sqlite3_result_error_nomem(context);
   123297     goto exprtest_out;
   123298   }
   123299   pTokenizer->pModule = pModule;
   123300 
   123301   zExpr = (const char *)sqlite3_value_text(argv[1]);
   123302   nExpr = sqlite3_value_bytes(argv[1]);
   123303   nCol = argc-2;
   123304   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   123305   if( !azCol ){
   123306     sqlite3_result_error_nomem(context);
   123307     goto exprtest_out;
   123308   }
   123309   for(ii=0; ii<nCol; ii++){
   123310     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   123311   }
   123312 
   123313   rc = sqlite3Fts3ExprParse(
   123314       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
   123315   );
   123316   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   123317     sqlite3_result_error(context, "Error parsing expression", -1);
   123318   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   123319     sqlite3_result_error_nomem(context);
   123320   }else{
   123321     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   123322     sqlite3_free(zBuf);
   123323   }
   123324 
   123325   sqlite3Fts3ExprFree(pExpr);
   123326 
   123327 exprtest_out:
   123328   if( pModule && pTokenizer ){
   123329     rc = pModule->xDestroy(pTokenizer);
   123330   }
   123331   sqlite3_free(azCol);
   123332 }
   123333 
   123334 /*
   123335 ** Register the query expression parser test function fts3_exprtest()
   123336 ** with database connection db.
   123337 */
   123338 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   123339   return sqlite3_create_function(
   123340       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   123341   );
   123342 }
   123343 
   123344 #endif
   123345 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   123346 
   123347 /************** End of fts3_expr.c *******************************************/
   123348 /************** Begin file fts3_hash.c ***************************************/
   123349 /*
   123350 ** 2001 September 22
   123351 **
   123352 ** The author disclaims copyright to this source code.  In place of
   123353 ** a legal notice, here is a blessing:
   123354 **
   123355 **    May you do good and not evil.
   123356 **    May you find forgiveness for yourself and forgive others.
   123357 **    May you share freely, never taking more than you give.
   123358 **
   123359 *************************************************************************
   123360 ** This is the implementation of generic hash-tables used in SQLite.
   123361 ** We've modified it slightly to serve as a standalone hash table
   123362 ** implementation for the full-text indexing module.
   123363 */
   123364 
   123365 /*
   123366 ** The code in this file is only compiled if:
   123367 **
   123368 **     * The FTS3 module is being built as an extension
   123369 **       (in which case SQLITE_CORE is not defined), or
   123370 **
   123371 **     * The FTS3 module is being built into the core of
   123372 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   123373 */
   123374 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   123375 
   123376 /* #include <assert.h> */
   123377 /* #include <stdlib.h> */
   123378 /* #include <string.h> */
   123379 
   123380 
   123381 /*
   123382 ** Malloc and Free functions
   123383 */
   123384 static void *fts3HashMalloc(int n){
   123385   void *p = sqlite3_malloc(n);
   123386   if( p ){
   123387     memset(p, 0, n);
   123388   }
   123389   return p;
   123390 }
   123391 static void fts3HashFree(void *p){
   123392   sqlite3_free(p);
   123393 }
   123394 
   123395 /* Turn bulk memory into a hash table object by initializing the
   123396 ** fields of the Hash structure.
   123397 **
   123398 ** "pNew" is a pointer to the hash table that is to be initialized.
   123399 ** keyClass is one of the constants
   123400 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   123401 ** determines what kind of key the hash table will use.  "copyKey" is
   123402 ** true if the hash table should make its own private copy of keys and
   123403 ** false if it should just use the supplied pointer.
   123404 */
   123405 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   123406   assert( pNew!=0 );
   123407   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   123408   pNew->keyClass = keyClass;
   123409   pNew->copyKey = copyKey;
   123410   pNew->first = 0;
   123411   pNew->count = 0;
   123412   pNew->htsize = 0;
   123413   pNew->ht = 0;
   123414 }
   123415 
   123416 /* Remove all entries from a hash table.  Reclaim all memory.
   123417 ** Call this routine to delete a hash table or to reset a hash table
   123418 ** to the empty state.
   123419 */
   123420 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   123421   Fts3HashElem *elem;         /* For looping over all elements of the table */
   123422 
   123423   assert( pH!=0 );
   123424   elem = pH->first;
   123425   pH->first = 0;
   123426   fts3HashFree(pH->ht);
   123427   pH->ht = 0;
   123428   pH->htsize = 0;
   123429   while( elem ){
   123430     Fts3HashElem *next_elem = elem->next;
   123431     if( pH->copyKey && elem->pKey ){
   123432       fts3HashFree(elem->pKey);
   123433     }
   123434     fts3HashFree(elem);
   123435     elem = next_elem;
   123436   }
   123437   pH->count = 0;
   123438 }
   123439 
   123440 /*
   123441 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   123442 */
   123443 static int fts3StrHash(const void *pKey, int nKey){
   123444   const char *z = (const char *)pKey;
   123445   int h = 0;
   123446   if( nKey<=0 ) nKey = (int) strlen(z);
   123447   while( nKey > 0  ){
   123448     h = (h<<3) ^ h ^ *z++;
   123449     nKey--;
   123450   }
   123451   return h & 0x7fffffff;
   123452 }
   123453 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   123454   if( n1!=n2 ) return 1;
   123455   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   123456 }
   123457 
   123458 /*
   123459 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   123460 */
   123461 static int fts3BinHash(const void *pKey, int nKey){
   123462   int h = 0;
   123463   const char *z = (const char *)pKey;
   123464   while( nKey-- > 0 ){
   123465     h = (h<<3) ^ h ^ *(z++);
   123466   }
   123467   return h & 0x7fffffff;
   123468 }
   123469 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   123470   if( n1!=n2 ) return 1;
   123471   return memcmp(pKey1,pKey2,n1);
   123472 }
   123473 
   123474 /*
   123475 ** Return a pointer to the appropriate hash function given the key class.
   123476 **
   123477 ** The C syntax in this function definition may be unfamilar to some
   123478 ** programmers, so we provide the following additional explanation:
   123479 **
   123480 ** The name of the function is "ftsHashFunction".  The function takes a
   123481 ** single parameter "keyClass".  The return value of ftsHashFunction()
   123482 ** is a pointer to another function.  Specifically, the return value
   123483 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   123484 ** with types "const void*" and "int" and returns an "int".
   123485 */
   123486 static int (*ftsHashFunction(int keyClass))(const void*,int){
   123487   if( keyClass==FTS3_HASH_STRING ){
   123488     return &fts3StrHash;
   123489   }else{
   123490     assert( keyClass==FTS3_HASH_BINARY );
   123491     return &fts3BinHash;
   123492   }
   123493 }
   123494 
   123495 /*
   123496 ** Return a pointer to the appropriate hash function given the key class.
   123497 **
   123498 ** For help in interpreted the obscure C code in the function definition,
   123499 ** see the header comment on the previous function.
   123500 */
   123501 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   123502   if( keyClass==FTS3_HASH_STRING ){
   123503     return &fts3StrCompare;
   123504   }else{
   123505     assert( keyClass==FTS3_HASH_BINARY );
   123506     return &fts3BinCompare;
   123507   }
   123508 }
   123509 
   123510 /* Link an element into the hash table
   123511 */
   123512 static void fts3HashInsertElement(
   123513   Fts3Hash *pH,            /* The complete hash table */
   123514   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   123515   Fts3HashElem *pNew       /* The element to be inserted */
   123516 ){
   123517   Fts3HashElem *pHead;     /* First element already in pEntry */
   123518   pHead = pEntry->chain;
   123519   if( pHead ){
   123520     pNew->next = pHead;
   123521     pNew->prev = pHead->prev;
   123522     if( pHead->prev ){ pHead->prev->next = pNew; }
   123523     else             { pH->first = pNew; }
   123524     pHead->prev = pNew;
   123525   }else{
   123526     pNew->next = pH->first;
   123527     if( pH->first ){ pH->first->prev = pNew; }
   123528     pNew->prev = 0;
   123529     pH->first = pNew;
   123530   }
   123531   pEntry->count++;
   123532   pEntry->chain = pNew;
   123533 }
   123534 
   123535 
   123536 /* Resize the hash table so that it cantains "new_size" buckets.
   123537 ** "new_size" must be a power of 2.  The hash table might fail
   123538 ** to resize if sqliteMalloc() fails.
   123539 **
   123540 ** Return non-zero if a memory allocation error occurs.
   123541 */
   123542 static int fts3Rehash(Fts3Hash *pH, int new_size){
   123543   struct _fts3ht *new_ht;          /* The new hash table */
   123544   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   123545   int (*xHash)(const void*,int);   /* The hash function */
   123546 
   123547   assert( (new_size & (new_size-1))==0 );
   123548   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   123549   if( new_ht==0 ) return 1;
   123550   fts3HashFree(pH->ht);
   123551   pH->ht = new_ht;
   123552   pH->htsize = new_size;
   123553   xHash = ftsHashFunction(pH->keyClass);
   123554   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   123555     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   123556     next_elem = elem->next;
   123557     fts3HashInsertElement(pH, &new_ht[h], elem);
   123558   }
   123559   return 0;
   123560 }
   123561 
   123562 /* This function (for internal use only) locates an element in an
   123563 ** hash table that matches the given key.  The hash for this key has
   123564 ** already been computed and is passed as the 4th parameter.
   123565 */
   123566 static Fts3HashElem *fts3FindElementByHash(
   123567   const Fts3Hash *pH, /* The pH to be searched */
   123568   const void *pKey,   /* The key we are searching for */
   123569   int nKey,
   123570   int h               /* The hash for this key. */
   123571 ){
   123572   Fts3HashElem *elem;            /* Used to loop thru the element list */
   123573   int count;                     /* Number of elements left to test */
   123574   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   123575 
   123576   if( pH->ht ){
   123577     struct _fts3ht *pEntry = &pH->ht[h];
   123578     elem = pEntry->chain;
   123579     count = pEntry->count;
   123580     xCompare = ftsCompareFunction(pH->keyClass);
   123581     while( count-- && elem ){
   123582       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   123583         return elem;
   123584       }
   123585       elem = elem->next;
   123586     }
   123587   }
   123588   return 0;
   123589 }
   123590 
   123591 /* Remove a single entry from the hash table given a pointer to that
   123592 ** element and a hash on the element's key.
   123593 */
   123594 static void fts3RemoveElementByHash(
   123595   Fts3Hash *pH,         /* The pH containing "elem" */
   123596   Fts3HashElem* elem,   /* The element to be removed from the pH */
   123597   int h                 /* Hash value for the element */
   123598 ){
   123599   struct _fts3ht *pEntry;
   123600   if( elem->prev ){
   123601     elem->prev->next = elem->next;
   123602   }else{
   123603     pH->first = elem->next;
   123604   }
   123605   if( elem->next ){
   123606     elem->next->prev = elem->prev;
   123607   }
   123608   pEntry = &pH->ht[h];
   123609   if( pEntry->chain==elem ){
   123610     pEntry->chain = elem->next;
   123611   }
   123612   pEntry->count--;
   123613   if( pEntry->count<=0 ){
   123614     pEntry->chain = 0;
   123615   }
   123616   if( pH->copyKey && elem->pKey ){
   123617     fts3HashFree(elem->pKey);
   123618   }
   123619   fts3HashFree( elem );
   123620   pH->count--;
   123621   if( pH->count<=0 ){
   123622     assert( pH->first==0 );
   123623     assert( pH->count==0 );
   123624     fts3HashClear(pH);
   123625   }
   123626 }
   123627 
   123628 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   123629   const Fts3Hash *pH,
   123630   const void *pKey,
   123631   int nKey
   123632 ){
   123633   int h;                          /* A hash on key */
   123634   int (*xHash)(const void*,int);  /* The hash function */
   123635 
   123636   if( pH==0 || pH->ht==0 ) return 0;
   123637   xHash = ftsHashFunction(pH->keyClass);
   123638   assert( xHash!=0 );
   123639   h = (*xHash)(pKey,nKey);
   123640   assert( (pH->htsize & (pH->htsize-1))==0 );
   123641   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   123642 }
   123643 
   123644 /*
   123645 ** Attempt to locate an element of the hash table pH with a key
   123646 ** that matches pKey,nKey.  Return the data for this element if it is
   123647 ** found, or NULL if there is no match.
   123648 */
   123649 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   123650   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   123651 
   123652   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   123653   return pElem ? pElem->data : 0;
   123654 }
   123655 
   123656 /* Insert an element into the hash table pH.  The key is pKey,nKey
   123657 ** and the data is "data".
   123658 **
   123659 ** If no element exists with a matching key, then a new
   123660 ** element is created.  A copy of the key is made if the copyKey
   123661 ** flag is set.  NULL is returned.
   123662 **
   123663 ** If another element already exists with the same key, then the
   123664 ** new data replaces the old data and the old data is returned.
   123665 ** The key is not copied in this instance.  If a malloc fails, then
   123666 ** the new data is returned and the hash table is unchanged.
   123667 **
   123668 ** If the "data" parameter to this function is NULL, then the
   123669 ** element corresponding to "key" is removed from the hash table.
   123670 */
   123671 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   123672   Fts3Hash *pH,        /* The hash table to insert into */
   123673   const void *pKey,    /* The key */
   123674   int nKey,            /* Number of bytes in the key */
   123675   void *data           /* The data */
   123676 ){
   123677   int hraw;                 /* Raw hash value of the key */
   123678   int h;                    /* the hash of the key modulo hash table size */
   123679   Fts3HashElem *elem;       /* Used to loop thru the element list */
   123680   Fts3HashElem *new_elem;   /* New element added to the pH */
   123681   int (*xHash)(const void*,int);  /* The hash function */
   123682 
   123683   assert( pH!=0 );
   123684   xHash = ftsHashFunction(pH->keyClass);
   123685   assert( xHash!=0 );
   123686   hraw = (*xHash)(pKey, nKey);
   123687   assert( (pH->htsize & (pH->htsize-1))==0 );
   123688   h = hraw & (pH->htsize-1);
   123689   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   123690   if( elem ){
   123691     void *old_data = elem->data;
   123692     if( data==0 ){
   123693       fts3RemoveElementByHash(pH,elem,h);
   123694     }else{
   123695       elem->data = data;
   123696     }
   123697     return old_data;
   123698   }
   123699   if( data==0 ) return 0;
   123700   if( (pH->htsize==0 && fts3Rehash(pH,8))
   123701    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   123702   ){
   123703     pH->count = 0;
   123704     return data;
   123705   }
   123706   assert( pH->htsize>0 );
   123707   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   123708   if( new_elem==0 ) return data;
   123709   if( pH->copyKey && pKey!=0 ){
   123710     new_elem->pKey = fts3HashMalloc( nKey );
   123711     if( new_elem->pKey==0 ){
   123712       fts3HashFree(new_elem);
   123713       return data;
   123714     }
   123715     memcpy((void*)new_elem->pKey, pKey, nKey);
   123716   }else{
   123717     new_elem->pKey = (void*)pKey;
   123718   }
   123719   new_elem->nKey = nKey;
   123720   pH->count++;
   123721   assert( pH->htsize>0 );
   123722   assert( (pH->htsize & (pH->htsize-1))==0 );
   123723   h = hraw & (pH->htsize-1);
   123724   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   123725   new_elem->data = data;
   123726   return 0;
   123727 }
   123728 
   123729 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   123730 
   123731 /************** End of fts3_hash.c *******************************************/
   123732 /************** Begin file fts3_porter.c *************************************/
   123733 /*
   123734 ** 2006 September 30
   123735 **
   123736 ** The author disclaims copyright to this source code.  In place of
   123737 ** a legal notice, here is a blessing:
   123738 **
   123739 **    May you do good and not evil.
   123740 **    May you find forgiveness for yourself and forgive others.
   123741 **    May you share freely, never taking more than you give.
   123742 **
   123743 *************************************************************************
   123744 ** Implementation of the full-text-search tokenizer that implements
   123745 ** a Porter stemmer.
   123746 */
   123747 
   123748 /*
   123749 ** The code in this file is only compiled if:
   123750 **
   123751 **     * The FTS3 module is being built as an extension
   123752 **       (in which case SQLITE_CORE is not defined), or
   123753 **
   123754 **     * The FTS3 module is being built into the core of
   123755 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   123756 */
   123757 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   123758 
   123759 /* #include <assert.h> */
   123760 /* #include <stdlib.h> */
   123761 /* #include <stdio.h> */
   123762 /* #include <string.h> */
   123763 
   123764 
   123765 /*
   123766 ** Class derived from sqlite3_tokenizer
   123767 */
   123768 typedef struct porter_tokenizer {
   123769   sqlite3_tokenizer base;      /* Base class */
   123770 } porter_tokenizer;
   123771 
   123772 /*
   123773 ** Class derived from sqlite3_tokenizer_cursor
   123774 */
   123775 typedef struct porter_tokenizer_cursor {
   123776   sqlite3_tokenizer_cursor base;
   123777   const char *zInput;          /* input we are tokenizing */
   123778   int nInput;                  /* size of the input */
   123779   int iOffset;                 /* current position in zInput */
   123780   int iToken;                  /* index of next token to be returned */
   123781   char *zToken;                /* storage for current token */
   123782   int nAllocated;              /* space allocated to zToken buffer */
   123783 } porter_tokenizer_cursor;
   123784 
   123785 
   123786 /*
   123787 ** Create a new tokenizer instance.
   123788 */
   123789 static int porterCreate(
   123790   int argc, const char * const *argv,
   123791   sqlite3_tokenizer **ppTokenizer
   123792 ){
   123793   porter_tokenizer *t;
   123794 
   123795   UNUSED_PARAMETER(argc);
   123796   UNUSED_PARAMETER(argv);
   123797 
   123798   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   123799   if( t==NULL ) return SQLITE_NOMEM;
   123800   memset(t, 0, sizeof(*t));
   123801   *ppTokenizer = &t->base;
   123802   return SQLITE_OK;
   123803 }
   123804 
   123805 /*
   123806 ** Destroy a tokenizer
   123807 */
   123808 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   123809   sqlite3_free(pTokenizer);
   123810   return SQLITE_OK;
   123811 }
   123812 
   123813 /*
   123814 ** Prepare to begin tokenizing a particular string.  The input
   123815 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   123816 ** used to incrementally tokenize this string is returned in
   123817 ** *ppCursor.
   123818 */
   123819 static int porterOpen(
   123820   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   123821   const char *zInput, int nInput,        /* String to be tokenized */
   123822   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   123823 ){
   123824   porter_tokenizer_cursor *c;
   123825 
   123826   UNUSED_PARAMETER(pTokenizer);
   123827 
   123828   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   123829   if( c==NULL ) return SQLITE_NOMEM;
   123830 
   123831   c->zInput = zInput;
   123832   if( zInput==0 ){
   123833     c->nInput = 0;
   123834   }else if( nInput<0 ){
   123835     c->nInput = (int)strlen(zInput);
   123836   }else{
   123837     c->nInput = nInput;
   123838   }
   123839   c->iOffset = 0;                 /* start tokenizing at the beginning */
   123840   c->iToken = 0;
   123841   c->zToken = NULL;               /* no space allocated, yet. */
   123842   c->nAllocated = 0;
   123843 
   123844   *ppCursor = &c->base;
   123845   return SQLITE_OK;
   123846 }
   123847 
   123848 /*
   123849 ** Close a tokenization cursor previously opened by a call to
   123850 ** porterOpen() above.
   123851 */
   123852 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   123853   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   123854   sqlite3_free(c->zToken);
   123855   sqlite3_free(c);
   123856   return SQLITE_OK;
   123857 }
   123858 /*
   123859 ** Vowel or consonant
   123860 */
   123861 static const char cType[] = {
   123862    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   123863    1, 1, 1, 2, 1
   123864 };
   123865 
   123866 /*
   123867 ** isConsonant() and isVowel() determine if their first character in
   123868 ** the string they point to is a consonant or a vowel, according
   123869 ** to Porter ruls.
   123870 **
   123871 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   123872 ** 'Y' is a consonant unless it follows another consonant,
   123873 ** in which case it is a vowel.
   123874 **
   123875 ** In these routine, the letters are in reverse order.  So the 'y' rule
   123876 ** is that 'y' is a consonant unless it is followed by another
   123877 ** consonent.
   123878 */
   123879 static int isVowel(const char*);
   123880 static int isConsonant(const char *z){
   123881   int j;
   123882   char x = *z;
   123883   if( x==0 ) return 0;
   123884   assert( x>='a' && x<='z' );
   123885   j = cType[x-'a'];
   123886   if( j<2 ) return j;
   123887   return z[1]==0 || isVowel(z + 1);
   123888 }
   123889 static int isVowel(const char *z){
   123890   int j;
   123891   char x = *z;
   123892   if( x==0 ) return 0;
   123893   assert( x>='a' && x<='z' );
   123894   j = cType[x-'a'];
   123895   if( j<2 ) return 1-j;
   123896   return isConsonant(z + 1);
   123897 }
   123898 
   123899 /*
   123900 ** Let any sequence of one or more vowels be represented by V and let
   123901 ** C be sequence of one or more consonants.  Then every word can be
   123902 ** represented as:
   123903 **
   123904 **           [C] (VC){m} [V]
   123905 **
   123906 ** In prose:  A word is an optional consonant followed by zero or
   123907 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   123908 ** number of vowel consonant pairs.  This routine computes the value
   123909 ** of m for the first i bytes of a word.
   123910 **
   123911 ** Return true if the m-value for z is 1 or more.  In other words,
   123912 ** return true if z contains at least one vowel that is followed
   123913 ** by a consonant.
   123914 **
   123915 ** In this routine z[] is in reverse order.  So we are really looking
   123916 ** for an instance of of a consonant followed by a vowel.
   123917 */
   123918 static int m_gt_0(const char *z){
   123919   while( isVowel(z) ){ z++; }
   123920   if( *z==0 ) return 0;
   123921   while( isConsonant(z) ){ z++; }
   123922   return *z!=0;
   123923 }
   123924 
   123925 /* Like mgt0 above except we are looking for a value of m which is
   123926 ** exactly 1
   123927 */
   123928 static int m_eq_1(const char *z){
   123929   while( isVowel(z) ){ z++; }
   123930   if( *z==0 ) return 0;
   123931   while( isConsonant(z) ){ z++; }
   123932   if( *z==0 ) return 0;
   123933   while( isVowel(z) ){ z++; }
   123934   if( *z==0 ) return 1;
   123935   while( isConsonant(z) ){ z++; }
   123936   return *z==0;
   123937 }
   123938 
   123939 /* Like mgt0 above except we are looking for a value of m>1 instead
   123940 ** or m>0
   123941 */
   123942 static int m_gt_1(const char *z){
   123943   while( isVowel(z) ){ z++; }
   123944   if( *z==0 ) return 0;
   123945   while( isConsonant(z) ){ z++; }
   123946   if( *z==0 ) return 0;
   123947   while( isVowel(z) ){ z++; }
   123948   if( *z==0 ) return 0;
   123949   while( isConsonant(z) ){ z++; }
   123950   return *z!=0;
   123951 }
   123952 
   123953 /*
   123954 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   123955 */
   123956 static int hasVowel(const char *z){
   123957   while( isConsonant(z) ){ z++; }
   123958   return *z!=0;
   123959 }
   123960 
   123961 /*
   123962 ** Return TRUE if the word ends in a double consonant.
   123963 **
   123964 ** The text is reversed here. So we are really looking at
   123965 ** the first two characters of z[].
   123966 */
   123967 static int doubleConsonant(const char *z){
   123968   return isConsonant(z) && z[0]==z[1];
   123969 }
   123970 
   123971 /*
   123972 ** Return TRUE if the word ends with three letters which
   123973 ** are consonant-vowel-consonent and where the final consonant
   123974 ** is not 'w', 'x', or 'y'.
   123975 **
   123976 ** The word is reversed here.  So we are really checking the
   123977 ** first three letters and the first one cannot be in [wxy].
   123978 */
   123979 static int star_oh(const char *z){
   123980   return
   123981     isConsonant(z) &&
   123982     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   123983     isVowel(z+1) &&
   123984     isConsonant(z+2);
   123985 }
   123986 
   123987 /*
   123988 ** If the word ends with zFrom and xCond() is true for the stem
   123989 ** of the word that preceeds the zFrom ending, then change the
   123990 ** ending to zTo.
   123991 **
   123992 ** The input word *pz and zFrom are both in reverse order.  zTo
   123993 ** is in normal order.
   123994 **
   123995 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   123996 ** match.  Not that TRUE is returned even if xCond() fails and
   123997 ** no substitution occurs.
   123998 */
   123999 static int stem(
   124000   char **pz,             /* The word being stemmed (Reversed) */
   124001   const char *zFrom,     /* If the ending matches this... (Reversed) */
   124002   const char *zTo,       /* ... change the ending to this (not reversed) */
   124003   int (*xCond)(const char*)   /* Condition that must be true */
   124004 ){
   124005   char *z = *pz;
   124006   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   124007   if( *zFrom!=0 ) return 0;
   124008   if( xCond && !xCond(z) ) return 1;
   124009   while( *zTo ){
   124010     *(--z) = *(zTo++);
   124011   }
   124012   *pz = z;
   124013   return 1;
   124014 }
   124015 
   124016 /*
   124017 ** This is the fallback stemmer used when the porter stemmer is
   124018 ** inappropriate.  The input word is copied into the output with
   124019 ** US-ASCII case folding.  If the input word is too long (more
   124020 ** than 20 bytes if it contains no digits or more than 6 bytes if
   124021 ** it contains digits) then word is truncated to 20 or 6 bytes
   124022 ** by taking 10 or 3 bytes from the beginning and end.
   124023 */
   124024 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   124025   int i, mx, j;
   124026   int hasDigit = 0;
   124027   for(i=0; i<nIn; i++){
   124028     char c = zIn[i];
   124029     if( c>='A' && c<='Z' ){
   124030       zOut[i] = c - 'A' + 'a';
   124031     }else{
   124032       if( c>='0' && c<='9' ) hasDigit = 1;
   124033       zOut[i] = c;
   124034     }
   124035   }
   124036   mx = hasDigit ? 3 : 10;
   124037   if( nIn>mx*2 ){
   124038     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   124039       zOut[j] = zOut[i];
   124040     }
   124041     i = j;
   124042   }
   124043   zOut[i] = 0;
   124044   *pnOut = i;
   124045 }
   124046 
   124047 
   124048 /*
   124049 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   124050 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   124051 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   124052 **
   124053 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   124054 ** are converted to lower case.  Upper-case UTF characters are
   124055 ** unchanged.
   124056 **
   124057 ** Words that are longer than about 20 bytes are stemmed by retaining
   124058 ** a few bytes from the beginning and the end of the word.  If the
   124059 ** word contains digits, 3 bytes are taken from the beginning and
   124060 ** 3 bytes from the end.  For long words without digits, 10 bytes
   124061 ** are taken from each end.  US-ASCII case folding still applies.
   124062 **
   124063 ** If the input word contains not digits but does characters not
   124064 ** in [a-zA-Z] then no stemming is attempted and this routine just
   124065 ** copies the input into the input into the output with US-ASCII
   124066 ** case folding.
   124067 **
   124068 ** Stemming never increases the length of the word.  So there is
   124069 ** no chance of overflowing the zOut buffer.
   124070 */
   124071 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   124072   int i, j;
   124073   char zReverse[28];
   124074   char *z, *z2;
   124075   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   124076     /* The word is too big or too small for the porter stemmer.
   124077     ** Fallback to the copy stemmer */
   124078     copy_stemmer(zIn, nIn, zOut, pnOut);
   124079     return;
   124080   }
   124081   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   124082     char c = zIn[i];
   124083     if( c>='A' && c<='Z' ){
   124084       zReverse[j] = c + 'a' - 'A';
   124085     }else if( c>='a' && c<='z' ){
   124086       zReverse[j] = c;
   124087     }else{
   124088       /* The use of a character not in [a-zA-Z] means that we fallback
   124089       ** to the copy stemmer */
   124090       copy_stemmer(zIn, nIn, zOut, pnOut);
   124091       return;
   124092     }
   124093   }
   124094   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   124095   z = &zReverse[j+1];
   124096 
   124097 
   124098   /* Step 1a */
   124099   if( z[0]=='s' ){
   124100     if(
   124101      !stem(&z, "sess", "ss", 0) &&
   124102      !stem(&z, "sei", "i", 0)  &&
   124103      !stem(&z, "ss", "ss", 0)
   124104     ){
   124105       z++;
   124106     }
   124107   }
   124108 
   124109   /* Step 1b */
   124110   z2 = z;
   124111   if( stem(&z, "dee", "ee", m_gt_0) ){
   124112     /* Do nothing.  The work was all in the test */
   124113   }else if(
   124114      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   124115       && z!=z2
   124116   ){
   124117      if( stem(&z, "ta", "ate", 0) ||
   124118          stem(&z, "lb", "ble", 0) ||
   124119          stem(&z, "zi", "ize", 0) ){
   124120        /* Do nothing.  The work was all in the test */
   124121      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   124122        z++;
   124123      }else if( m_eq_1(z) && star_oh(z) ){
   124124        *(--z) = 'e';
   124125      }
   124126   }
   124127 
   124128   /* Step 1c */
   124129   if( z[0]=='y' && hasVowel(z+1) ){
   124130     z[0] = 'i';
   124131   }
   124132 
   124133   /* Step 2 */
   124134   switch( z[1] ){
   124135    case 'a':
   124136      stem(&z, "lanoita", "ate", m_gt_0) ||
   124137      stem(&z, "lanoit", "tion", m_gt_0);
   124138      break;
   124139    case 'c':
   124140      stem(&z, "icne", "ence", m_gt_0) ||
   124141      stem(&z, "icna", "ance", m_gt_0);
   124142      break;
   124143    case 'e':
   124144      stem(&z, "rezi", "ize", m_gt_0);
   124145      break;
   124146    case 'g':
   124147      stem(&z, "igol", "log", m_gt_0);
   124148      break;
   124149    case 'l':
   124150      stem(&z, "ilb", "ble", m_gt_0) ||
   124151      stem(&z, "illa", "al", m_gt_0) ||
   124152      stem(&z, "iltne", "ent", m_gt_0) ||
   124153      stem(&z, "ile", "e", m_gt_0) ||
   124154      stem(&z, "ilsuo", "ous", m_gt_0);
   124155      break;
   124156    case 'o':
   124157      stem(&z, "noitazi", "ize", m_gt_0) ||
   124158      stem(&z, "noita", "ate", m_gt_0) ||
   124159      stem(&z, "rota", "ate", m_gt_0);
   124160      break;
   124161    case 's':
   124162      stem(&z, "msila", "al", m_gt_0) ||
   124163      stem(&z, "ssenevi", "ive", m_gt_0) ||
   124164      stem(&z, "ssenluf", "ful", m_gt_0) ||
   124165      stem(&z, "ssensuo", "ous", m_gt_0);
   124166      break;
   124167    case 't':
   124168      stem(&z, "itila", "al", m_gt_0) ||
   124169      stem(&z, "itivi", "ive", m_gt_0) ||
   124170      stem(&z, "itilib", "ble", m_gt_0);
   124171      break;
   124172   }
   124173 
   124174   /* Step 3 */
   124175   switch( z[0] ){
   124176    case 'e':
   124177      stem(&z, "etaci", "ic", m_gt_0) ||
   124178      stem(&z, "evita", "", m_gt_0)   ||
   124179      stem(&z, "ezila", "al", m_gt_0);
   124180      break;
   124181    case 'i':
   124182      stem(&z, "itici", "ic", m_gt_0);
   124183      break;
   124184    case 'l':
   124185      stem(&z, "laci", "ic", m_gt_0) ||
   124186      stem(&z, "luf", "", m_gt_0);
   124187      break;
   124188    case 's':
   124189      stem(&z, "ssen", "", m_gt_0);
   124190      break;
   124191   }
   124192 
   124193   /* Step 4 */
   124194   switch( z[1] ){
   124195    case 'a':
   124196      if( z[0]=='l' && m_gt_1(z+2) ){
   124197        z += 2;
   124198      }
   124199      break;
   124200    case 'c':
   124201      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   124202        z += 4;
   124203      }
   124204      break;
   124205    case 'e':
   124206      if( z[0]=='r' && m_gt_1(z+2) ){
   124207        z += 2;
   124208      }
   124209      break;
   124210    case 'i':
   124211      if( z[0]=='c' && m_gt_1(z+2) ){
   124212        z += 2;
   124213      }
   124214      break;
   124215    case 'l':
   124216      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   124217        z += 4;
   124218      }
   124219      break;
   124220    case 'n':
   124221      if( z[0]=='t' ){
   124222        if( z[2]=='a' ){
   124223          if( m_gt_1(z+3) ){
   124224            z += 3;
   124225          }
   124226        }else if( z[2]=='e' ){
   124227          stem(&z, "tneme", "", m_gt_1) ||
   124228          stem(&z, "tnem", "", m_gt_1) ||
   124229          stem(&z, "tne", "", m_gt_1);
   124230        }
   124231      }
   124232      break;
   124233    case 'o':
   124234      if( z[0]=='u' ){
   124235        if( m_gt_1(z+2) ){
   124236          z += 2;
   124237        }
   124238      }else if( z[3]=='s' || z[3]=='t' ){
   124239        stem(&z, "noi", "", m_gt_1);
   124240      }
   124241      break;
   124242    case 's':
   124243      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   124244        z += 3;
   124245      }
   124246      break;
   124247    case 't':
   124248      stem(&z, "eta", "", m_gt_1) ||
   124249      stem(&z, "iti", "", m_gt_1);
   124250      break;
   124251    case 'u':
   124252      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   124253        z += 3;
   124254      }
   124255      break;
   124256    case 'v':
   124257    case 'z':
   124258      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   124259        z += 3;
   124260      }
   124261      break;
   124262   }
   124263 
   124264   /* Step 5a */
   124265   if( z[0]=='e' ){
   124266     if( m_gt_1(z+1) ){
   124267       z++;
   124268     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   124269       z++;
   124270     }
   124271   }
   124272 
   124273   /* Step 5b */
   124274   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   124275     z++;
   124276   }
   124277 
   124278   /* z[] is now the stemmed word in reverse order.  Flip it back
   124279   ** around into forward order and return.
   124280   */
   124281   *pnOut = i = (int)strlen(z);
   124282   zOut[i] = 0;
   124283   while( *z ){
   124284     zOut[--i] = *(z++);
   124285   }
   124286 }
   124287 
   124288 /*
   124289 ** Characters that can be part of a token.  We assume any character
   124290 ** whose value is greater than 0x80 (any UTF character) can be
   124291 ** part of a token.  In other words, delimiters all must have
   124292 ** values of 0x7f or lower.
   124293 */
   124294 static const char porterIdChar[] = {
   124295 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   124296     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   124297     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   124298     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   124299     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   124300     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   124301 };
   124302 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   124303 
   124304 /*
   124305 ** Extract the next token from a tokenization cursor.  The cursor must
   124306 ** have been opened by a prior call to porterOpen().
   124307 */
   124308 static int porterNext(
   124309   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   124310   const char **pzToken,               /* OUT: *pzToken is the token text */
   124311   int *pnBytes,                       /* OUT: Number of bytes in token */
   124312   int *piStartOffset,                 /* OUT: Starting offset of token */
   124313   int *piEndOffset,                   /* OUT: Ending offset of token */
   124314   int *piPosition                     /* OUT: Position integer of token */
   124315 ){
   124316   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   124317   const char *z = c->zInput;
   124318 
   124319   while( c->iOffset<c->nInput ){
   124320     int iStartOffset, ch;
   124321 
   124322     /* Scan past delimiter characters */
   124323     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   124324       c->iOffset++;
   124325     }
   124326 
   124327     /* Count non-delimiter characters. */
   124328     iStartOffset = c->iOffset;
   124329     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   124330       c->iOffset++;
   124331     }
   124332 
   124333     if( c->iOffset>iStartOffset ){
   124334       int n = c->iOffset-iStartOffset;
   124335       if( n>c->nAllocated ){
   124336         char *pNew;
   124337         c->nAllocated = n+20;
   124338         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   124339         if( !pNew ) return SQLITE_NOMEM;
   124340         c->zToken = pNew;
   124341       }
   124342       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   124343       *pzToken = c->zToken;
   124344       *piStartOffset = iStartOffset;
   124345       *piEndOffset = c->iOffset;
   124346       *piPosition = c->iToken++;
   124347       return SQLITE_OK;
   124348     }
   124349   }
   124350   return SQLITE_DONE;
   124351 }
   124352 
   124353 /*
   124354 ** The set of routines that implement the porter-stemmer tokenizer
   124355 */
   124356 static const sqlite3_tokenizer_module porterTokenizerModule = {
   124357   0,
   124358   porterCreate,
   124359   porterDestroy,
   124360   porterOpen,
   124361   porterClose,
   124362   porterNext,
   124363   0
   124364 };
   124365 
   124366 /*
   124367 ** Allocate a new porter tokenizer.  Return a pointer to the new
   124368 ** tokenizer in *ppModule
   124369 */
   124370 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   124371   sqlite3_tokenizer_module const**ppModule
   124372 ){
   124373   *ppModule = &porterTokenizerModule;
   124374 }
   124375 
   124376 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   124377 
   124378 /************** End of fts3_porter.c *****************************************/
   124379 /************** Begin file fts3_tokenizer.c **********************************/
   124380 /*
   124381 ** 2007 June 22
   124382 **
   124383 ** The author disclaims copyright to this source code.  In place of
   124384 ** a legal notice, here is a blessing:
   124385 **
   124386 **    May you do good and not evil.
   124387 **    May you find forgiveness for yourself and forgive others.
   124388 **    May you share freely, never taking more than you give.
   124389 **
   124390 ******************************************************************************
   124391 **
   124392 ** This is part of an SQLite module implementing full-text search.
   124393 ** This particular file implements the generic tokenizer interface.
   124394 */
   124395 
   124396 /*
   124397 ** The code in this file is only compiled if:
   124398 **
   124399 **     * The FTS3 module is being built as an extension
   124400 **       (in which case SQLITE_CORE is not defined), or
   124401 **
   124402 **     * The FTS3 module is being built into the core of
   124403 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   124404 */
   124405 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   124406 
   124407 /* #include <assert.h> */
   124408 /* #include <string.h> */
   124409 
   124410 /*
   124411 ** Implementation of the SQL scalar function for accessing the underlying
   124412 ** hash table. This function may be called as follows:
   124413 **
   124414 **   SELECT <function-name>(<key-name>);
   124415 **   SELECT <function-name>(<key-name>, <pointer>);
   124416 **
   124417 ** where <function-name> is the name passed as the second argument
   124418 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   124419 **
   124420 ** If the <pointer> argument is specified, it must be a blob value
   124421 ** containing a pointer to be stored as the hash data corresponding
   124422 ** to the string <key-name>. If <pointer> is not specified, then
   124423 ** the string <key-name> must already exist in the has table. Otherwise,
   124424 ** an error is returned.
   124425 **
   124426 ** Whether or not the <pointer> argument is specified, the value returned
   124427 ** is a blob containing the pointer stored as the hash data corresponding
   124428 ** to string <key-name> (after the hash-table is updated, if applicable).
   124429 */
   124430 static void scalarFunc(
   124431   sqlite3_context *context,
   124432   int argc,
   124433   sqlite3_value **argv
   124434 ){
   124435   Fts3Hash *pHash;
   124436   void *pPtr = 0;
   124437   const unsigned char *zName;
   124438   int nName;
   124439 
   124440   assert( argc==1 || argc==2 );
   124441 
   124442   pHash = (Fts3Hash *)sqlite3_user_data(context);
   124443 
   124444   zName = sqlite3_value_text(argv[0]);
   124445   nName = sqlite3_value_bytes(argv[0])+1;
   124446 
   124447   if( argc==2 ){
   124448     void *pOld;
   124449     int n = sqlite3_value_bytes(argv[1]);
   124450     if( n!=sizeof(pPtr) ){
   124451       sqlite3_result_error(context, "argument type mismatch", -1);
   124452       return;
   124453     }
   124454     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   124455     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   124456     if( pOld==pPtr ){
   124457       sqlite3_result_error(context, "out of memory", -1);
   124458       return;
   124459     }
   124460   }else{
   124461     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   124462     if( !pPtr ){
   124463       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   124464       sqlite3_result_error(context, zErr, -1);
   124465       sqlite3_free(zErr);
   124466       return;
   124467     }
   124468   }
   124469 
   124470   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   124471 }
   124472 
   124473 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   124474   static const char isFtsIdChar[] = {
   124475       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   124476       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   124477       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   124478       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   124479       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   124480       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   124481       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   124482       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   124483   };
   124484   return (c&0x80 || isFtsIdChar[(int)(c)]);
   124485 }
   124486 
   124487 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   124488   const char *z1;
   124489   const char *z2 = 0;
   124490 
   124491   /* Find the start of the next token. */
   124492   z1 = zStr;
   124493   while( z2==0 ){
   124494     char c = *z1;
   124495     switch( c ){
   124496       case '\0': return 0;        /* No more tokens here */
   124497       case '\'':
   124498       case '"':
   124499       case '`': {
   124500         z2 = z1;
   124501         while( *++z2 && (*z2!=c || *++z2==c) );
   124502         break;
   124503       }
   124504       case '[':
   124505         z2 = &z1[1];
   124506         while( *z2 && z2[0]!=']' ) z2++;
   124507         if( *z2 ) z2++;
   124508         break;
   124509 
   124510       default:
   124511         if( sqlite3Fts3IsIdChar(*z1) ){
   124512           z2 = &z1[1];
   124513           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   124514         }else{
   124515           z1++;
   124516         }
   124517     }
   124518   }
   124519 
   124520   *pn = (int)(z2-z1);
   124521   return z1;
   124522 }
   124523 
   124524 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   124525   Fts3Hash *pHash,                /* Tokenizer hash table */
   124526   const char *zArg,               /* Tokenizer name */
   124527   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   124528   char **pzErr                    /* OUT: Set to malloced error message */
   124529 ){
   124530   int rc;
   124531   char *z = (char *)zArg;
   124532   int n = 0;
   124533   char *zCopy;
   124534   char *zEnd;                     /* Pointer to nul-term of zCopy */
   124535   sqlite3_tokenizer_module *m;
   124536 
   124537   zCopy = sqlite3_mprintf("%s", zArg);
   124538   if( !zCopy ) return SQLITE_NOMEM;
   124539   zEnd = &zCopy[strlen(zCopy)];
   124540 
   124541   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   124542   z[n] = '\0';
   124543   sqlite3Fts3Dequote(z);
   124544 
   124545   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   124546   if( !m ){
   124547     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   124548     rc = SQLITE_ERROR;
   124549   }else{
   124550     char const **aArg = 0;
   124551     int iArg = 0;
   124552     z = &z[n+1];
   124553     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   124554       int nNew = sizeof(char *)*(iArg+1);
   124555       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   124556       if( !aNew ){
   124557         sqlite3_free(zCopy);
   124558         sqlite3_free((void *)aArg);
   124559         return SQLITE_NOMEM;
   124560       }
   124561       aArg = aNew;
   124562       aArg[iArg++] = z;
   124563       z[n] = '\0';
   124564       sqlite3Fts3Dequote(z);
   124565       z = &z[n+1];
   124566     }
   124567     rc = m->xCreate(iArg, aArg, ppTok);
   124568     assert( rc!=SQLITE_OK || *ppTok );
   124569     if( rc!=SQLITE_OK ){
   124570       *pzErr = sqlite3_mprintf("unknown tokenizer");
   124571     }else{
   124572       (*ppTok)->pModule = m;
   124573     }
   124574     sqlite3_free((void *)aArg);
   124575   }
   124576 
   124577   sqlite3_free(zCopy);
   124578   return rc;
   124579 }
   124580 
   124581 
   124582 #ifdef SQLITE_TEST
   124583 
   124584 /* #include <tcl.h> */
   124585 /* #include <string.h> */
   124586 
   124587 /*
   124588 ** Implementation of a special SQL scalar function for testing tokenizers
   124589 ** designed to be used in concert with the Tcl testing framework. This
   124590 ** function must be called with two arguments:
   124591 **
   124592 **   SELECT <function-name>(<key-name>, <input-string>);
   124593 **   SELECT <function-name>(<key-name>, <pointer>);
   124594 **
   124595 ** where <function-name> is the name passed as the second argument
   124596 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   124597 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   124598 **
   124599 ** The return value is a string that may be interpreted as a Tcl
   124600 ** list. For each token in the <input-string>, three elements are
   124601 ** added to the returned list. The first is the token position, the
   124602 ** second is the token text (folded, stemmed, etc.) and the third is the
   124603 ** substring of <input-string> associated with the token. For example,
   124604 ** using the built-in "simple" tokenizer:
   124605 **
   124606 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   124607 **
   124608 ** will return the string:
   124609 **
   124610 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   124611 **
   124612 */
   124613 static void testFunc(
   124614   sqlite3_context *context,
   124615   int argc,
   124616   sqlite3_value **argv
   124617 ){
   124618   Fts3Hash *pHash;
   124619   sqlite3_tokenizer_module *p;
   124620   sqlite3_tokenizer *pTokenizer = 0;
   124621   sqlite3_tokenizer_cursor *pCsr = 0;
   124622 
   124623   const char *zErr = 0;
   124624 
   124625   const char *zName;
   124626   int nName;
   124627   const char *zInput;
   124628   int nInput;
   124629 
   124630   const char *zArg = 0;
   124631 
   124632   const char *zToken;
   124633   int nToken;
   124634   int iStart;
   124635   int iEnd;
   124636   int iPos;
   124637 
   124638   Tcl_Obj *pRet;
   124639 
   124640   assert( argc==2 || argc==3 );
   124641 
   124642   nName = sqlite3_value_bytes(argv[0]);
   124643   zName = (const char *)sqlite3_value_text(argv[0]);
   124644   nInput = sqlite3_value_bytes(argv[argc-1]);
   124645   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   124646 
   124647   if( argc==3 ){
   124648     zArg = (const char *)sqlite3_value_text(argv[1]);
   124649   }
   124650 
   124651   pHash = (Fts3Hash *)sqlite3_user_data(context);
   124652   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   124653 
   124654   if( !p ){
   124655     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   124656     sqlite3_result_error(context, zErr, -1);
   124657     sqlite3_free(zErr);
   124658     return;
   124659   }
   124660 
   124661   pRet = Tcl_NewObj();
   124662   Tcl_IncrRefCount(pRet);
   124663 
   124664   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
   124665     zErr = "error in xCreate()";
   124666     goto finish;
   124667   }
   124668   pTokenizer->pModule = p;
   124669   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
   124670     zErr = "error in xOpen()";
   124671     goto finish;
   124672   }
   124673 
   124674   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   124675     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   124676     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   124677     zToken = &zInput[iStart];
   124678     nToken = iEnd-iStart;
   124679     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   124680   }
   124681 
   124682   if( SQLITE_OK!=p->xClose(pCsr) ){
   124683     zErr = "error in xClose()";
   124684     goto finish;
   124685   }
   124686   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   124687     zErr = "error in xDestroy()";
   124688     goto finish;
   124689   }
   124690 
   124691 finish:
   124692   if( zErr ){
   124693     sqlite3_result_error(context, zErr, -1);
   124694   }else{
   124695     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   124696   }
   124697   Tcl_DecrRefCount(pRet);
   124698 }
   124699 
   124700 static
   124701 int registerTokenizer(
   124702   sqlite3 *db,
   124703   char *zName,
   124704   const sqlite3_tokenizer_module *p
   124705 ){
   124706   int rc;
   124707   sqlite3_stmt *pStmt;
   124708   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   124709 
   124710   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   124711   if( rc!=SQLITE_OK ){
   124712     return rc;
   124713   }
   124714 
   124715   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   124716   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   124717   sqlite3_step(pStmt);
   124718 
   124719   return sqlite3_finalize(pStmt);
   124720 }
   124721 
   124722 static
   124723 int queryTokenizer(
   124724   sqlite3 *db,
   124725   char *zName,
   124726   const sqlite3_tokenizer_module **pp
   124727 ){
   124728   int rc;
   124729   sqlite3_stmt *pStmt;
   124730   const char zSql[] = "SELECT fts3_tokenizer(?)";
   124731 
   124732   *pp = 0;
   124733   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   124734   if( rc!=SQLITE_OK ){
   124735     return rc;
   124736   }
   124737 
   124738   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   124739   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   124740     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   124741       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   124742     }
   124743   }
   124744 
   124745   return sqlite3_finalize(pStmt);
   124746 }
   124747 
   124748 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   124749 
   124750 /*
   124751 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   124752 ** This function is used for testing only, it is not included in the
   124753 ** build unless SQLITE_TEST is defined.
   124754 **
   124755 ** The purpose of this is to test that the fts3_tokenizer() function
   124756 ** can be used as designed by the C-code in the queryTokenizer and
   124757 ** registerTokenizer() functions above. These two functions are repeated
   124758 ** in the README.tokenizer file as an example, so it is important to
   124759 ** test them.
   124760 **
   124761 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   124762 ** function with no arguments. An assert() will fail if a problem is
   124763 ** detected. i.e.:
   124764 **
   124765 **     SELECT fts3_tokenizer_internal_test();
   124766 **
   124767 */
   124768 static void intTestFunc(
   124769   sqlite3_context *context,
   124770   int argc,
   124771   sqlite3_value **argv
   124772 ){
   124773   int rc;
   124774   const sqlite3_tokenizer_module *p1;
   124775   const sqlite3_tokenizer_module *p2;
   124776   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   124777 
   124778   UNUSED_PARAMETER(argc);
   124779   UNUSED_PARAMETER(argv);
   124780 
   124781   /* Test the query function */
   124782   sqlite3Fts3SimpleTokenizerModule(&p1);
   124783   rc = queryTokenizer(db, "simple", &p2);
   124784   assert( rc==SQLITE_OK );
   124785   assert( p1==p2 );
   124786   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   124787   assert( rc==SQLITE_ERROR );
   124788   assert( p2==0 );
   124789   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   124790 
   124791   /* Test the storage function */
   124792   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   124793   assert( rc==SQLITE_OK );
   124794   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   124795   assert( rc==SQLITE_OK );
   124796   assert( p2==p1 );
   124797 
   124798   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   124799 }
   124800 
   124801 #endif
   124802 
   124803 /*
   124804 ** Set up SQL objects in database db used to access the contents of
   124805 ** the hash table pointed to by argument pHash. The hash table must
   124806 ** been initialised to use string keys, and to take a private copy
   124807 ** of the key when a value is inserted. i.e. by a call similar to:
   124808 **
   124809 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   124810 **
   124811 ** This function adds a scalar function (see header comment above
   124812 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   124813 ** defined at compilation time, a temporary virtual table (see header
   124814 ** comment above struct HashTableVtab) to the database schema. Both
   124815 ** provide read/write access to the contents of *pHash.
   124816 **
   124817 ** The third argument to this function, zName, is used as the name
   124818 ** of both the scalar and, if created, the virtual table.
   124819 */
   124820 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   124821   sqlite3 *db,
   124822   Fts3Hash *pHash,
   124823   const char *zName
   124824 ){
   124825   int rc = SQLITE_OK;
   124826   void *p = (void *)pHash;
   124827   const int any = SQLITE_ANY;
   124828 
   124829 #ifdef SQLITE_TEST
   124830   char *zTest = 0;
   124831   char *zTest2 = 0;
   124832   void *pdb = (void *)db;
   124833   zTest = sqlite3_mprintf("%s_test", zName);
   124834   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   124835   if( !zTest || !zTest2 ){
   124836     rc = SQLITE_NOMEM;
   124837   }
   124838 #endif
   124839 
   124840   if( SQLITE_OK==rc ){
   124841     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
   124842   }
   124843   if( SQLITE_OK==rc ){
   124844     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
   124845   }
   124846 #ifdef SQLITE_TEST
   124847   if( SQLITE_OK==rc ){
   124848     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
   124849   }
   124850   if( SQLITE_OK==rc ){
   124851     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
   124852   }
   124853   if( SQLITE_OK==rc ){
   124854     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   124855   }
   124856 #endif
   124857 
   124858 #ifdef SQLITE_TEST
   124859   sqlite3_free(zTest);
   124860   sqlite3_free(zTest2);
   124861 #endif
   124862 
   124863   return rc;
   124864 }
   124865 
   124866 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   124867 
   124868 /************** End of fts3_tokenizer.c **************************************/
   124869 /************** Begin file fts3_tokenizer1.c *********************************/
   124870 /*
   124871 ** 2006 Oct 10
   124872 **
   124873 ** The author disclaims copyright to this source code.  In place of
   124874 ** a legal notice, here is a blessing:
   124875 **
   124876 **    May you do good and not evil.
   124877 **    May you find forgiveness for yourself and forgive others.
   124878 **    May you share freely, never taking more than you give.
   124879 **
   124880 ******************************************************************************
   124881 **
   124882 ** Implementation of the "simple" full-text-search tokenizer.
   124883 */
   124884 
   124885 /*
   124886 ** The code in this file is only compiled if:
   124887 **
   124888 **     * The FTS3 module is being built as an extension
   124889 **       (in which case SQLITE_CORE is not defined), or
   124890 **
   124891 **     * The FTS3 module is being built into the core of
   124892 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   124893 */
   124894 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   124895 
   124896 /* #include <assert.h> */
   124897 /* #include <stdlib.h> */
   124898 /* #include <stdio.h> */
   124899 /* #include <string.h> */
   124900 
   124901 
   124902 typedef struct simple_tokenizer {
   124903   sqlite3_tokenizer base;
   124904   char delim[128];             /* flag ASCII delimiters */
   124905 } simple_tokenizer;
   124906 
   124907 typedef struct simple_tokenizer_cursor {
   124908   sqlite3_tokenizer_cursor base;
   124909   const char *pInput;          /* input we are tokenizing */
   124910   int nBytes;                  /* size of the input */
   124911   int iOffset;                 /* current position in pInput */
   124912   int iToken;                  /* index of next token to be returned */
   124913   char *pToken;                /* storage for current token */
   124914   int nTokenAllocated;         /* space allocated to zToken buffer */
   124915 } simple_tokenizer_cursor;
   124916 
   124917 
   124918 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   124919   return c<0x80 && t->delim[c];
   124920 }
   124921 static int fts3_isalnum(int x){
   124922   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   124923 }
   124924 
   124925 /*
   124926 ** Create a new tokenizer instance.
   124927 */
   124928 static int simpleCreate(
   124929   int argc, const char * const *argv,
   124930   sqlite3_tokenizer **ppTokenizer
   124931 ){
   124932   simple_tokenizer *t;
   124933 
   124934   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   124935   if( t==NULL ) return SQLITE_NOMEM;
   124936   memset(t, 0, sizeof(*t));
   124937 
   124938   /* TODO(shess) Delimiters need to remain the same from run to run,
   124939   ** else we need to reindex.  One solution would be a meta-table to
   124940   ** track such information in the database, then we'd only want this
   124941   ** information on the initial create.
   124942   */
   124943   if( argc>1 ){
   124944     int i, n = (int)strlen(argv[1]);
   124945     for(i=0; i<n; i++){
   124946       unsigned char ch = argv[1][i];
   124947       /* We explicitly don't support UTF-8 delimiters for now. */
   124948       if( ch>=0x80 ){
   124949         sqlite3_free(t);
   124950         return SQLITE_ERROR;
   124951       }
   124952       t->delim[ch] = 1;
   124953     }
   124954   } else {
   124955     /* Mark non-alphanumeric ASCII characters as delimiters */
   124956     int i;
   124957     for(i=1; i<0x80; i++){
   124958       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   124959     }
   124960   }
   124961 
   124962   *ppTokenizer = &t->base;
   124963   return SQLITE_OK;
   124964 }
   124965 
   124966 /*
   124967 ** Destroy a tokenizer
   124968 */
   124969 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   124970   sqlite3_free(pTokenizer);
   124971   return SQLITE_OK;
   124972 }
   124973 
   124974 /*
   124975 ** Prepare to begin tokenizing a particular string.  The input
   124976 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   124977 ** used to incrementally tokenize this string is returned in
   124978 ** *ppCursor.
   124979 */
   124980 static int simpleOpen(
   124981   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   124982   const char *pInput, int nBytes,        /* String to be tokenized */
   124983   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   124984 ){
   124985   simple_tokenizer_cursor *c;
   124986 
   124987   UNUSED_PARAMETER(pTokenizer);
   124988 
   124989   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   124990   if( c==NULL ) return SQLITE_NOMEM;
   124991 
   124992   c->pInput = pInput;
   124993   if( pInput==0 ){
   124994     c->nBytes = 0;
   124995   }else if( nBytes<0 ){
   124996     c->nBytes = (int)strlen(pInput);
   124997   }else{
   124998     c->nBytes = nBytes;
   124999   }
   125000   c->iOffset = 0;                 /* start tokenizing at the beginning */
   125001   c->iToken = 0;
   125002   c->pToken = NULL;               /* no space allocated, yet. */
   125003   c->nTokenAllocated = 0;
   125004 
   125005   *ppCursor = &c->base;
   125006   return SQLITE_OK;
   125007 }
   125008 
   125009 /*
   125010 ** Close a tokenization cursor previously opened by a call to
   125011 ** simpleOpen() above.
   125012 */
   125013 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   125014   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   125015   sqlite3_free(c->pToken);
   125016   sqlite3_free(c);
   125017   return SQLITE_OK;
   125018 }
   125019 
   125020 /*
   125021 ** Extract the next token from a tokenization cursor.  The cursor must
   125022 ** have been opened by a prior call to simpleOpen().
   125023 */
   125024 static int simpleNext(
   125025   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   125026   const char **ppToken,               /* OUT: *ppToken is the token text */
   125027   int *pnBytes,                       /* OUT: Number of bytes in token */
   125028   int *piStartOffset,                 /* OUT: Starting offset of token */
   125029   int *piEndOffset,                   /* OUT: Ending offset of token */
   125030   int *piPosition                     /* OUT: Position integer of token */
   125031 ){
   125032   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   125033   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   125034   unsigned char *p = (unsigned char *)c->pInput;
   125035 
   125036   while( c->iOffset<c->nBytes ){
   125037     int iStartOffset;
   125038 
   125039     /* Scan past delimiter characters */
   125040     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   125041       c->iOffset++;
   125042     }
   125043 
   125044     /* Count non-delimiter characters. */
   125045     iStartOffset = c->iOffset;
   125046     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   125047       c->iOffset++;
   125048     }
   125049 
   125050     if( c->iOffset>iStartOffset ){
   125051       int i, n = c->iOffset-iStartOffset;
   125052       if( n>c->nTokenAllocated ){
   125053         char *pNew;
   125054         c->nTokenAllocated = n+20;
   125055         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   125056         if( !pNew ) return SQLITE_NOMEM;
   125057         c->pToken = pNew;
   125058       }
   125059       for(i=0; i<n; i++){
   125060         /* TODO(shess) This needs expansion to handle UTF-8
   125061         ** case-insensitivity.
   125062         */
   125063         unsigned char ch = p[iStartOffset+i];
   125064         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   125065       }
   125066       *ppToken = c->pToken;
   125067       *pnBytes = n;
   125068       *piStartOffset = iStartOffset;
   125069       *piEndOffset = c->iOffset;
   125070       *piPosition = c->iToken++;
   125071 
   125072       return SQLITE_OK;
   125073     }
   125074   }
   125075   return SQLITE_DONE;
   125076 }
   125077 
   125078 /*
   125079 ** The set of routines that implement the simple tokenizer
   125080 */
   125081 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   125082   0,
   125083   simpleCreate,
   125084   simpleDestroy,
   125085   simpleOpen,
   125086   simpleClose,
   125087   simpleNext,
   125088   0,
   125089 };
   125090 
   125091 /*
   125092 ** Allocate a new simple tokenizer.  Return a pointer to the new
   125093 ** tokenizer in *ppModule
   125094 */
   125095 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   125096   sqlite3_tokenizer_module const**ppModule
   125097 ){
   125098   *ppModule = &simpleTokenizerModule;
   125099 }
   125100 
   125101 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   125102 
   125103 /************** End of fts3_tokenizer1.c *************************************/
   125104 /************** Begin file fts3_write.c **************************************/
   125105 /*
   125106 ** 2009 Oct 23
   125107 **
   125108 ** The author disclaims copyright to this source code.  In place of
   125109 ** a legal notice, here is a blessing:
   125110 **
   125111 **    May you do good and not evil.
   125112 **    May you find forgiveness for yourself and forgive others.
   125113 **    May you share freely, never taking more than you give.
   125114 **
   125115 ******************************************************************************
   125116 **
   125117 ** This file is part of the SQLite FTS3 extension module. Specifically,
   125118 ** this file contains code to insert, update and delete rows from FTS3
   125119 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   125120 ** of the sub-routines used to merge segments are also used by the query
   125121 ** code in fts3.c.
   125122 */
   125123 
   125124 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   125125 
   125126 /* #include <string.h> */
   125127 /* #include <assert.h> */
   125128 /* #include <stdlib.h> */
   125129 
   125130 /*
   125131 ** When full-text index nodes are loaded from disk, the buffer that they
   125132 ** are loaded into has the following number of bytes of padding at the end
   125133 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   125134 ** of 920 bytes is allocated for it.
   125135 **
   125136 ** This means that if we have a pointer into a buffer containing node data,
   125137 ** it is always safe to read up to two varints from it without risking an
   125138 ** overread, even if the node data is corrupted.
   125139 */
   125140 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   125141 
   125142 /*
   125143 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
   125144 ** memory incrementally instead of all at once. This can be a big performance
   125145 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
   125146 ** method before retrieving all query results (as may happen, for example,
   125147 ** if a query has a LIMIT clause).
   125148 **
   125149 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
   125150 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
   125151 ** The code is written so that the hard lower-limit for each of these values
   125152 ** is 1. Clearly such small values would be inefficient, but can be useful
   125153 ** for testing purposes.
   125154 **
   125155 ** If this module is built with SQLITE_TEST defined, these constants may
   125156 ** be overridden at runtime for testing purposes. File fts3_test.c contains
   125157 ** a Tcl interface to read and write the values.
   125158 */
   125159 #ifdef SQLITE_TEST
   125160 int test_fts3_node_chunksize = (4*1024);
   125161 int test_fts3_node_chunk_threshold = (4*1024)*4;
   125162 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
   125163 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
   125164 #else
   125165 # define FTS3_NODE_CHUNKSIZE (4*1024)
   125166 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
   125167 #endif
   125168 
   125169 typedef struct PendingList PendingList;
   125170 typedef struct SegmentNode SegmentNode;
   125171 typedef struct SegmentWriter SegmentWriter;
   125172 
   125173 /*
   125174 ** An instance of the following data structure is used to build doclists
   125175 ** incrementally. See function fts3PendingListAppend() for details.
   125176 */
   125177 struct PendingList {
   125178   int nData;
   125179   char *aData;
   125180   int nSpace;
   125181   sqlite3_int64 iLastDocid;
   125182   sqlite3_int64 iLastCol;
   125183   sqlite3_int64 iLastPos;
   125184 };
   125185 
   125186 
   125187 /*
   125188 ** Each cursor has a (possibly empty) linked list of the following objects.
   125189 */
   125190 struct Fts3DeferredToken {
   125191   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   125192   int iCol;                       /* Column token must occur in */
   125193   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   125194   PendingList *pList;             /* Doclist is assembled here */
   125195 };
   125196 
   125197 /*
   125198 ** An instance of this structure is used to iterate through the terms on
   125199 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   125200 ** this structure are only manipulated by code in this file, opaque handles
   125201 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   125202 ** terms when querying the full-text index. See functions:
   125203 **
   125204 **   sqlite3Fts3SegReaderNew()
   125205 **   sqlite3Fts3SegReaderFree()
   125206 **   sqlite3Fts3SegReaderIterate()
   125207 **
   125208 ** Methods used to manipulate Fts3SegReader structures:
   125209 **
   125210 **   fts3SegReaderNext()
   125211 **   fts3SegReaderFirstDocid()
   125212 **   fts3SegReaderNextDocid()
   125213 */
   125214 struct Fts3SegReader {
   125215   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   125216   int bLookup;                    /* True for a lookup only */
   125217 
   125218   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   125219   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   125220   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   125221   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   125222 
   125223   char *aNode;                    /* Pointer to node data (or NULL) */
   125224   int nNode;                      /* Size of buffer at aNode (or 0) */
   125225   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
   125226   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
   125227 
   125228   Fts3HashElem **ppNextElem;
   125229 
   125230   /* Variables set by fts3SegReaderNext(). These may be read directly
   125231   ** by the caller. They are valid from the time SegmentReaderNew() returns
   125232   ** until SegmentReaderNext() returns something other than SQLITE_OK
   125233   ** (i.e. SQLITE_DONE).
   125234   */
   125235   int nTerm;                      /* Number of bytes in current term */
   125236   char *zTerm;                    /* Pointer to current term */
   125237   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   125238   char *aDoclist;                 /* Pointer to doclist of current entry */
   125239   int nDoclist;                   /* Size of doclist in current entry */
   125240 
   125241   /* The following variables are used by fts3SegReaderNextDocid() to iterate
   125242   ** through the current doclist (aDoclist/nDoclist).
   125243   */
   125244   char *pOffsetList;
   125245   int nOffsetList;                /* For descending pending seg-readers only */
   125246   sqlite3_int64 iDocid;
   125247 };
   125248 
   125249 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   125250 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
   125251 
   125252 /*
   125253 ** An instance of this structure is used to create a segment b-tree in the
   125254 ** database. The internal details of this type are only accessed by the
   125255 ** following functions:
   125256 **
   125257 **   fts3SegWriterAdd()
   125258 **   fts3SegWriterFlush()
   125259 **   fts3SegWriterFree()
   125260 */
   125261 struct SegmentWriter {
   125262   SegmentNode *pTree;             /* Pointer to interior tree structure */
   125263   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   125264   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   125265   char *zTerm;                    /* Pointer to previous term buffer */
   125266   int nTerm;                      /* Number of bytes in zTerm */
   125267   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   125268   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   125269   int nSize;                      /* Size of allocation at aData */
   125270   int nData;                      /* Bytes of data in aData */
   125271   char *aData;                    /* Pointer to block from malloc() */
   125272 };
   125273 
   125274 /*
   125275 ** Type SegmentNode is used by the following three functions to create
   125276 ** the interior part of the segment b+-tree structures (everything except
   125277 ** the leaf nodes). These functions and type are only ever used by code
   125278 ** within the fts3SegWriterXXX() family of functions described above.
   125279 **
   125280 **   fts3NodeAddTerm()
   125281 **   fts3NodeWrite()
   125282 **   fts3NodeFree()
   125283 **
   125284 ** When a b+tree is written to the database (either as a result of a merge
   125285 ** or the pending-terms table being flushed), leaves are written into the
   125286 ** database file as soon as they are completely populated. The interior of
   125287 ** the tree is assembled in memory and written out only once all leaves have
   125288 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
   125289 ** very large, meaning that the interior of the tree consumes relatively
   125290 ** little memory.
   125291 */
   125292 struct SegmentNode {
   125293   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   125294   SegmentNode *pRight;            /* Pointer to right-sibling */
   125295   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   125296   int nEntry;                     /* Number of terms written to node so far */
   125297   char *zTerm;                    /* Pointer to previous term buffer */
   125298   int nTerm;                      /* Number of bytes in zTerm */
   125299   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   125300   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   125301   int nData;                      /* Bytes of valid data so far */
   125302   char *aData;                    /* Node data */
   125303 };
   125304 
   125305 /*
   125306 ** Valid values for the second argument to fts3SqlStmt().
   125307 */
   125308 #define SQL_DELETE_CONTENT             0
   125309 #define SQL_IS_EMPTY                   1
   125310 #define SQL_DELETE_ALL_CONTENT         2
   125311 #define SQL_DELETE_ALL_SEGMENTS        3
   125312 #define SQL_DELETE_ALL_SEGDIR          4
   125313 #define SQL_DELETE_ALL_DOCSIZE         5
   125314 #define SQL_DELETE_ALL_STAT            6
   125315 #define SQL_SELECT_CONTENT_BY_ROWID    7
   125316 #define SQL_NEXT_SEGMENT_INDEX         8
   125317 #define SQL_INSERT_SEGMENTS            9
   125318 #define SQL_NEXT_SEGMENTS_ID          10
   125319 #define SQL_INSERT_SEGDIR             11
   125320 #define SQL_SELECT_LEVEL              12
   125321 #define SQL_SELECT_LEVEL_RANGE        13
   125322 #define SQL_SELECT_LEVEL_COUNT        14
   125323 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
   125324 #define SQL_DELETE_SEGDIR_LEVEL       16
   125325 #define SQL_DELETE_SEGMENTS_RANGE     17
   125326 #define SQL_CONTENT_INSERT            18
   125327 #define SQL_DELETE_DOCSIZE            19
   125328 #define SQL_REPLACE_DOCSIZE           20
   125329 #define SQL_SELECT_DOCSIZE            21
   125330 #define SQL_SELECT_DOCTOTAL           22
   125331 #define SQL_REPLACE_DOCTOTAL          23
   125332 
   125333 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
   125334 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
   125335 
   125336 #define SQL_DELETE_SEGDIR_RANGE       26
   125337 
   125338 #define SQL_SELECT_ALL_LANGID         27
   125339 
   125340 /*
   125341 ** This function is used to obtain an SQLite prepared statement handle
   125342 ** for the statement identified by the second argument. If successful,
   125343 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   125344 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   125345 **
   125346 ** If argument apVal is not NULL, then it must point to an array with
   125347 ** at least as many entries as the requested statement has bound
   125348 ** parameters. The values are bound to the statements parameters before
   125349 ** returning.
   125350 */
   125351 static int fts3SqlStmt(
   125352   Fts3Table *p,                   /* Virtual table handle */
   125353   int eStmt,                      /* One of the SQL_XXX constants above */
   125354   sqlite3_stmt **pp,              /* OUT: Statement handle */
   125355   sqlite3_value **apVal           /* Values to bind to statement */
   125356 ){
   125357   const char *azSql[] = {
   125358 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   125359 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   125360 /* 2  */  "DELETE FROM %Q.'%q_content'",
   125361 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   125362 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   125363 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   125364 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   125365 /* 7  */  "SELECT %s WHERE rowid=?",
   125366 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   125367 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   125368 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   125369 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   125370 
   125371           /* Return segments in order from oldest to newest.*/
   125372 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   125373             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   125374 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   125375             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
   125376             "ORDER BY level DESC, idx ASC",
   125377 
   125378 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   125379 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   125380 
   125381 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   125382 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   125383 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
   125384 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   125385 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   125386 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   125387 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
   125388 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
   125389 /* 24 */  "",
   125390 /* 25 */  "",
   125391 
   125392 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   125393 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
   125394 
   125395   };
   125396   int rc = SQLITE_OK;
   125397   sqlite3_stmt *pStmt;
   125398 
   125399   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   125400   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   125401 
   125402   pStmt = p->aStmt[eStmt];
   125403   if( !pStmt ){
   125404     char *zSql;
   125405     if( eStmt==SQL_CONTENT_INSERT ){
   125406       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
   125407     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
   125408       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
   125409     }else{
   125410       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   125411     }
   125412     if( !zSql ){
   125413       rc = SQLITE_NOMEM;
   125414     }else{
   125415       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   125416       sqlite3_free(zSql);
   125417       assert( rc==SQLITE_OK || pStmt==0 );
   125418       p->aStmt[eStmt] = pStmt;
   125419     }
   125420   }
   125421   if( apVal ){
   125422     int i;
   125423     int nParam = sqlite3_bind_parameter_count(pStmt);
   125424     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   125425       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   125426     }
   125427   }
   125428   *pp = pStmt;
   125429   return rc;
   125430 }
   125431 
   125432 static int fts3SelectDocsize(
   125433   Fts3Table *pTab,                /* FTS3 table handle */
   125434   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
   125435   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   125436   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125437 ){
   125438   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   125439   int rc;                         /* Return code */
   125440 
   125441   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
   125442 
   125443   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
   125444   if( rc==SQLITE_OK ){
   125445     if( eStmt==SQL_SELECT_DOCSIZE ){
   125446       sqlite3_bind_int64(pStmt, 1, iDocid);
   125447     }
   125448     rc = sqlite3_step(pStmt);
   125449     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   125450       rc = sqlite3_reset(pStmt);
   125451       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   125452       pStmt = 0;
   125453     }else{
   125454       rc = SQLITE_OK;
   125455     }
   125456   }
   125457 
   125458   *ppStmt = pStmt;
   125459   return rc;
   125460 }
   125461 
   125462 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   125463   Fts3Table *pTab,                /* Fts3 table handle */
   125464   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125465 ){
   125466   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
   125467 }
   125468 
   125469 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   125470   Fts3Table *pTab,                /* Fts3 table handle */
   125471   sqlite3_int64 iDocid,           /* Docid to read size data for */
   125472   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125473 ){
   125474   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
   125475 }
   125476 
   125477 /*
   125478 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   125479 ** array apVal[] to the SQL statement identified by eStmt, the statement
   125480 ** is executed.
   125481 **
   125482 ** Returns SQLITE_OK if the statement is successfully executed, or an
   125483 ** SQLite error code otherwise.
   125484 */
   125485 static void fts3SqlExec(
   125486   int *pRC,                /* Result code */
   125487   Fts3Table *p,            /* The FTS3 table */
   125488   int eStmt,               /* Index of statement to evaluate */
   125489   sqlite3_value **apVal    /* Parameters to bind */
   125490 ){
   125491   sqlite3_stmt *pStmt;
   125492   int rc;
   125493   if( *pRC ) return;
   125494   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   125495   if( rc==SQLITE_OK ){
   125496     sqlite3_step(pStmt);
   125497     rc = sqlite3_reset(pStmt);
   125498   }
   125499   *pRC = rc;
   125500 }
   125501 
   125502 
   125503 /*
   125504 ** This function ensures that the caller has obtained a shared-cache
   125505 ** table-lock on the %_content table. This is required before reading
   125506 ** data from the fts3 table. If this lock is not acquired first, then
   125507 ** the caller may end up holding read-locks on the %_segments and %_segdir
   125508 ** tables, but no read-lock on the %_content table. If this happens
   125509 ** a second connection will be able to write to the fts3 table, but
   125510 ** attempting to commit those writes might return SQLITE_LOCKED or
   125511 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
   125512 ** write-locks on the %_segments and %_segdir ** tables).
   125513 **
   125514 ** We try to avoid this because if FTS3 returns any error when committing
   125515 ** a transaction, the whole transaction will be rolled back. And this is
   125516 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
   125517 ** still happen if the user reads data directly from the %_segments or
   125518 ** %_segdir tables instead of going through FTS3 though.
   125519 **
   125520 ** This reasoning does not apply to a content=xxx table.
   125521 */
   125522 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
   125523   int rc;                         /* Return code */
   125524   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
   125525 
   125526   if( p->zContentTbl==0 ){
   125527     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
   125528     if( rc==SQLITE_OK ){
   125529       sqlite3_bind_null(pStmt, 1);
   125530       sqlite3_step(pStmt);
   125531       rc = sqlite3_reset(pStmt);
   125532     }
   125533   }else{
   125534     rc = SQLITE_OK;
   125535   }
   125536 
   125537   return rc;
   125538 }
   125539 
   125540 /*
   125541 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
   125542 ** Within each language id, a separate index is maintained to store the
   125543 ** document terms, and each configured prefix size (configured the FTS
   125544 ** "prefix=" option). And each index consists of multiple levels ("relative
   125545 ** levels").
   125546 **
   125547 ** All three of these values (the language id, the specific index and the
   125548 ** level within the index) are encoded in 64-bit integer values stored
   125549 ** in the %_segdir table on disk. This function is used to convert three
   125550 ** separate component values into the single 64-bit integer value that
   125551 ** can be used to query the %_segdir table.
   125552 **
   125553 ** Specifically, each language-id/index combination is allocated 1024
   125554 ** 64-bit integer level values ("absolute levels"). The main terms index
   125555 ** for language-id 0 is allocate values 0-1023. The first prefix index
   125556 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
   125557 ** Language 1 indexes are allocated immediately following language 0.
   125558 **
   125559 ** So, for a system with nPrefix prefix indexes configured, the block of
   125560 ** absolute levels that corresponds to language-id iLangid and index
   125561 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
   125562 */
   125563 static sqlite3_int64 getAbsoluteLevel(
   125564   Fts3Table *p,
   125565   int iLangid,
   125566   int iIndex,
   125567   int iLevel
   125568 ){
   125569   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
   125570   assert( iLangid>=0 );
   125571   assert( p->nIndex>0 );
   125572   assert( iIndex>=0 && iIndex<p->nIndex );
   125573 
   125574   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
   125575   return iBase + iLevel;
   125576 }
   125577 
   125578 
   125579 /*
   125580 ** Set *ppStmt to a statement handle that may be used to iterate through
   125581 ** all rows in the %_segdir table, from oldest to newest. If successful,
   125582 ** return SQLITE_OK. If an error occurs while preparing the statement,
   125583 ** return an SQLite error code.
   125584 **
   125585 ** There is only ever one instance of this SQL statement compiled for
   125586 ** each FTS3 table.
   125587 **
   125588 ** The statement returns the following columns from the %_segdir table:
   125589 **
   125590 **   0: idx
   125591 **   1: start_block
   125592 **   2: leaves_end_block
   125593 **   3: end_block
   125594 **   4: root
   125595 */
   125596 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   125597   Fts3Table *p,                   /* FTS3 table */
   125598   int iLangid,                    /* Language being queried */
   125599   int iIndex,                     /* Index for p->aIndex[] */
   125600   int iLevel,                     /* Level to select (relative level) */
   125601   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
   125602 ){
   125603   int rc;
   125604   sqlite3_stmt *pStmt = 0;
   125605 
   125606   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
   125607   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   125608   assert( iIndex>=0 && iIndex<p->nIndex );
   125609 
   125610   if( iLevel<0 ){
   125611     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
   125612     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
   125613     if( rc==SQLITE_OK ){
   125614       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   125615       sqlite3_bind_int64(pStmt, 2,
   125616           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   125617       );
   125618     }
   125619   }else{
   125620     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
   125621     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   125622     if( rc==SQLITE_OK ){
   125623       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
   125624     }
   125625   }
   125626   *ppStmt = pStmt;
   125627   return rc;
   125628 }
   125629 
   125630 
   125631 /*
   125632 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   125633 ** if successful, or an SQLite error code otherwise.
   125634 **
   125635 ** This function also serves to allocate the PendingList structure itself.
   125636 ** For example, to create a new PendingList structure containing two
   125637 ** varints:
   125638 **
   125639 **   PendingList *p = 0;
   125640 **   fts3PendingListAppendVarint(&p, 1);
   125641 **   fts3PendingListAppendVarint(&p, 2);
   125642 */
   125643 static int fts3PendingListAppendVarint(
   125644   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   125645   sqlite3_int64 i                 /* Value to append to data */
   125646 ){
   125647   PendingList *p = *pp;
   125648 
   125649   /* Allocate or grow the PendingList as required. */
   125650   if( !p ){
   125651     p = sqlite3_malloc(sizeof(*p) + 100);
   125652     if( !p ){
   125653       return SQLITE_NOMEM;
   125654     }
   125655     p->nSpace = 100;
   125656     p->aData = (char *)&p[1];
   125657     p->nData = 0;
   125658   }
   125659   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   125660     int nNew = p->nSpace * 2;
   125661     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   125662     if( !p ){
   125663       sqlite3_free(*pp);
   125664       *pp = 0;
   125665       return SQLITE_NOMEM;
   125666     }
   125667     p->nSpace = nNew;
   125668     p->aData = (char *)&p[1];
   125669   }
   125670 
   125671   /* Append the new serialized varint to the end of the list. */
   125672   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   125673   p->aData[p->nData] = '\0';
   125674   *pp = p;
   125675   return SQLITE_OK;
   125676 }
   125677 
   125678 /*
   125679 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   125680 ** is returned if the structure is sqlite3_realloced as part of adding
   125681 ** the entry. Otherwise, zero.
   125682 **
   125683 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   125684 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   125685 ** it is set to SQLITE_OK.
   125686 */
   125687 static int fts3PendingListAppend(
   125688   PendingList **pp,               /* IN/OUT: PendingList structure */
   125689   sqlite3_int64 iDocid,           /* Docid for entry to add */
   125690   sqlite3_int64 iCol,             /* Column for entry to add */
   125691   sqlite3_int64 iPos,             /* Position of term for entry to add */
   125692   int *pRc                        /* OUT: Return code */
   125693 ){
   125694   PendingList *p = *pp;
   125695   int rc = SQLITE_OK;
   125696 
   125697   assert( !p || p->iLastDocid<=iDocid );
   125698 
   125699   if( !p || p->iLastDocid!=iDocid ){
   125700     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   125701     if( p ){
   125702       assert( p->nData<p->nSpace );
   125703       assert( p->aData[p->nData]==0 );
   125704       p->nData++;
   125705     }
   125706     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   125707       goto pendinglistappend_out;
   125708     }
   125709     p->iLastCol = -1;
   125710     p->iLastPos = 0;
   125711     p->iLastDocid = iDocid;
   125712   }
   125713   if( iCol>0 && p->iLastCol!=iCol ){
   125714     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   125715      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   125716     ){
   125717       goto pendinglistappend_out;
   125718     }
   125719     p->iLastCol = iCol;
   125720     p->iLastPos = 0;
   125721   }
   125722   if( iCol>=0 ){
   125723     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   125724     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   125725     if( rc==SQLITE_OK ){
   125726       p->iLastPos = iPos;
   125727     }
   125728   }
   125729 
   125730  pendinglistappend_out:
   125731   *pRc = rc;
   125732   if( p!=*pp ){
   125733     *pp = p;
   125734     return 1;
   125735   }
   125736   return 0;
   125737 }
   125738 
   125739 /*
   125740 ** Free a PendingList object allocated by fts3PendingListAppend().
   125741 */
   125742 static void fts3PendingListDelete(PendingList *pList){
   125743   sqlite3_free(pList);
   125744 }
   125745 
   125746 /*
   125747 ** Add an entry to one of the pending-terms hash tables.
   125748 */
   125749 static int fts3PendingTermsAddOne(
   125750   Fts3Table *p,
   125751   int iCol,
   125752   int iPos,
   125753   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
   125754   const char *zToken,
   125755   int nToken
   125756 ){
   125757   PendingList *pList;
   125758   int rc = SQLITE_OK;
   125759 
   125760   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
   125761   if( pList ){
   125762     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   125763   }
   125764   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   125765     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
   125766       /* Malloc failed while inserting the new entry. This can only
   125767       ** happen if there was no previous entry for this token.
   125768       */
   125769       assert( 0==fts3HashFind(pHash, zToken, nToken) );
   125770       sqlite3_free(pList);
   125771       rc = SQLITE_NOMEM;
   125772     }
   125773   }
   125774   if( rc==SQLITE_OK ){
   125775     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   125776   }
   125777   return rc;
   125778 }
   125779 
   125780 /*
   125781 ** Tokenize the nul-terminated string zText and add all tokens to the
   125782 ** pending-terms hash-table. The docid used is that currently stored in
   125783 ** p->iPrevDocid, and the column is specified by argument iCol.
   125784 **
   125785 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   125786 */
   125787 static int fts3PendingTermsAdd(
   125788   Fts3Table *p,                   /* Table into which text will be inserted */
   125789   int iLangid,                    /* Language id to use */
   125790   const char *zText,              /* Text of document to be inserted */
   125791   int iCol,                       /* Column into which text is being inserted */
   125792   u32 *pnWord                     /* OUT: Number of tokens inserted */
   125793 ){
   125794   int rc;
   125795   int iStart;
   125796   int iEnd;
   125797   int iPos;
   125798   int nWord = 0;
   125799 
   125800   char const *zToken;
   125801   int nToken;
   125802 
   125803   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   125804   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   125805   sqlite3_tokenizer_cursor *pCsr;
   125806   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   125807       const char**,int*,int*,int*,int*);
   125808 
   125809   assert( pTokenizer && pModule );
   125810 
   125811   /* If the user has inserted a NULL value, this function may be called with
   125812   ** zText==0. In this case, add zero token entries to the hash table and
   125813   ** return early. */
   125814   if( zText==0 ){
   125815     *pnWord = 0;
   125816     return SQLITE_OK;
   125817   }
   125818 
   125819   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
   125820   if( rc!=SQLITE_OK ){
   125821     return rc;
   125822   }
   125823 
   125824   xNext = pModule->xNext;
   125825   while( SQLITE_OK==rc
   125826       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   125827   ){
   125828     int i;
   125829     if( iPos>=nWord ) nWord = iPos+1;
   125830 
   125831     /* Positions cannot be negative; we use -1 as a terminator internally.
   125832     ** Tokens must have a non-zero length.
   125833     */
   125834     if( iPos<0 || !zToken || nToken<=0 ){
   125835       rc = SQLITE_ERROR;
   125836       break;
   125837     }
   125838 
   125839     /* Add the term to the terms index */
   125840     rc = fts3PendingTermsAddOne(
   125841         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
   125842     );
   125843 
   125844     /* Add the term to each of the prefix indexes that it is not too
   125845     ** short for. */
   125846     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
   125847       struct Fts3Index *pIndex = &p->aIndex[i];
   125848       if( nToken<pIndex->nPrefix ) continue;
   125849       rc = fts3PendingTermsAddOne(
   125850           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
   125851       );
   125852     }
   125853   }
   125854 
   125855   pModule->xClose(pCsr);
   125856   *pnWord = nWord;
   125857   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   125858 }
   125859 
   125860 /*
   125861 ** Calling this function indicates that subsequent calls to
   125862 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   125863 ** contents of the document with docid iDocid.
   125864 */
   125865 static int fts3PendingTermsDocid(
   125866   Fts3Table *p,                   /* Full-text table handle */
   125867   int iLangid,                    /* Language id of row being written */
   125868   sqlite_int64 iDocid             /* Docid of row being written */
   125869 ){
   125870   assert( iLangid>=0 );
   125871 
   125872   /* TODO(shess) Explore whether partially flushing the buffer on
   125873   ** forced-flush would provide better performance.  I suspect that if
   125874   ** we ordered the doclists by size and flushed the largest until the
   125875   ** buffer was half empty, that would let the less frequent terms
   125876   ** generate longer doclists.
   125877   */
   125878   if( iDocid<=p->iPrevDocid
   125879    || p->iPrevLangid!=iLangid
   125880    || p->nPendingData>p->nMaxPendingData
   125881   ){
   125882     int rc = sqlite3Fts3PendingTermsFlush(p);
   125883     if( rc!=SQLITE_OK ) return rc;
   125884   }
   125885   p->iPrevDocid = iDocid;
   125886   p->iPrevLangid = iLangid;
   125887   return SQLITE_OK;
   125888 }
   125889 
   125890 /*
   125891 ** Discard the contents of the pending-terms hash tables.
   125892 */
   125893 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   125894   int i;
   125895   for(i=0; i<p->nIndex; i++){
   125896     Fts3HashElem *pElem;
   125897     Fts3Hash *pHash = &p->aIndex[i].hPending;
   125898     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
   125899       PendingList *pList = (PendingList *)fts3HashData(pElem);
   125900       fts3PendingListDelete(pList);
   125901     }
   125902     fts3HashClear(pHash);
   125903   }
   125904   p->nPendingData = 0;
   125905 }
   125906 
   125907 /*
   125908 ** This function is called by the xUpdate() method as part of an INSERT
   125909 ** operation. It adds entries for each term in the new record to the
   125910 ** pendingTerms hash table.
   125911 **
   125912 ** Argument apVal is the same as the similarly named argument passed to
   125913 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   125914 */
   125915 static int fts3InsertTerms(
   125916   Fts3Table *p,
   125917   int iLangid,
   125918   sqlite3_value **apVal,
   125919   u32 *aSz
   125920 ){
   125921   int i;                          /* Iterator variable */
   125922   for(i=2; i<p->nColumn+2; i++){
   125923     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   125924     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
   125925     if( rc!=SQLITE_OK ){
   125926       return rc;
   125927     }
   125928     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   125929   }
   125930   return SQLITE_OK;
   125931 }
   125932 
   125933 /*
   125934 ** This function is called by the xUpdate() method for an INSERT operation.
   125935 ** The apVal parameter is passed a copy of the apVal argument passed by
   125936 ** SQLite to the xUpdate() method. i.e:
   125937 **
   125938 **   apVal[0]                Not used for INSERT.
   125939 **   apVal[1]                rowid
   125940 **   apVal[2]                Left-most user-defined column
   125941 **   ...
   125942 **   apVal[p->nColumn+1]     Right-most user-defined column
   125943 **   apVal[p->nColumn+2]     Hidden column with same name as table
   125944 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   125945 **   apVal[p->nColumn+4]     Hidden languageid column
   125946 */
   125947 static int fts3InsertData(
   125948   Fts3Table *p,                   /* Full-text table */
   125949   sqlite3_value **apVal,          /* Array of values to insert */
   125950   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   125951 ){
   125952   int rc;                         /* Return code */
   125953   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   125954 
   125955   if( p->zContentTbl ){
   125956     sqlite3_value *pRowid = apVal[p->nColumn+3];
   125957     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
   125958       pRowid = apVal[1];
   125959     }
   125960     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
   125961       return SQLITE_CONSTRAINT;
   125962     }
   125963     *piDocid = sqlite3_value_int64(pRowid);
   125964     return SQLITE_OK;
   125965   }
   125966 
   125967   /* Locate the statement handle used to insert data into the %_content
   125968   ** table. The SQL for this statement is:
   125969   **
   125970   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   125971   **
   125972   ** The statement features N '?' variables, where N is the number of user
   125973   ** defined columns in the FTS3 table, plus one for the docid field.
   125974   */
   125975   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   125976   if( rc==SQLITE_OK && p->zLanguageid ){
   125977     rc = sqlite3_bind_int(
   125978         pContentInsert, p->nColumn+2,
   125979         sqlite3_value_int(apVal[p->nColumn+4])
   125980     );
   125981   }
   125982   if( rc!=SQLITE_OK ) return rc;
   125983 
   125984   /* There is a quirk here. The users INSERT statement may have specified
   125985   ** a value for the "rowid" field, for the "docid" field, or for both.
   125986   ** Which is a problem, since "rowid" and "docid" are aliases for the
   125987   ** same value. For example:
   125988   **
   125989   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   125990   **
   125991   ** In FTS3, this is an error. It is an error to specify non-NULL values
   125992   ** for both docid and some other rowid alias.
   125993   */
   125994   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   125995     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   125996      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   125997     ){
   125998       /* A rowid/docid conflict. */
   125999       return SQLITE_ERROR;
   126000     }
   126001     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   126002     if( rc!=SQLITE_OK ) return rc;
   126003   }
   126004 
   126005   /* Execute the statement to insert the record. Set *piDocid to the
   126006   ** new docid value.
   126007   */
   126008   sqlite3_step(pContentInsert);
   126009   rc = sqlite3_reset(pContentInsert);
   126010 
   126011   *piDocid = sqlite3_last_insert_rowid(p->db);
   126012   return rc;
   126013 }
   126014 
   126015 
   126016 
   126017 /*
   126018 ** Remove all data from the FTS3 table. Clear the hash table containing
   126019 ** pending terms.
   126020 */
   126021 static int fts3DeleteAll(Fts3Table *p, int bContent){
   126022   int rc = SQLITE_OK;             /* Return code */
   126023 
   126024   /* Discard the contents of the pending-terms hash table. */
   126025   sqlite3Fts3PendingTermsClear(p);
   126026 
   126027   /* Delete everything from the shadow tables. Except, leave %_content as
   126028   ** is if bContent is false.  */
   126029   assert( p->zContentTbl==0 || bContent==0 );
   126030   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   126031   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   126032   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   126033   if( p->bHasDocsize ){
   126034     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   126035   }
   126036   if( p->bHasStat ){
   126037     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   126038   }
   126039   return rc;
   126040 }
   126041 
   126042 /*
   126043 **
   126044 */
   126045 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
   126046   int iLangid = 0;
   126047   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
   126048   return iLangid;
   126049 }
   126050 
   126051 /*
   126052 ** The first element in the apVal[] array is assumed to contain the docid
   126053 ** (an integer) of a row about to be deleted. Remove all terms from the
   126054 ** full-text index.
   126055 */
   126056 static void fts3DeleteTerms(
   126057   int *pRC,               /* Result code */
   126058   Fts3Table *p,           /* The FTS table to delete from */
   126059   sqlite3_value *pRowid,  /* The docid to be deleted */
   126060   u32 *aSz                /* Sizes of deleted document written here */
   126061 ){
   126062   int rc;
   126063   sqlite3_stmt *pSelect;
   126064 
   126065   if( *pRC ) return;
   126066   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
   126067   if( rc==SQLITE_OK ){
   126068     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   126069       int i;
   126070       int iLangid = langidFromSelect(p, pSelect);
   126071       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
   126072       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
   126073         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   126074         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
   126075         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   126076       }
   126077       if( rc!=SQLITE_OK ){
   126078         sqlite3_reset(pSelect);
   126079         *pRC = rc;
   126080         return;
   126081       }
   126082     }
   126083     rc = sqlite3_reset(pSelect);
   126084   }else{
   126085     sqlite3_reset(pSelect);
   126086   }
   126087   *pRC = rc;
   126088 }
   126089 
   126090 /*
   126091 ** Forward declaration to account for the circular dependency between
   126092 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   126093 */
   126094 static int fts3SegmentMerge(Fts3Table *, int, int, int);
   126095 
   126096 /*
   126097 ** This function allocates a new level iLevel index in the segdir table.
   126098 ** Usually, indexes are allocated within a level sequentially starting
   126099 ** with 0, so the allocated index is one greater than the value returned
   126100 ** by:
   126101 **
   126102 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   126103 **
   126104 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   126105 ** level, they are merged into a single level (iLevel+1) segment and the
   126106 ** allocated index is 0.
   126107 **
   126108 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   126109 ** returned. Otherwise, an SQLite error code is returned.
   126110 */
   126111 static int fts3AllocateSegdirIdx(
   126112   Fts3Table *p,
   126113   int iLangid,                    /* Language id */
   126114   int iIndex,                     /* Index for p->aIndex */
   126115   int iLevel,
   126116   int *piIdx
   126117 ){
   126118   int rc;                         /* Return Code */
   126119   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   126120   int iNext = 0;                  /* Result of query pNextIdx */
   126121 
   126122   assert( iLangid>=0 );
   126123   assert( p->nIndex>=1 );
   126124 
   126125   /* Set variable iNext to the next available segdir index at level iLevel. */
   126126   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   126127   if( rc==SQLITE_OK ){
   126128     sqlite3_bind_int64(
   126129         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   126130     );
   126131     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   126132       iNext = sqlite3_column_int(pNextIdx, 0);
   126133     }
   126134     rc = sqlite3_reset(pNextIdx);
   126135   }
   126136 
   126137   if( rc==SQLITE_OK ){
   126138     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   126139     ** full, merge all segments in level iLevel into a single iLevel+1
   126140     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   126141     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   126142     */
   126143     if( iNext>=FTS3_MERGE_COUNT ){
   126144       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
   126145       *piIdx = 0;
   126146     }else{
   126147       *piIdx = iNext;
   126148     }
   126149   }
   126150 
   126151   return rc;
   126152 }
   126153 
   126154 /*
   126155 ** The %_segments table is declared as follows:
   126156 **
   126157 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   126158 **
   126159 ** This function reads data from a single row of the %_segments table. The
   126160 ** specific row is identified by the iBlockid parameter. If paBlob is not
   126161 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   126162 ** with the contents of the blob stored in the "block" column of the
   126163 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   126164 ** to the size of the blob in bytes before returning.
   126165 **
   126166 ** If an error occurs, or the table does not contain the specified row,
   126167 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   126168 ** paBlob is non-NULL, then it is the responsibility of the caller to
   126169 ** eventually free the returned buffer.
   126170 **
   126171 ** This function may leave an open sqlite3_blob* handle in the
   126172 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   126173 ** to this function. The handle may be closed by calling the
   126174 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   126175 ** performance improvement, but the blob handle should always be closed
   126176 ** before control is returned to the user (to prevent a lock being held
   126177 ** on the database file for longer than necessary). Thus, any virtual table
   126178 ** method (xFilter etc.) that may directly or indirectly call this function
   126179 ** must call sqlite3Fts3SegmentsClose() before returning.
   126180 */
   126181 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   126182   Fts3Table *p,                   /* FTS3 table handle */
   126183   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   126184   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   126185   int *pnBlob,                    /* OUT: Size of blob data */
   126186   int *pnLoad                     /* OUT: Bytes actually loaded */
   126187 ){
   126188   int rc;                         /* Return code */
   126189 
   126190   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   126191   assert( pnBlob);
   126192 
   126193   if( p->pSegments ){
   126194     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   126195   }else{
   126196     if( 0==p->zSegmentsTbl ){
   126197       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   126198       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   126199     }
   126200     rc = sqlite3_blob_open(
   126201        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   126202     );
   126203   }
   126204 
   126205   if( rc==SQLITE_OK ){
   126206     int nByte = sqlite3_blob_bytes(p->pSegments);
   126207     *pnBlob = nByte;
   126208     if( paBlob ){
   126209       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   126210       if( !aByte ){
   126211         rc = SQLITE_NOMEM;
   126212       }else{
   126213         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
   126214           nByte = FTS3_NODE_CHUNKSIZE;
   126215           *pnLoad = nByte;
   126216         }
   126217         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   126218         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   126219         if( rc!=SQLITE_OK ){
   126220           sqlite3_free(aByte);
   126221           aByte = 0;
   126222         }
   126223       }
   126224       *paBlob = aByte;
   126225     }
   126226   }
   126227 
   126228   return rc;
   126229 }
   126230 
   126231 /*
   126232 ** Close the blob handle at p->pSegments, if it is open. See comments above
   126233 ** the sqlite3Fts3ReadBlock() function for details.
   126234 */
   126235 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   126236   sqlite3_blob_close(p->pSegments);
   126237   p->pSegments = 0;
   126238 }
   126239 
   126240 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   126241   int nRead;                      /* Number of bytes to read */
   126242   int rc;                         /* Return code */
   126243 
   126244   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   126245   rc = sqlite3_blob_read(
   126246       pReader->pBlob,
   126247       &pReader->aNode[pReader->nPopulate],
   126248       nRead,
   126249       pReader->nPopulate
   126250   );
   126251 
   126252   if( rc==SQLITE_OK ){
   126253     pReader->nPopulate += nRead;
   126254     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
   126255     if( pReader->nPopulate==pReader->nNode ){
   126256       sqlite3_blob_close(pReader->pBlob);
   126257       pReader->pBlob = 0;
   126258       pReader->nPopulate = 0;
   126259     }
   126260   }
   126261   return rc;
   126262 }
   126263 
   126264 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   126265   int rc = SQLITE_OK;
   126266   assert( !pReader->pBlob
   126267        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   126268   );
   126269   while( pReader->pBlob && rc==SQLITE_OK
   126270      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   126271   ){
   126272     rc = fts3SegReaderIncrRead(pReader);
   126273   }
   126274   return rc;
   126275 }
   126276 
   126277 /*
   126278 ** Set an Fts3SegReader cursor to point at EOF.
   126279 */
   126280 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
   126281   if( !fts3SegReaderIsRootOnly(pSeg) ){
   126282     sqlite3_free(pSeg->aNode);
   126283     sqlite3_blob_close(pSeg->pBlob);
   126284     pSeg->pBlob = 0;
   126285   }
   126286   pSeg->aNode = 0;
   126287 }
   126288 
   126289 /*
   126290 ** Move the iterator passed as the first argument to the next term in the
   126291 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   126292 ** SQLITE_DONE. Otherwise, an SQLite error code.
   126293 */
   126294 static int fts3SegReaderNext(
   126295   Fts3Table *p,
   126296   Fts3SegReader *pReader,
   126297   int bIncr
   126298 ){
   126299   int rc;                         /* Return code of various sub-routines */
   126300   char *pNext;                    /* Cursor variable */
   126301   int nPrefix;                    /* Number of bytes in term prefix */
   126302   int nSuffix;                    /* Number of bytes in term suffix */
   126303 
   126304   if( !pReader->aDoclist ){
   126305     pNext = pReader->aNode;
   126306   }else{
   126307     pNext = &pReader->aDoclist[pReader->nDoclist];
   126308   }
   126309 
   126310   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   126311 
   126312     if( fts3SegReaderIsPending(pReader) ){
   126313       Fts3HashElem *pElem = *(pReader->ppNextElem);
   126314       if( pElem==0 ){
   126315         pReader->aNode = 0;
   126316       }else{
   126317         PendingList *pList = (PendingList *)fts3HashData(pElem);
   126318         pReader->zTerm = (char *)fts3HashKey(pElem);
   126319         pReader->nTerm = fts3HashKeysize(pElem);
   126320         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   126321         pReader->aNode = pReader->aDoclist = pList->aData;
   126322         pReader->ppNextElem++;
   126323         assert( pReader->aNode );
   126324       }
   126325       return SQLITE_OK;
   126326     }
   126327 
   126328     fts3SegReaderSetEof(pReader);
   126329 
   126330     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   126331     ** blocks have already been traversed.  */
   126332     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   126333     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   126334       return SQLITE_OK;
   126335     }
   126336 
   126337     rc = sqlite3Fts3ReadBlock(
   126338         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
   126339         (bIncr ? &pReader->nPopulate : 0)
   126340     );
   126341     if( rc!=SQLITE_OK ) return rc;
   126342     assert( pReader->pBlob==0 );
   126343     if( bIncr && pReader->nPopulate<pReader->nNode ){
   126344       pReader->pBlob = p->pSegments;
   126345       p->pSegments = 0;
   126346     }
   126347     pNext = pReader->aNode;
   126348   }
   126349 
   126350   assert( !fts3SegReaderIsPending(pReader) );
   126351 
   126352   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   126353   if( rc!=SQLITE_OK ) return rc;
   126354 
   126355   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   126356   ** safe (no risk of overread) even if the node data is corrupted. */
   126357   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
   126358   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
   126359   if( nPrefix<0 || nSuffix<=0
   126360    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   126361   ){
   126362     return FTS_CORRUPT_VTAB;
   126363   }
   126364 
   126365   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   126366     int nNew = (nPrefix+nSuffix)*2;
   126367     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   126368     if( !zNew ){
   126369       return SQLITE_NOMEM;
   126370     }
   126371     pReader->zTerm = zNew;
   126372     pReader->nTermAlloc = nNew;
   126373   }
   126374 
   126375   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
   126376   if( rc!=SQLITE_OK ) return rc;
   126377 
   126378   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   126379   pReader->nTerm = nPrefix+nSuffix;
   126380   pNext += nSuffix;
   126381   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
   126382   pReader->aDoclist = pNext;
   126383   pReader->pOffsetList = 0;
   126384 
   126385   /* Check that the doclist does not appear to extend past the end of the
   126386   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   126387   ** of these statements is untrue, then the data structure is corrupt.
   126388   */
   126389   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   126390    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
   126391   ){
   126392     return FTS_CORRUPT_VTAB;
   126393   }
   126394   return SQLITE_OK;
   126395 }
   126396 
   126397 /*
   126398 ** Set the SegReader to point to the first docid in the doclist associated
   126399 ** with the current term.
   126400 */
   126401 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
   126402   int rc = SQLITE_OK;
   126403   assert( pReader->aDoclist );
   126404   assert( !pReader->pOffsetList );
   126405   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   126406     u8 bEof = 0;
   126407     pReader->iDocid = 0;
   126408     pReader->nOffsetList = 0;
   126409     sqlite3Fts3DoclistPrev(0,
   126410         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
   126411         &pReader->iDocid, &pReader->nOffsetList, &bEof
   126412     );
   126413   }else{
   126414     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
   126415     if( rc==SQLITE_OK ){
   126416       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   126417       pReader->pOffsetList = &pReader->aDoclist[n];
   126418     }
   126419   }
   126420   return rc;
   126421 }
   126422 
   126423 /*
   126424 ** Advance the SegReader to point to the next docid in the doclist
   126425 ** associated with the current term.
   126426 **
   126427 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   126428 ** *ppOffsetList is set to point to the first column-offset list
   126429 ** in the doclist entry (i.e. immediately past the docid varint).
   126430 ** *pnOffsetList is set to the length of the set of column-offset
   126431 ** lists, not including the nul-terminator byte. For example:
   126432 */
   126433 static int fts3SegReaderNextDocid(
   126434   Fts3Table *pTab,
   126435   Fts3SegReader *pReader,         /* Reader to advance to next docid */
   126436   char **ppOffsetList,            /* OUT: Pointer to current position-list */
   126437   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
   126438 ){
   126439   int rc = SQLITE_OK;
   126440   char *p = pReader->pOffsetList;
   126441   char c = 0;
   126442 
   126443   assert( p );
   126444 
   126445   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   126446     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
   126447     ** Pending-terms doclists are always built up in ascending order, so
   126448     ** we have to iterate through them backwards here. */
   126449     u8 bEof = 0;
   126450     if( ppOffsetList ){
   126451       *ppOffsetList = pReader->pOffsetList;
   126452       *pnOffsetList = pReader->nOffsetList - 1;
   126453     }
   126454     sqlite3Fts3DoclistPrev(0,
   126455         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
   126456         &pReader->nOffsetList, &bEof
   126457     );
   126458     if( bEof ){
   126459       pReader->pOffsetList = 0;
   126460     }else{
   126461       pReader->pOffsetList = p;
   126462     }
   126463   }else{
   126464     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
   126465 
   126466     /* Pointer p currently points at the first byte of an offset list. The
   126467     ** following block advances it to point one byte past the end of
   126468     ** the same offset list. */
   126469     while( 1 ){
   126470 
   126471       /* The following line of code (and the "p++" below the while() loop) is
   126472       ** normally all that is required to move pointer p to the desired
   126473       ** position. The exception is if this node is being loaded from disk
   126474       ** incrementally and pointer "p" now points to the first byte passed
   126475       ** the populated part of pReader->aNode[].
   126476       */
   126477       while( *p | c ) c = *p++ & 0x80;
   126478       assert( *p==0 );
   126479 
   126480       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
   126481       rc = fts3SegReaderIncrRead(pReader);
   126482       if( rc!=SQLITE_OK ) return rc;
   126483     }
   126484     p++;
   126485 
   126486     /* If required, populate the output variables with a pointer to and the
   126487     ** size of the previous offset-list.
   126488     */
   126489     if( ppOffsetList ){
   126490       *ppOffsetList = pReader->pOffsetList;
   126491       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   126492     }
   126493 
   126494     while( p<pEnd && *p==0 ) p++;
   126495 
   126496     /* If there are no more entries in the doclist, set pOffsetList to
   126497     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   126498     ** Fts3SegReader.pOffsetList to point to the next offset list before
   126499     ** returning.
   126500     */
   126501     if( p>=pEnd ){
   126502       pReader->pOffsetList = 0;
   126503     }else{
   126504       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
   126505       if( rc==SQLITE_OK ){
   126506         sqlite3_int64 iDelta;
   126507         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   126508         if( pTab->bDescIdx ){
   126509           pReader->iDocid -= iDelta;
   126510         }else{
   126511           pReader->iDocid += iDelta;
   126512         }
   126513       }
   126514     }
   126515   }
   126516 
   126517   return SQLITE_OK;
   126518 }
   126519 
   126520 
   126521 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
   126522   Fts3Cursor *pCsr,
   126523   Fts3MultiSegReader *pMsr,
   126524   int *pnOvfl
   126525 ){
   126526   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   126527   int nOvfl = 0;
   126528   int ii;
   126529   int rc = SQLITE_OK;
   126530   int pgsz = p->nPgsz;
   126531 
   126532   assert( p->bHasStat );
   126533   assert( pgsz>0 );
   126534 
   126535   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
   126536     Fts3SegReader *pReader = pMsr->apSegment[ii];
   126537     if( !fts3SegReaderIsPending(pReader)
   126538      && !fts3SegReaderIsRootOnly(pReader)
   126539     ){
   126540       sqlite3_int64 jj;
   126541       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
   126542         int nBlob;
   126543         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
   126544         if( rc!=SQLITE_OK ) break;
   126545         if( (nBlob+35)>pgsz ){
   126546           nOvfl += (nBlob + 34)/pgsz;
   126547         }
   126548       }
   126549     }
   126550   }
   126551   *pnOvfl = nOvfl;
   126552   return rc;
   126553 }
   126554 
   126555 /*
   126556 ** Free all allocations associated with the iterator passed as the
   126557 ** second argument.
   126558 */
   126559 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   126560   if( pReader && !fts3SegReaderIsPending(pReader) ){
   126561     sqlite3_free(pReader->zTerm);
   126562     if( !fts3SegReaderIsRootOnly(pReader) ){
   126563       sqlite3_free(pReader->aNode);
   126564       sqlite3_blob_close(pReader->pBlob);
   126565     }
   126566   }
   126567   sqlite3_free(pReader);
   126568 }
   126569 
   126570 /*
   126571 ** Allocate a new SegReader object.
   126572 */
   126573 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   126574   int iAge,                       /* Segment "age". */
   126575   int bLookup,                    /* True for a lookup only */
   126576   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   126577   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   126578   sqlite3_int64 iEndBlock,        /* Final block of segment */
   126579   const char *zRoot,              /* Buffer containing root node */
   126580   int nRoot,                      /* Size of buffer containing root node */
   126581   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   126582 ){
   126583   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   126584   int nExtra = 0;                 /* Bytes to allocate segment root node */
   126585 
   126586   assert( iStartLeaf<=iEndLeaf );
   126587   if( iStartLeaf==0 ){
   126588     nExtra = nRoot + FTS3_NODE_PADDING;
   126589   }
   126590 
   126591   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   126592   if( !pReader ){
   126593     return SQLITE_NOMEM;
   126594   }
   126595   memset(pReader, 0, sizeof(Fts3SegReader));
   126596   pReader->iIdx = iAge;
   126597   pReader->bLookup = bLookup;
   126598   pReader->iStartBlock = iStartLeaf;
   126599   pReader->iLeafEndBlock = iEndLeaf;
   126600   pReader->iEndBlock = iEndBlock;
   126601 
   126602   if( nExtra ){
   126603     /* The entire segment is stored in the root node. */
   126604     pReader->aNode = (char *)&pReader[1];
   126605     pReader->nNode = nRoot;
   126606     memcpy(pReader->aNode, zRoot, nRoot);
   126607     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   126608   }else{
   126609     pReader->iCurrentBlock = iStartLeaf-1;
   126610   }
   126611   *ppReader = pReader;
   126612   return SQLITE_OK;
   126613 }
   126614 
   126615 /*
   126616 ** This is a comparison function used as a qsort() callback when sorting
   126617 ** an array of pending terms by term. This occurs as part of flushing
   126618 ** the contents of the pending-terms hash table to the database.
   126619 */
   126620 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   126621   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   126622   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   126623   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   126624   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   126625 
   126626   int n = (n1<n2 ? n1 : n2);
   126627   int c = memcmp(z1, z2, n);
   126628   if( c==0 ){
   126629     c = n1 - n2;
   126630   }
   126631   return c;
   126632 }
   126633 
   126634 /*
   126635 ** This function is used to allocate an Fts3SegReader that iterates through
   126636 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   126637 **
   126638 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
   126639 ** through each term in the pending-terms table. Or, if isPrefixIter is
   126640 ** non-zero, it iterates through each term and its prefixes. For example, if
   126641 ** the pending terms hash table contains the terms "sqlite", "mysql" and
   126642 ** "firebird", then the iterator visits the following 'terms' (in the order
   126643 ** shown):
   126644 **
   126645 **   f fi fir fire fireb firebi firebir firebird
   126646 **   m my mys mysq mysql
   126647 **   s sq sql sqli sqlit sqlite
   126648 **
   126649 ** Whereas if isPrefixIter is zero, the terms visited are:
   126650 **
   126651 **   firebird mysql sqlite
   126652 */
   126653 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   126654   Fts3Table *p,                   /* Virtual table handle */
   126655   int iIndex,                     /* Index for p->aIndex */
   126656   const char *zTerm,              /* Term to search for */
   126657   int nTerm,                      /* Size of buffer zTerm */
   126658   int bPrefix,                    /* True for a prefix iterator */
   126659   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   126660 ){
   126661   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   126662   Fts3HashElem *pE;               /* Iterator variable */
   126663   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   126664   int nElem = 0;                  /* Size of array at aElem */
   126665   int rc = SQLITE_OK;             /* Return Code */
   126666   Fts3Hash *pHash;
   126667 
   126668   pHash = &p->aIndex[iIndex].hPending;
   126669   if( bPrefix ){
   126670     int nAlloc = 0;               /* Size of allocated array at aElem */
   126671 
   126672     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
   126673       char *zKey = (char *)fts3HashKey(pE);
   126674       int nKey = fts3HashKeysize(pE);
   126675       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   126676         if( nElem==nAlloc ){
   126677           Fts3HashElem **aElem2;
   126678           nAlloc += 16;
   126679           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   126680               aElem, nAlloc*sizeof(Fts3HashElem *)
   126681           );
   126682           if( !aElem2 ){
   126683             rc = SQLITE_NOMEM;
   126684             nElem = 0;
   126685             break;
   126686           }
   126687           aElem = aElem2;
   126688         }
   126689 
   126690         aElem[nElem++] = pE;
   126691       }
   126692     }
   126693 
   126694     /* If more than one term matches the prefix, sort the Fts3HashElem
   126695     ** objects in term order using qsort(). This uses the same comparison
   126696     ** callback as is used when flushing terms to disk.
   126697     */
   126698     if( nElem>1 ){
   126699       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   126700     }
   126701 
   126702   }else{
   126703     /* The query is a simple term lookup that matches at most one term in
   126704     ** the index. All that is required is a straight hash-lookup.
   126705     **
   126706     ** Because the stack address of pE may be accessed via the aElem pointer
   126707     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
   126708     ** within this entire function, not just this "else{...}" block.
   126709     */
   126710     pE = fts3HashFindElem(pHash, zTerm, nTerm);
   126711     if( pE ){
   126712       aElem = &pE;
   126713       nElem = 1;
   126714     }
   126715   }
   126716 
   126717   if( nElem>0 ){
   126718     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   126719     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   126720     if( !pReader ){
   126721       rc = SQLITE_NOMEM;
   126722     }else{
   126723       memset(pReader, 0, nByte);
   126724       pReader->iIdx = 0x7FFFFFFF;
   126725       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   126726       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   126727     }
   126728   }
   126729 
   126730   if( bPrefix ){
   126731     sqlite3_free(aElem);
   126732   }
   126733   *ppReader = pReader;
   126734   return rc;
   126735 }
   126736 
   126737 /*
   126738 ** Compare the entries pointed to by two Fts3SegReader structures.
   126739 ** Comparison is as follows:
   126740 **
   126741 **   1) EOF is greater than not EOF.
   126742 **
   126743 **   2) The current terms (if any) are compared using memcmp(). If one
   126744 **      term is a prefix of another, the longer term is considered the
   126745 **      larger.
   126746 **
   126747 **   3) By segment age. An older segment is considered larger.
   126748 */
   126749 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126750   int rc;
   126751   if( pLhs->aNode && pRhs->aNode ){
   126752     int rc2 = pLhs->nTerm - pRhs->nTerm;
   126753     if( rc2<0 ){
   126754       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   126755     }else{
   126756       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   126757     }
   126758     if( rc==0 ){
   126759       rc = rc2;
   126760     }
   126761   }else{
   126762     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   126763   }
   126764   if( rc==0 ){
   126765     rc = pRhs->iIdx - pLhs->iIdx;
   126766   }
   126767   assert( rc!=0 );
   126768   return rc;
   126769 }
   126770 
   126771 /*
   126772 ** A different comparison function for SegReader structures. In this
   126773 ** version, it is assumed that each SegReader points to an entry in
   126774 ** a doclist for identical terms. Comparison is made as follows:
   126775 **
   126776 **   1) EOF (end of doclist in this case) is greater than not EOF.
   126777 **
   126778 **   2) By current docid.
   126779 **
   126780 **   3) By segment age. An older segment is considered larger.
   126781 */
   126782 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126783   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   126784   if( rc==0 ){
   126785     if( pLhs->iDocid==pRhs->iDocid ){
   126786       rc = pRhs->iIdx - pLhs->iIdx;
   126787     }else{
   126788       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   126789     }
   126790   }
   126791   assert( pLhs->aNode && pRhs->aNode );
   126792   return rc;
   126793 }
   126794 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126795   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   126796   if( rc==0 ){
   126797     if( pLhs->iDocid==pRhs->iDocid ){
   126798       rc = pRhs->iIdx - pLhs->iIdx;
   126799     }else{
   126800       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
   126801     }
   126802   }
   126803   assert( pLhs->aNode && pRhs->aNode );
   126804   return rc;
   126805 }
   126806 
   126807 /*
   126808 ** Compare the term that the Fts3SegReader object passed as the first argument
   126809 ** points to with the term specified by arguments zTerm and nTerm.
   126810 **
   126811 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   126812 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   126813 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   126814 */
   126815 static int fts3SegReaderTermCmp(
   126816   Fts3SegReader *pSeg,            /* Segment reader object */
   126817   const char *zTerm,              /* Term to compare to */
   126818   int nTerm                       /* Size of term zTerm in bytes */
   126819 ){
   126820   int res = 0;
   126821   if( pSeg->aNode ){
   126822     if( pSeg->nTerm>nTerm ){
   126823       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   126824     }else{
   126825       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   126826     }
   126827     if( res==0 ){
   126828       res = pSeg->nTerm-nTerm;
   126829     }
   126830   }
   126831   return res;
   126832 }
   126833 
   126834 /*
   126835 ** Argument apSegment is an array of nSegment elements. It is known that
   126836 ** the final (nSegment-nSuspect) members are already in sorted order
   126837 ** (according to the comparison function provided). This function shuffles
   126838 ** the array around until all entries are in sorted order.
   126839 */
   126840 static void fts3SegReaderSort(
   126841   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   126842   int nSegment,                                  /* Size of apSegment array */
   126843   int nSuspect,                                  /* Unsorted entry count */
   126844   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   126845 ){
   126846   int i;                          /* Iterator variable */
   126847 
   126848   assert( nSuspect<=nSegment );
   126849 
   126850   if( nSuspect==nSegment ) nSuspect--;
   126851   for(i=nSuspect-1; i>=0; i--){
   126852     int j;
   126853     for(j=i; j<(nSegment-1); j++){
   126854       Fts3SegReader *pTmp;
   126855       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   126856       pTmp = apSegment[j+1];
   126857       apSegment[j+1] = apSegment[j];
   126858       apSegment[j] = pTmp;
   126859     }
   126860   }
   126861 
   126862 #ifndef NDEBUG
   126863   /* Check that the list really is sorted now. */
   126864   for(i=0; i<(nSuspect-1); i++){
   126865     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   126866   }
   126867 #endif
   126868 }
   126869 
   126870 /*
   126871 ** Insert a record into the %_segments table.
   126872 */
   126873 static int fts3WriteSegment(
   126874   Fts3Table *p,                   /* Virtual table handle */
   126875   sqlite3_int64 iBlock,           /* Block id for new block */
   126876   char *z,                        /* Pointer to buffer containing block data */
   126877   int n                           /* Size of buffer z in bytes */
   126878 ){
   126879   sqlite3_stmt *pStmt;
   126880   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   126881   if( rc==SQLITE_OK ){
   126882     sqlite3_bind_int64(pStmt, 1, iBlock);
   126883     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   126884     sqlite3_step(pStmt);
   126885     rc = sqlite3_reset(pStmt);
   126886   }
   126887   return rc;
   126888 }
   126889 
   126890 /*
   126891 ** Insert a record into the %_segdir table.
   126892 */
   126893 static int fts3WriteSegdir(
   126894   Fts3Table *p,                   /* Virtual table handle */
   126895   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
   126896   int iIdx,                       /* Value for "idx" field */
   126897   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   126898   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   126899   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   126900   char *zRoot,                    /* Blob value for "root" field */
   126901   int nRoot                       /* Number of bytes in buffer zRoot */
   126902 ){
   126903   sqlite3_stmt *pStmt;
   126904   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   126905   if( rc==SQLITE_OK ){
   126906     sqlite3_bind_int64(pStmt, 1, iLevel);
   126907     sqlite3_bind_int(pStmt, 2, iIdx);
   126908     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   126909     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   126910     sqlite3_bind_int64(pStmt, 5, iEndBlock);
   126911     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   126912     sqlite3_step(pStmt);
   126913     rc = sqlite3_reset(pStmt);
   126914   }
   126915   return rc;
   126916 }
   126917 
   126918 /*
   126919 ** Return the size of the common prefix (if any) shared by zPrev and
   126920 ** zNext, in bytes. For example,
   126921 **
   126922 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   126923 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   126924 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   126925 */
   126926 static int fts3PrefixCompress(
   126927   const char *zPrev,              /* Buffer containing previous term */
   126928   int nPrev,                      /* Size of buffer zPrev in bytes */
   126929   const char *zNext,              /* Buffer containing next term */
   126930   int nNext                       /* Size of buffer zNext in bytes */
   126931 ){
   126932   int n;
   126933   UNUSED_PARAMETER(nNext);
   126934   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   126935   return n;
   126936 }
   126937 
   126938 /*
   126939 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   126940 ** (according to memcmp) than the previous term.
   126941 */
   126942 static int fts3NodeAddTerm(
   126943   Fts3Table *p,                   /* Virtual table handle */
   126944   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   126945   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   126946   const char *zTerm,              /* Pointer to buffer containing term */
   126947   int nTerm                       /* Size of term in bytes */
   126948 ){
   126949   SegmentNode *pTree = *ppTree;
   126950   int rc;
   126951   SegmentNode *pNew;
   126952 
   126953   /* First try to append the term to the current node. Return early if
   126954   ** this is possible.
   126955   */
   126956   if( pTree ){
   126957     int nData = pTree->nData;     /* Current size of node in bytes */
   126958     int nReq = nData;             /* Required space after adding zTerm */
   126959     int nPrefix;                  /* Number of bytes of prefix compression */
   126960     int nSuffix;                  /* Suffix length */
   126961 
   126962     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   126963     nSuffix = nTerm-nPrefix;
   126964 
   126965     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   126966     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   126967 
   126968       if( nReq>p->nNodeSize ){
   126969         /* An unusual case: this is the first term to be added to the node
   126970         ** and the static node buffer (p->nNodeSize bytes) is not large
   126971         ** enough. Use a separately malloced buffer instead This wastes
   126972         ** p->nNodeSize bytes, but since this scenario only comes about when
   126973         ** the database contain two terms that share a prefix of almost 2KB,
   126974         ** this is not expected to be a serious problem.
   126975         */
   126976         assert( pTree->aData==(char *)&pTree[1] );
   126977         pTree->aData = (char *)sqlite3_malloc(nReq);
   126978         if( !pTree->aData ){
   126979           return SQLITE_NOMEM;
   126980         }
   126981       }
   126982 
   126983       if( pTree->zTerm ){
   126984         /* There is no prefix-length field for first term in a node */
   126985         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   126986       }
   126987 
   126988       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   126989       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   126990       pTree->nData = nData + nSuffix;
   126991       pTree->nEntry++;
   126992 
   126993       if( isCopyTerm ){
   126994         if( pTree->nMalloc<nTerm ){
   126995           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   126996           if( !zNew ){
   126997             return SQLITE_NOMEM;
   126998           }
   126999           pTree->nMalloc = nTerm*2;
   127000           pTree->zMalloc = zNew;
   127001         }
   127002         pTree->zTerm = pTree->zMalloc;
   127003         memcpy(pTree->zTerm, zTerm, nTerm);
   127004         pTree->nTerm = nTerm;
   127005       }else{
   127006         pTree->zTerm = (char *)zTerm;
   127007         pTree->nTerm = nTerm;
   127008       }
   127009       return SQLITE_OK;
   127010     }
   127011   }
   127012 
   127013   /* If control flows to here, it was not possible to append zTerm to the
   127014   ** current node. Create a new node (a right-sibling of the current node).
   127015   ** If this is the first node in the tree, the term is added to it.
   127016   **
   127017   ** Otherwise, the term is not added to the new node, it is left empty for
   127018   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   127019   ** has no parent, one is created here.
   127020   */
   127021   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   127022   if( !pNew ){
   127023     return SQLITE_NOMEM;
   127024   }
   127025   memset(pNew, 0, sizeof(SegmentNode));
   127026   pNew->nData = 1 + FTS3_VARINT_MAX;
   127027   pNew->aData = (char *)&pNew[1];
   127028 
   127029   if( pTree ){
   127030     SegmentNode *pParent = pTree->pParent;
   127031     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   127032     if( pTree->pParent==0 ){
   127033       pTree->pParent = pParent;
   127034     }
   127035     pTree->pRight = pNew;
   127036     pNew->pLeftmost = pTree->pLeftmost;
   127037     pNew->pParent = pParent;
   127038     pNew->zMalloc = pTree->zMalloc;
   127039     pNew->nMalloc = pTree->nMalloc;
   127040     pTree->zMalloc = 0;
   127041   }else{
   127042     pNew->pLeftmost = pNew;
   127043     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   127044   }
   127045 
   127046   *ppTree = pNew;
   127047   return rc;
   127048 }
   127049 
   127050 /*
   127051 ** Helper function for fts3NodeWrite().
   127052 */
   127053 static int fts3TreeFinishNode(
   127054   SegmentNode *pTree,
   127055   int iHeight,
   127056   sqlite3_int64 iLeftChild
   127057 ){
   127058   int nStart;
   127059   assert( iHeight>=1 && iHeight<128 );
   127060   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   127061   pTree->aData[nStart] = (char)iHeight;
   127062   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   127063   return nStart;
   127064 }
   127065 
   127066 /*
   127067 ** Write the buffer for the segment node pTree and all of its peers to the
   127068 ** database. Then call this function recursively to write the parent of
   127069 ** pTree and its peers to the database.
   127070 **
   127071 ** Except, if pTree is a root node, do not write it to the database. Instead,
   127072 ** set output variables *paRoot and *pnRoot to contain the root node.
   127073 **
   127074 ** If successful, SQLITE_OK is returned and output variable *piLast is
   127075 ** set to the largest blockid written to the database (or zero if no
   127076 ** blocks were written to the db). Otherwise, an SQLite error code is
   127077 ** returned.
   127078 */
   127079 static int fts3NodeWrite(
   127080   Fts3Table *p,                   /* Virtual table handle */
   127081   SegmentNode *pTree,             /* SegmentNode handle */
   127082   int iHeight,                    /* Height of this node in tree */
   127083   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   127084   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   127085   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   127086   char **paRoot,                  /* OUT: Data for root node */
   127087   int *pnRoot                     /* OUT: Size of root node in bytes */
   127088 ){
   127089   int rc = SQLITE_OK;
   127090 
   127091   if( !pTree->pParent ){
   127092     /* Root node of the tree. */
   127093     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   127094     *piLast = iFree-1;
   127095     *pnRoot = pTree->nData - nStart;
   127096     *paRoot = &pTree->aData[nStart];
   127097   }else{
   127098     SegmentNode *pIter;
   127099     sqlite3_int64 iNextFree = iFree;
   127100     sqlite3_int64 iNextLeaf = iLeaf;
   127101     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   127102       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   127103       int nWrite = pIter->nData - nStart;
   127104 
   127105       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   127106       iNextFree++;
   127107       iNextLeaf += (pIter->nEntry+1);
   127108     }
   127109     if( rc==SQLITE_OK ){
   127110       assert( iNextLeaf==iFree );
   127111       rc = fts3NodeWrite(
   127112           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   127113       );
   127114     }
   127115   }
   127116 
   127117   return rc;
   127118 }
   127119 
   127120 /*
   127121 ** Free all memory allocations associated with the tree pTree.
   127122 */
   127123 static void fts3NodeFree(SegmentNode *pTree){
   127124   if( pTree ){
   127125     SegmentNode *p = pTree->pLeftmost;
   127126     fts3NodeFree(p->pParent);
   127127     while( p ){
   127128       SegmentNode *pRight = p->pRight;
   127129       if( p->aData!=(char *)&p[1] ){
   127130         sqlite3_free(p->aData);
   127131       }
   127132       assert( pRight==0 || p->zMalloc==0 );
   127133       sqlite3_free(p->zMalloc);
   127134       sqlite3_free(p);
   127135       p = pRight;
   127136     }
   127137   }
   127138 }
   127139 
   127140 /*
   127141 ** Add a term to the segment being constructed by the SegmentWriter object
   127142 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   127143 ** be passed NULL. This function will allocate a new SegmentWriter object
   127144 ** and return it via the input/output variable *ppWriter in this case.
   127145 **
   127146 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   127147 */
   127148 static int fts3SegWriterAdd(
   127149   Fts3Table *p,                   /* Virtual table handle */
   127150   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   127151   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   127152   const char *zTerm,              /* Pointer to buffer containing term */
   127153   int nTerm,                      /* Size of term in bytes */
   127154   const char *aDoclist,           /* Pointer to buffer containing doclist */
   127155   int nDoclist                    /* Size of doclist in bytes */
   127156 ){
   127157   int nPrefix;                    /* Size of term prefix in bytes */
   127158   int nSuffix;                    /* Size of term suffix in bytes */
   127159   int nReq;                       /* Number of bytes required on leaf page */
   127160   int nData;
   127161   SegmentWriter *pWriter = *ppWriter;
   127162 
   127163   if( !pWriter ){
   127164     int rc;
   127165     sqlite3_stmt *pStmt;
   127166 
   127167     /* Allocate the SegmentWriter structure */
   127168     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   127169     if( !pWriter ) return SQLITE_NOMEM;
   127170     memset(pWriter, 0, sizeof(SegmentWriter));
   127171     *ppWriter = pWriter;
   127172 
   127173     /* Allocate a buffer in which to accumulate data */
   127174     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   127175     if( !pWriter->aData ) return SQLITE_NOMEM;
   127176     pWriter->nSize = p->nNodeSize;
   127177 
   127178     /* Find the next free blockid in the %_segments table */
   127179     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   127180     if( rc!=SQLITE_OK ) return rc;
   127181     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127182       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   127183       pWriter->iFirst = pWriter->iFree;
   127184     }
   127185     rc = sqlite3_reset(pStmt);
   127186     if( rc!=SQLITE_OK ) return rc;
   127187   }
   127188   nData = pWriter->nData;
   127189 
   127190   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   127191   nSuffix = nTerm-nPrefix;
   127192 
   127193   /* Figure out how many bytes are required by this new entry */
   127194   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   127195     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   127196     nSuffix +                               /* Term suffix */
   127197     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   127198     nDoclist;                               /* Doclist data */
   127199 
   127200   if( nData>0 && nData+nReq>p->nNodeSize ){
   127201     int rc;
   127202 
   127203     /* The current leaf node is full. Write it out to the database. */
   127204     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   127205     if( rc!=SQLITE_OK ) return rc;
   127206 
   127207     /* Add the current term to the interior node tree. The term added to
   127208     ** the interior tree must:
   127209     **
   127210     **   a) be greater than the largest term on the leaf node just written
   127211     **      to the database (still available in pWriter->zTerm), and
   127212     **
   127213     **   b) be less than or equal to the term about to be added to the new
   127214     **      leaf node (zTerm/nTerm).
   127215     **
   127216     ** In other words, it must be the prefix of zTerm 1 byte longer than
   127217     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   127218     */
   127219     assert( nPrefix<nTerm );
   127220     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   127221     if( rc!=SQLITE_OK ) return rc;
   127222 
   127223     nData = 0;
   127224     pWriter->nTerm = 0;
   127225 
   127226     nPrefix = 0;
   127227     nSuffix = nTerm;
   127228     nReq = 1 +                              /* varint containing prefix size */
   127229       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   127230       nTerm +                               /* Term suffix */
   127231       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   127232       nDoclist;                             /* Doclist data */
   127233   }
   127234 
   127235   /* If the buffer currently allocated is too small for this entry, realloc
   127236   ** the buffer to make it large enough.
   127237   */
   127238   if( nReq>pWriter->nSize ){
   127239     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   127240     if( !aNew ) return SQLITE_NOMEM;
   127241     pWriter->aData = aNew;
   127242     pWriter->nSize = nReq;
   127243   }
   127244   assert( nData+nReq<=pWriter->nSize );
   127245 
   127246   /* Append the prefix-compressed term and doclist to the buffer. */
   127247   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   127248   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   127249   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   127250   nData += nSuffix;
   127251   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   127252   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   127253   pWriter->nData = nData + nDoclist;
   127254 
   127255   /* Save the current term so that it can be used to prefix-compress the next.
   127256   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   127257   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   127258   ** store a copy of the pointer.
   127259   */
   127260   if( isCopyTerm ){
   127261     if( nTerm>pWriter->nMalloc ){
   127262       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   127263       if( !zNew ){
   127264         return SQLITE_NOMEM;
   127265       }
   127266       pWriter->nMalloc = nTerm*2;
   127267       pWriter->zMalloc = zNew;
   127268       pWriter->zTerm = zNew;
   127269     }
   127270     assert( pWriter->zTerm==pWriter->zMalloc );
   127271     memcpy(pWriter->zTerm, zTerm, nTerm);
   127272   }else{
   127273     pWriter->zTerm = (char *)zTerm;
   127274   }
   127275   pWriter->nTerm = nTerm;
   127276 
   127277   return SQLITE_OK;
   127278 }
   127279 
   127280 /*
   127281 ** Flush all data associated with the SegmentWriter object pWriter to the
   127282 ** database. This function must be called after all terms have been added
   127283 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   127284 ** returned. Otherwise, an SQLite error code.
   127285 */
   127286 static int fts3SegWriterFlush(
   127287   Fts3Table *p,                   /* Virtual table handle */
   127288   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   127289   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
   127290   int iIdx                        /* Value for 'idx' column of %_segdir */
   127291 ){
   127292   int rc;                         /* Return code */
   127293   if( pWriter->pTree ){
   127294     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   127295     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   127296     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   127297     int nRoot = 0;                /* Size of buffer zRoot */
   127298 
   127299     iLastLeaf = pWriter->iFree;
   127300     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   127301     if( rc==SQLITE_OK ){
   127302       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   127303           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   127304     }
   127305     if( rc==SQLITE_OK ){
   127306       rc = fts3WriteSegdir(
   127307           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
   127308     }
   127309   }else{
   127310     /* The entire tree fits on the root node. Write it to the segdir table. */
   127311     rc = fts3WriteSegdir(
   127312         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
   127313   }
   127314   return rc;
   127315 }
   127316 
   127317 /*
   127318 ** Release all memory held by the SegmentWriter object passed as the
   127319 ** first argument.
   127320 */
   127321 static void fts3SegWriterFree(SegmentWriter *pWriter){
   127322   if( pWriter ){
   127323     sqlite3_free(pWriter->aData);
   127324     sqlite3_free(pWriter->zMalloc);
   127325     fts3NodeFree(pWriter->pTree);
   127326     sqlite3_free(pWriter);
   127327   }
   127328 }
   127329 
   127330 /*
   127331 ** The first value in the apVal[] array is assumed to contain an integer.
   127332 ** This function tests if there exist any documents with docid values that
   127333 ** are different from that integer. i.e. if deleting the document with docid
   127334 ** pRowid would mean the FTS3 table were empty.
   127335 **
   127336 ** If successful, *pisEmpty is set to true if the table is empty except for
   127337 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
   127338 ** error occurs, an SQLite error code is returned.
   127339 */
   127340 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
   127341   sqlite3_stmt *pStmt;
   127342   int rc;
   127343   if( p->zContentTbl ){
   127344     /* If using the content=xxx option, assume the table is never empty */
   127345     *pisEmpty = 0;
   127346     rc = SQLITE_OK;
   127347   }else{
   127348     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
   127349     if( rc==SQLITE_OK ){
   127350       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127351         *pisEmpty = sqlite3_column_int(pStmt, 0);
   127352       }
   127353       rc = sqlite3_reset(pStmt);
   127354     }
   127355   }
   127356   return rc;
   127357 }
   127358 
   127359 /*
   127360 ** Set *pnMax to the largest segment level in the database for the index
   127361 ** iIndex.
   127362 **
   127363 ** Segment levels are stored in the 'level' column of the %_segdir table.
   127364 **
   127365 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   127366 */
   127367 static int fts3SegmentMaxLevel(
   127368   Fts3Table *p,
   127369   int iLangid,
   127370   int iIndex,
   127371   sqlite3_int64 *pnMax
   127372 ){
   127373   sqlite3_stmt *pStmt;
   127374   int rc;
   127375   assert( iIndex>=0 && iIndex<p->nIndex );
   127376 
   127377   /* Set pStmt to the compiled version of:
   127378   **
   127379   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   127380   **
   127381   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   127382   */
   127383   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   127384   if( rc!=SQLITE_OK ) return rc;
   127385   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   127386   sqlite3_bind_int64(pStmt, 2,
   127387       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   127388   );
   127389   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127390     *pnMax = sqlite3_column_int64(pStmt, 0);
   127391   }
   127392   return sqlite3_reset(pStmt);
   127393 }
   127394 
   127395 /*
   127396 ** This function is used after merging multiple segments into a single large
   127397 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   127398 ** it:
   127399 **
   127400 **   1) Deletes all %_segments entries for the segments associated with
   127401 **      each of the SegReader objects in the array passed as the third
   127402 **      argument, and
   127403 **
   127404 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   127405 **      entries regardless of level if (iLevel<0).
   127406 **
   127407 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   127408 */
   127409 static int fts3DeleteSegdir(
   127410   Fts3Table *p,                   /* Virtual table handle */
   127411   int iLangid,                    /* Language id */
   127412   int iIndex,                     /* Index for p->aIndex */
   127413   int iLevel,                     /* Level of %_segdir entries to delete */
   127414   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   127415   int nReader                     /* Size of array apSegment */
   127416 ){
   127417   int rc;                         /* Return Code */
   127418   int i;                          /* Iterator variable */
   127419   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
   127420 
   127421   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   127422   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   127423     Fts3SegReader *pSegment = apSegment[i];
   127424     if( pSegment->iStartBlock ){
   127425       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
   127426       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
   127427       sqlite3_step(pDelete);
   127428       rc = sqlite3_reset(pDelete);
   127429     }
   127430   }
   127431   if( rc!=SQLITE_OK ){
   127432     return rc;
   127433   }
   127434 
   127435   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
   127436   if( iLevel==FTS3_SEGCURSOR_ALL ){
   127437     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
   127438     if( rc==SQLITE_OK ){
   127439       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   127440       sqlite3_bind_int64(pDelete, 2,
   127441           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   127442       );
   127443     }
   127444   }else{
   127445     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
   127446     if( rc==SQLITE_OK ){
   127447       sqlite3_bind_int64(
   127448           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   127449       );
   127450     }
   127451   }
   127452 
   127453   if( rc==SQLITE_OK ){
   127454     sqlite3_step(pDelete);
   127455     rc = sqlite3_reset(pDelete);
   127456   }
   127457 
   127458   return rc;
   127459 }
   127460 
   127461 /*
   127462 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   127463 ** a position list that may (or may not) feature multiple columns. This
   127464 ** function adjusts the pointer *ppList and the length *pnList so that they
   127465 ** identify the subset of the position list that corresponds to column iCol.
   127466 **
   127467 ** If there are no entries in the input position list for column iCol, then
   127468 ** *pnList is set to zero before returning.
   127469 */
   127470 static void fts3ColumnFilter(
   127471   int iCol,                       /* Column to filter on */
   127472   char **ppList,                  /* IN/OUT: Pointer to position list */
   127473   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   127474 ){
   127475   char *pList = *ppList;
   127476   int nList = *pnList;
   127477   char *pEnd = &pList[nList];
   127478   int iCurrent = 0;
   127479   char *p = pList;
   127480 
   127481   assert( iCol>=0 );
   127482   while( 1 ){
   127483     char c = 0;
   127484     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   127485 
   127486     if( iCol==iCurrent ){
   127487       nList = (int)(p - pList);
   127488       break;
   127489     }
   127490 
   127491     nList -= (int)(p - pList);
   127492     pList = p;
   127493     if( nList==0 ){
   127494       break;
   127495     }
   127496     p = &pList[1];
   127497     p += sqlite3Fts3GetVarint32(p, &iCurrent);
   127498   }
   127499 
   127500   *ppList = pList;
   127501   *pnList = nList;
   127502 }
   127503 
   127504 /*
   127505 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
   127506 ** existing data). Grow the buffer if required.
   127507 **
   127508 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
   127509 ** trying to resize the buffer, return SQLITE_NOMEM.
   127510 */
   127511 static int fts3MsrBufferData(
   127512   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   127513   char *pList,
   127514   int nList
   127515 ){
   127516   if( nList>pMsr->nBuffer ){
   127517     char *pNew;
   127518     pMsr->nBuffer = nList*2;
   127519     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
   127520     if( !pNew ) return SQLITE_NOMEM;
   127521     pMsr->aBuffer = pNew;
   127522   }
   127523 
   127524   memcpy(pMsr->aBuffer, pList, nList);
   127525   return SQLITE_OK;
   127526 }
   127527 
   127528 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   127529   Fts3Table *p,                   /* Virtual table handle */
   127530   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   127531   sqlite3_int64 *piDocid,         /* OUT: Docid value */
   127532   char **paPoslist,               /* OUT: Pointer to position list */
   127533   int *pnPoslist                  /* OUT: Size of position list in bytes */
   127534 ){
   127535   int nMerge = pMsr->nAdvance;
   127536   Fts3SegReader **apSegment = pMsr->apSegment;
   127537   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127538     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127539   );
   127540 
   127541   if( nMerge==0 ){
   127542     *paPoslist = 0;
   127543     return SQLITE_OK;
   127544   }
   127545 
   127546   while( 1 ){
   127547     Fts3SegReader *pSeg;
   127548     pSeg = pMsr->apSegment[0];
   127549 
   127550     if( pSeg->pOffsetList==0 ){
   127551       *paPoslist = 0;
   127552       break;
   127553     }else{
   127554       int rc;
   127555       char *pList;
   127556       int nList;
   127557       int j;
   127558       sqlite3_int64 iDocid = apSegment[0]->iDocid;
   127559 
   127560       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   127561       j = 1;
   127562       while( rc==SQLITE_OK
   127563         && j<nMerge
   127564         && apSegment[j]->pOffsetList
   127565         && apSegment[j]->iDocid==iDocid
   127566       ){
   127567         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   127568         j++;
   127569       }
   127570       if( rc!=SQLITE_OK ) return rc;
   127571       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
   127572 
   127573       if( pMsr->iColFilter>=0 ){
   127574         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
   127575       }
   127576 
   127577       if( nList>0 ){
   127578         if( fts3SegReaderIsPending(apSegment[0]) ){
   127579           rc = fts3MsrBufferData(pMsr, pList, nList+1);
   127580           if( rc!=SQLITE_OK ) return rc;
   127581           *paPoslist = pMsr->aBuffer;
   127582           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
   127583         }else{
   127584           *paPoslist = pList;
   127585         }
   127586         *piDocid = iDocid;
   127587         *pnPoslist = nList;
   127588         break;
   127589       }
   127590     }
   127591   }
   127592 
   127593   return SQLITE_OK;
   127594 }
   127595 
   127596 static int fts3SegReaderStart(
   127597   Fts3Table *p,                   /* Virtual table handle */
   127598   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127599   const char *zTerm,              /* Term searched for (or NULL) */
   127600   int nTerm                       /* Length of zTerm in bytes */
   127601 ){
   127602   int i;
   127603   int nSeg = pCsr->nSegment;
   127604 
   127605   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   127606   ** for, then advance each segment iterator until it points to a term of
   127607   ** equal or greater value than the specified term. This prevents many
   127608   ** unnecessary merge/sort operations for the case where single segment
   127609   ** b-tree leaf nodes contain more than one term.
   127610   */
   127611   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
   127612     int res = 0;
   127613     Fts3SegReader *pSeg = pCsr->apSegment[i];
   127614     do {
   127615       int rc = fts3SegReaderNext(p, pSeg, 0);
   127616       if( rc!=SQLITE_OK ) return rc;
   127617     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
   127618 
   127619     if( pSeg->bLookup && res!=0 ){
   127620       fts3SegReaderSetEof(pSeg);
   127621     }
   127622   }
   127623   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
   127624 
   127625   return SQLITE_OK;
   127626 }
   127627 
   127628 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
   127629   Fts3Table *p,                   /* Virtual table handle */
   127630   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127631   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
   127632 ){
   127633   pCsr->pFilter = pFilter;
   127634   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
   127635 }
   127636 
   127637 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   127638   Fts3Table *p,                   /* Virtual table handle */
   127639   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127640   int iCol,                       /* Column to match on. */
   127641   const char *zTerm,              /* Term to iterate through a doclist for */
   127642   int nTerm                       /* Number of bytes in zTerm */
   127643 ){
   127644   int i;
   127645   int rc;
   127646   int nSegment = pCsr->nSegment;
   127647   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127648     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127649   );
   127650 
   127651   assert( pCsr->pFilter==0 );
   127652   assert( zTerm && nTerm>0 );
   127653 
   127654   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
   127655   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
   127656   if( rc!=SQLITE_OK ) return rc;
   127657 
   127658   /* Determine how many of the segments actually point to zTerm/nTerm. */
   127659   for(i=0; i<nSegment; i++){
   127660     Fts3SegReader *pSeg = pCsr->apSegment[i];
   127661     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
   127662       break;
   127663     }
   127664   }
   127665   pCsr->nAdvance = i;
   127666 
   127667   /* Advance each of the segments to point to the first docid. */
   127668   for(i=0; i<pCsr->nAdvance; i++){
   127669     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
   127670     if( rc!=SQLITE_OK ) return rc;
   127671   }
   127672   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
   127673 
   127674   assert( iCol<0 || iCol<p->nColumn );
   127675   pCsr->iColFilter = iCol;
   127676 
   127677   return SQLITE_OK;
   127678 }
   127679 
   127680 /*
   127681 ** This function is called on a MultiSegReader that has been started using
   127682 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
   127683 ** have been made. Calling this function puts the MultiSegReader in such
   127684 ** a state that if the next two calls are:
   127685 **
   127686 **   sqlite3Fts3SegReaderStart()
   127687 **   sqlite3Fts3SegReaderStep()
   127688 **
   127689 ** then the entire doclist for the term is available in
   127690 ** MultiSegReader.aDoclist/nDoclist.
   127691 */
   127692 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   127693   int i;                          /* Used to iterate through segment-readers */
   127694 
   127695   assert( pCsr->zTerm==0 );
   127696   assert( pCsr->nTerm==0 );
   127697   assert( pCsr->aDoclist==0 );
   127698   assert( pCsr->nDoclist==0 );
   127699 
   127700   pCsr->nAdvance = 0;
   127701   pCsr->bRestart = 1;
   127702   for(i=0; i<pCsr->nSegment; i++){
   127703     pCsr->apSegment[i]->pOffsetList = 0;
   127704     pCsr->apSegment[i]->nOffsetList = 0;
   127705     pCsr->apSegment[i]->iDocid = 0;
   127706   }
   127707 
   127708   return SQLITE_OK;
   127709 }
   127710 
   127711 
   127712 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   127713   Fts3Table *p,                   /* Virtual table handle */
   127714   Fts3MultiSegReader *pCsr        /* Cursor object */
   127715 ){
   127716   int rc = SQLITE_OK;
   127717 
   127718   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   127719   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   127720   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   127721   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
   127722   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
   127723   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
   127724 
   127725   Fts3SegReader **apSegment = pCsr->apSegment;
   127726   int nSegment = pCsr->nSegment;
   127727   Fts3SegFilter *pFilter = pCsr->pFilter;
   127728   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127729     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127730   );
   127731 
   127732   if( pCsr->nSegment==0 ) return SQLITE_OK;
   127733 
   127734   do {
   127735     int nMerge;
   127736     int i;
   127737 
   127738     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
   127739     ** forward. Then sort the list in order of current term again.
   127740     */
   127741     for(i=0; i<pCsr->nAdvance; i++){
   127742       Fts3SegReader *pSeg = apSegment[i];
   127743       if( pSeg->bLookup ){
   127744         fts3SegReaderSetEof(pSeg);
   127745       }else{
   127746         rc = fts3SegReaderNext(p, pSeg, 0);
   127747       }
   127748       if( rc!=SQLITE_OK ) return rc;
   127749     }
   127750     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
   127751     pCsr->nAdvance = 0;
   127752 
   127753     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
   127754     assert( rc==SQLITE_OK );
   127755     if( apSegment[0]->aNode==0 ) break;
   127756 
   127757     pCsr->nTerm = apSegment[0]->nTerm;
   127758     pCsr->zTerm = apSegment[0]->zTerm;
   127759 
   127760     /* If this is a prefix-search, and if the term that apSegment[0] points
   127761     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   127762     ** required callbacks have been made. In this case exit early.
   127763     **
   127764     ** Similarly, if this is a search for an exact match, and the first term
   127765     ** of segment apSegment[0] is not a match, exit early.
   127766     */
   127767     if( pFilter->zTerm && !isScan ){
   127768       if( pCsr->nTerm<pFilter->nTerm
   127769        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
   127770        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
   127771       ){
   127772         break;
   127773       }
   127774     }
   127775 
   127776     nMerge = 1;
   127777     while( nMerge<nSegment
   127778         && apSegment[nMerge]->aNode
   127779         && apSegment[nMerge]->nTerm==pCsr->nTerm
   127780         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
   127781     ){
   127782       nMerge++;
   127783     }
   127784 
   127785     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   127786     if( nMerge==1
   127787      && !isIgnoreEmpty
   127788      && !isFirst
   127789      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
   127790     ){
   127791       pCsr->nDoclist = apSegment[0]->nDoclist;
   127792       if( fts3SegReaderIsPending(apSegment[0]) ){
   127793         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
   127794         pCsr->aDoclist = pCsr->aBuffer;
   127795       }else{
   127796         pCsr->aDoclist = apSegment[0]->aDoclist;
   127797       }
   127798       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
   127799     }else{
   127800       int nDoclist = 0;           /* Size of doclist */
   127801       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   127802 
   127803       /* The current term of the first nMerge entries in the array
   127804       ** of Fts3SegReader objects is the same. The doclists must be merged
   127805       ** and a single term returned with the merged doclist.
   127806       */
   127807       for(i=0; i<nMerge; i++){
   127808         fts3SegReaderFirstDocid(p, apSegment[i]);
   127809       }
   127810       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
   127811       while( apSegment[0]->pOffsetList ){
   127812         int j;                    /* Number of segments that share a docid */
   127813         char *pList;
   127814         int nList;
   127815         int nByte;
   127816         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   127817         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   127818         j = 1;
   127819         while( j<nMerge
   127820             && apSegment[j]->pOffsetList
   127821             && apSegment[j]->iDocid==iDocid
   127822         ){
   127823           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   127824           j++;
   127825         }
   127826 
   127827         if( isColFilter ){
   127828           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
   127829         }
   127830 
   127831         if( !isIgnoreEmpty || nList>0 ){
   127832 
   127833           /* Calculate the 'docid' delta value to write into the merged
   127834           ** doclist. */
   127835           sqlite3_int64 iDelta;
   127836           if( p->bDescIdx && nDoclist>0 ){
   127837             iDelta = iPrev - iDocid;
   127838           }else{
   127839             iDelta = iDocid - iPrev;
   127840           }
   127841           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
   127842           assert( nDoclist>0 || iDelta==iDocid );
   127843 
   127844           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
   127845           if( nDoclist+nByte>pCsr->nBuffer ){
   127846             char *aNew;
   127847             pCsr->nBuffer = (nDoclist+nByte)*2;
   127848             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
   127849             if( !aNew ){
   127850               return SQLITE_NOMEM;
   127851             }
   127852             pCsr->aBuffer = aNew;
   127853           }
   127854 
   127855           if( isFirst ){
   127856             char *a = &pCsr->aBuffer[nDoclist];
   127857             int nWrite;
   127858 
   127859             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
   127860             if( nWrite ){
   127861               iPrev = iDocid;
   127862               nDoclist += nWrite;
   127863             }
   127864           }else{
   127865             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
   127866             iPrev = iDocid;
   127867             if( isRequirePos ){
   127868               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
   127869               nDoclist += nList;
   127870               pCsr->aBuffer[nDoclist++] = '\0';
   127871             }
   127872           }
   127873         }
   127874 
   127875         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
   127876       }
   127877       if( nDoclist>0 ){
   127878         pCsr->aDoclist = pCsr->aBuffer;
   127879         pCsr->nDoclist = nDoclist;
   127880         rc = SQLITE_ROW;
   127881       }
   127882     }
   127883     pCsr->nAdvance = nMerge;
   127884   }while( rc==SQLITE_OK );
   127885 
   127886   return rc;
   127887 }
   127888 
   127889 
   127890 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
   127891   Fts3MultiSegReader *pCsr       /* Cursor object */
   127892 ){
   127893   if( pCsr ){
   127894     int i;
   127895     for(i=0; i<pCsr->nSegment; i++){
   127896       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
   127897     }
   127898     sqlite3_free(pCsr->apSegment);
   127899     sqlite3_free(pCsr->aBuffer);
   127900 
   127901     pCsr->nSegment = 0;
   127902     pCsr->apSegment = 0;
   127903     pCsr->aBuffer = 0;
   127904   }
   127905 }
   127906 
   127907 /*
   127908 ** Merge all level iLevel segments in the database into a single
   127909 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   127910 ** single segment with a level equal to the numerically largest level
   127911 ** currently present in the database.
   127912 **
   127913 ** If this function is called with iLevel<0, but there is only one
   127914 ** segment in the database, SQLITE_DONE is returned immediately.
   127915 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   127916 ** an SQLite error code is returned.
   127917 */
   127918 static int fts3SegmentMerge(
   127919   Fts3Table *p,
   127920   int iLangid,                    /* Language id to merge */
   127921   int iIndex,                     /* Index in p->aIndex[] to merge */
   127922   int iLevel                      /* Level to merge */
   127923 ){
   127924   int rc;                         /* Return code */
   127925   int iIdx = 0;                   /* Index of new segment */
   127926   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
   127927   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
   127928   Fts3SegFilter filter;           /* Segment term filter condition */
   127929   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
   127930   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
   127931 
   127932   assert( iLevel==FTS3_SEGCURSOR_ALL
   127933        || iLevel==FTS3_SEGCURSOR_PENDING
   127934        || iLevel>=0
   127935   );
   127936   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   127937   assert( iIndex>=0 && iIndex<p->nIndex );
   127938 
   127939   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
   127940   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
   127941 
   127942   if( iLevel==FTS3_SEGCURSOR_ALL ){
   127943     /* This call is to merge all segments in the database to a single
   127944     ** segment. The level of the new segment is equal to the the numerically
   127945     ** greatest segment level currently present in the database for this
   127946     ** index. The idx of the new segment is always 0.  */
   127947     if( csr.nSegment==1 ){
   127948       rc = SQLITE_DONE;
   127949       goto finished;
   127950     }
   127951     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
   127952     bIgnoreEmpty = 1;
   127953 
   127954   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
   127955     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
   127956     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
   127957   }else{
   127958     /* This call is to merge all segments at level iLevel. find the next
   127959     ** available segment index at level iLevel+1. The call to
   127960     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   127961     ** a single iLevel+2 segment if necessary.  */
   127962     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
   127963     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
   127964   }
   127965   if( rc!=SQLITE_OK ) goto finished;
   127966   assert( csr.nSegment>0 );
   127967   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
   127968   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
   127969 
   127970   memset(&filter, 0, sizeof(Fts3SegFilter));
   127971   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   127972   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   127973 
   127974   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   127975   while( SQLITE_OK==rc ){
   127976     rc = sqlite3Fts3SegReaderStep(p, &csr);
   127977     if( rc!=SQLITE_ROW ) break;
   127978     rc = fts3SegWriterAdd(p, &pWriter, 1,
   127979         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   127980   }
   127981   if( rc!=SQLITE_OK ) goto finished;
   127982   assert( pWriter );
   127983 
   127984   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   127985     rc = fts3DeleteSegdir(
   127986         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
   127987     );
   127988     if( rc!=SQLITE_OK ) goto finished;
   127989   }
   127990   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   127991 
   127992  finished:
   127993   fts3SegWriterFree(pWriter);
   127994   sqlite3Fts3SegReaderFinish(&csr);
   127995   return rc;
   127996 }
   127997 
   127998 
   127999 /*
   128000 ** Flush the contents of pendingTerms to level 0 segments.
   128001 */
   128002 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   128003   int rc = SQLITE_OK;
   128004   int i;
   128005   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   128006     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
   128007     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   128008   }
   128009   sqlite3Fts3PendingTermsClear(p);
   128010   return rc;
   128011 }
   128012 
   128013 /*
   128014 ** Encode N integers as varints into a blob.
   128015 */
   128016 static void fts3EncodeIntArray(
   128017   int N,             /* The number of integers to encode */
   128018   u32 *a,            /* The integer values */
   128019   char *zBuf,        /* Write the BLOB here */
   128020   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   128021 ){
   128022   int i, j;
   128023   for(i=j=0; i<N; i++){
   128024     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   128025   }
   128026   *pNBuf = j;
   128027 }
   128028 
   128029 /*
   128030 ** Decode a blob of varints into N integers
   128031 */
   128032 static void fts3DecodeIntArray(
   128033   int N,             /* The number of integers to decode */
   128034   u32 *a,            /* Write the integer values */
   128035   const char *zBuf,  /* The BLOB containing the varints */
   128036   int nBuf           /* size of the BLOB */
   128037 ){
   128038   int i, j;
   128039   UNUSED_PARAMETER(nBuf);
   128040   for(i=j=0; i<N; i++){
   128041     sqlite3_int64 x;
   128042     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   128043     assert(j<=nBuf);
   128044     a[i] = (u32)(x & 0xffffffff);
   128045   }
   128046 }
   128047 
   128048 /*
   128049 ** Insert the sizes (in tokens) for each column of the document
   128050 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   128051 ** a blob of varints.
   128052 */
   128053 static void fts3InsertDocsize(
   128054   int *pRC,                       /* Result code */
   128055   Fts3Table *p,                   /* Table into which to insert */
   128056   u32 *aSz                        /* Sizes of each column, in tokens */
   128057 ){
   128058   char *pBlob;             /* The BLOB encoding of the document size */
   128059   int nBlob;               /* Number of bytes in the BLOB */
   128060   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   128061   int rc;                  /* Result code from subfunctions */
   128062 
   128063   if( *pRC ) return;
   128064   pBlob = sqlite3_malloc( 10*p->nColumn );
   128065   if( pBlob==0 ){
   128066     *pRC = SQLITE_NOMEM;
   128067     return;
   128068   }
   128069   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   128070   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   128071   if( rc ){
   128072     sqlite3_free(pBlob);
   128073     *pRC = rc;
   128074     return;
   128075   }
   128076   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   128077   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   128078   sqlite3_step(pStmt);
   128079   *pRC = sqlite3_reset(pStmt);
   128080 }
   128081 
   128082 /*
   128083 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   128084 ** where N is the number of user defined columns in the fts3 table plus
   128085 ** two. If nCol is the number of user defined columns, then values of the
   128086 ** varints are set as follows:
   128087 **
   128088 **   Varint 0:       Total number of rows in the table.
   128089 **
   128090 **   Varint 1..nCol: For each column, the total number of tokens stored in
   128091 **                   the column for all rows of the table.
   128092 **
   128093 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   128094 **                   columns of all rows of the table.
   128095 **
   128096 */
   128097 static void fts3UpdateDocTotals(
   128098   int *pRC,                       /* The result code */
   128099   Fts3Table *p,                   /* Table being updated */
   128100   u32 *aSzIns,                    /* Size increases */
   128101   u32 *aSzDel,                    /* Size decreases */
   128102   int nChng                       /* Change in the number of documents */
   128103 ){
   128104   char *pBlob;             /* Storage for BLOB written into %_stat */
   128105   int nBlob;               /* Size of BLOB written into %_stat */
   128106   u32 *a;                  /* Array of integers that becomes the BLOB */
   128107   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   128108   int i;                   /* Loop counter */
   128109   int rc;                  /* Result code from subfunctions */
   128110 
   128111   const int nStat = p->nColumn+2;
   128112 
   128113   if( *pRC ) return;
   128114   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   128115   if( a==0 ){
   128116     *pRC = SQLITE_NOMEM;
   128117     return;
   128118   }
   128119   pBlob = (char*)&a[nStat];
   128120   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
   128121   if( rc ){
   128122     sqlite3_free(a);
   128123     *pRC = rc;
   128124     return;
   128125   }
   128126   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   128127     fts3DecodeIntArray(nStat, a,
   128128          sqlite3_column_blob(pStmt, 0),
   128129          sqlite3_column_bytes(pStmt, 0));
   128130   }else{
   128131     memset(a, 0, sizeof(u32)*(nStat) );
   128132   }
   128133   sqlite3_reset(pStmt);
   128134   if( nChng<0 && a[0]<(u32)(-nChng) ){
   128135     a[0] = 0;
   128136   }else{
   128137     a[0] += nChng;
   128138   }
   128139   for(i=0; i<p->nColumn+1; i++){
   128140     u32 x = a[i+1];
   128141     if( x+aSzIns[i] < aSzDel[i] ){
   128142       x = 0;
   128143     }else{
   128144       x = x + aSzIns[i] - aSzDel[i];
   128145     }
   128146     a[i+1] = x;
   128147   }
   128148   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   128149   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
   128150   if( rc ){
   128151     sqlite3_free(a);
   128152     *pRC = rc;
   128153     return;
   128154   }
   128155   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
   128156   sqlite3_step(pStmt);
   128157   *pRC = sqlite3_reset(pStmt);
   128158   sqlite3_free(a);
   128159 }
   128160 
   128161 /*
   128162 ** Merge the entire database so that there is one segment for each
   128163 ** iIndex/iLangid combination.
   128164 */
   128165 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   128166   int bSeenDone = 0;
   128167   int rc;
   128168   sqlite3_stmt *pAllLangid = 0;
   128169 
   128170   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   128171   if( rc==SQLITE_OK ){
   128172     int rc2;
   128173     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   128174     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
   128175       int i;
   128176       int iLangid = sqlite3_column_int(pAllLangid, 0);
   128177       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   128178         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
   128179         if( rc==SQLITE_DONE ){
   128180           bSeenDone = 1;
   128181           rc = SQLITE_OK;
   128182         }
   128183       }
   128184     }
   128185     rc2 = sqlite3_reset(pAllLangid);
   128186     if( rc==SQLITE_OK ) rc = rc2;
   128187   }
   128188 
   128189   sqlite3Fts3SegmentsClose(p);
   128190   sqlite3Fts3PendingTermsClear(p);
   128191 
   128192   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
   128193 }
   128194 
   128195 /*
   128196 ** This function is called when the user executes the following statement:
   128197 **
   128198 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
   128199 **
   128200 ** The entire FTS index is discarded and rebuilt. If the table is one
   128201 ** created using the content=xxx option, then the new index is based on
   128202 ** the current contents of the xxx table. Otherwise, it is rebuilt based
   128203 ** on the contents of the %_content table.
   128204 */
   128205 static int fts3DoRebuild(Fts3Table *p){
   128206   int rc;                         /* Return Code */
   128207 
   128208   rc = fts3DeleteAll(p, 0);
   128209   if( rc==SQLITE_OK ){
   128210     u32 *aSz = 0;
   128211     u32 *aSzIns = 0;
   128212     u32 *aSzDel = 0;
   128213     sqlite3_stmt *pStmt = 0;
   128214     int nEntry = 0;
   128215 
   128216     /* Compose and prepare an SQL statement to loop through the content table */
   128217     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   128218     if( !zSql ){
   128219       rc = SQLITE_NOMEM;
   128220     }else{
   128221       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   128222       sqlite3_free(zSql);
   128223     }
   128224 
   128225     if( rc==SQLITE_OK ){
   128226       int nByte = sizeof(u32) * (p->nColumn+1)*3;
   128227       aSz = (u32 *)sqlite3_malloc(nByte);
   128228       if( aSz==0 ){
   128229         rc = SQLITE_NOMEM;
   128230       }else{
   128231         memset(aSz, 0, nByte);
   128232         aSzIns = &aSz[p->nColumn+1];
   128233         aSzDel = &aSzIns[p->nColumn+1];
   128234       }
   128235     }
   128236 
   128237     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   128238       int iCol;
   128239       int iLangid = langidFromSelect(p, pStmt);
   128240       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
   128241       aSz[p->nColumn] = 0;
   128242       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   128243         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
   128244         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
   128245         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
   128246       }
   128247       if( p->bHasDocsize ){
   128248         fts3InsertDocsize(&rc, p, aSz);
   128249       }
   128250       if( rc!=SQLITE_OK ){
   128251         sqlite3_finalize(pStmt);
   128252         pStmt = 0;
   128253       }else{
   128254         nEntry++;
   128255         for(iCol=0; iCol<=p->nColumn; iCol++){
   128256           aSzIns[iCol] += aSz[iCol];
   128257         }
   128258       }
   128259     }
   128260     if( p->bHasStat ){
   128261       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
   128262     }
   128263     sqlite3_free(aSz);
   128264 
   128265     if( pStmt ){
   128266       int rc2 = sqlite3_finalize(pStmt);
   128267       if( rc==SQLITE_OK ){
   128268         rc = rc2;
   128269       }
   128270     }
   128271   }
   128272 
   128273   return rc;
   128274 }
   128275 
   128276 /*
   128277 ** Handle a 'special' INSERT of the form:
   128278 **
   128279 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   128280 **
   128281 ** Argument pVal contains the result of <expr>. Currently the only
   128282 ** meaningful value to insert is the text 'optimize'.
   128283 */
   128284 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   128285   int rc;                         /* Return Code */
   128286   const char *zVal = (const char *)sqlite3_value_text(pVal);
   128287   int nVal = sqlite3_value_bytes(pVal);
   128288 
   128289   if( !zVal ){
   128290     return SQLITE_NOMEM;
   128291   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   128292     rc = fts3DoOptimize(p, 0);
   128293   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
   128294     rc = fts3DoRebuild(p);
   128295 #ifdef SQLITE_TEST
   128296   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   128297     p->nNodeSize = atoi(&zVal[9]);
   128298     rc = SQLITE_OK;
   128299   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   128300     p->nMaxPendingData = atoi(&zVal[11]);
   128301     rc = SQLITE_OK;
   128302 #endif
   128303   }else{
   128304     rc = SQLITE_ERROR;
   128305   }
   128306 
   128307   return rc;
   128308 }
   128309 
   128310 /*
   128311 ** Delete all cached deferred doclists. Deferred doclists are cached
   128312 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   128313 */
   128314 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   128315   Fts3DeferredToken *pDef;
   128316   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   128317     fts3PendingListDelete(pDef->pList);
   128318     pDef->pList = 0;
   128319   }
   128320 }
   128321 
   128322 /*
   128323 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   128324 ** this list using sqlite3Fts3DeferToken().
   128325 */
   128326 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   128327   Fts3DeferredToken *pDef;
   128328   Fts3DeferredToken *pNext;
   128329   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   128330     pNext = pDef->pNext;
   128331     fts3PendingListDelete(pDef->pList);
   128332     sqlite3_free(pDef);
   128333   }
   128334   pCsr->pDeferred = 0;
   128335 }
   128336 
   128337 /*
   128338 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   128339 ** based on the row that pCsr currently points to.
   128340 **
   128341 ** A deferred-doclist is like any other doclist with position information
   128342 ** included, except that it only contains entries for a single row of the
   128343 ** table, not for all rows.
   128344 */
   128345 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   128346   int rc = SQLITE_OK;             /* Return code */
   128347   if( pCsr->pDeferred ){
   128348     int i;                        /* Used to iterate through table columns */
   128349     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   128350     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   128351 
   128352     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   128353     sqlite3_tokenizer *pT = p->pTokenizer;
   128354     sqlite3_tokenizer_module const *pModule = pT->pModule;
   128355 
   128356     assert( pCsr->isRequireSeek==0 );
   128357     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   128358 
   128359     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   128360       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   128361       sqlite3_tokenizer_cursor *pTC = 0;
   128362 
   128363       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
   128364       while( rc==SQLITE_OK ){
   128365         char const *zToken;       /* Buffer containing token */
   128366         int nToken;               /* Number of bytes in token */
   128367         int iDum1, iDum2;         /* Dummy variables */
   128368         int iPos;                 /* Position of token in zText */
   128369 
   128370         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   128371         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   128372           Fts3PhraseToken *pPT = pDef->pToken;
   128373           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   128374            && (pPT->bFirst==0 || iPos==0)
   128375            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   128376            && (0==memcmp(zToken, pPT->z, pPT->n))
   128377           ){
   128378             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   128379           }
   128380         }
   128381       }
   128382       if( pTC ) pModule->xClose(pTC);
   128383       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   128384     }
   128385 
   128386     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   128387       if( pDef->pList ){
   128388         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   128389       }
   128390     }
   128391   }
   128392 
   128393   return rc;
   128394 }
   128395 
   128396 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   128397   Fts3DeferredToken *p,
   128398   char **ppData,
   128399   int *pnData
   128400 ){
   128401   char *pRet;
   128402   int nSkip;
   128403   sqlite3_int64 dummy;
   128404 
   128405   *ppData = 0;
   128406   *pnData = 0;
   128407 
   128408   if( p->pList==0 ){
   128409     return SQLITE_OK;
   128410   }
   128411 
   128412   pRet = (char *)sqlite3_malloc(p->pList->nData);
   128413   if( !pRet ) return SQLITE_NOMEM;
   128414 
   128415   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   128416   *pnData = p->pList->nData - nSkip;
   128417   *ppData = pRet;
   128418 
   128419   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   128420   return SQLITE_OK;
   128421 }
   128422 
   128423 /*
   128424 ** Add an entry for token pToken to the pCsr->pDeferred list.
   128425 */
   128426 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   128427   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   128428   Fts3PhraseToken *pToken,        /* Token to defer */
   128429   int iCol                        /* Column that token must appear in (or -1) */
   128430 ){
   128431   Fts3DeferredToken *pDeferred;
   128432   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   128433   if( !pDeferred ){
   128434     return SQLITE_NOMEM;
   128435   }
   128436   memset(pDeferred, 0, sizeof(*pDeferred));
   128437   pDeferred->pToken = pToken;
   128438   pDeferred->pNext = pCsr->pDeferred;
   128439   pDeferred->iCol = iCol;
   128440   pCsr->pDeferred = pDeferred;
   128441 
   128442   assert( pToken->pDeferred==0 );
   128443   pToken->pDeferred = pDeferred;
   128444 
   128445   return SQLITE_OK;
   128446 }
   128447 
   128448 /*
   128449 ** SQLite value pRowid contains the rowid of a row that may or may not be
   128450 ** present in the FTS3 table. If it is, delete it and adjust the contents
   128451 ** of subsiduary data structures accordingly.
   128452 */
   128453 static int fts3DeleteByRowid(
   128454   Fts3Table *p,
   128455   sqlite3_value *pRowid,
   128456   int *pnDoc,
   128457   u32 *aSzDel
   128458 ){
   128459   int isEmpty = 0;
   128460   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
   128461   if( rc==SQLITE_OK ){
   128462     if( isEmpty ){
   128463       /* Deleting this row means the whole table is empty. In this case
   128464       ** delete the contents of all three tables and throw away any
   128465       ** data in the pendingTerms hash table.  */
   128466       rc = fts3DeleteAll(p, 1);
   128467       *pnDoc = *pnDoc - 1;
   128468     }else{
   128469       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
   128470       if( p->zContentTbl==0 ){
   128471         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
   128472         if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
   128473       }else{
   128474         *pnDoc = *pnDoc - 1;
   128475       }
   128476       if( p->bHasDocsize ){
   128477         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
   128478       }
   128479     }
   128480   }
   128481 
   128482   return rc;
   128483 }
   128484 
   128485 /*
   128486 ** This function does the work for the xUpdate method of FTS3 virtual
   128487 ** tables. The schema of the virtual table being:
   128488 **
   128489 **     CREATE TABLE <table name>(
   128490 **       <user COLUMns>,
   128491 **       <table name> HIDDEN,
   128492 **       docid HIDDEN,
   128493 **       <langid> HIDDEN
   128494 **     );
   128495 **
   128496 **
   128497 */
   128498 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   128499   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   128500   int nArg,                       /* Size of argument array */
   128501   sqlite3_value **apVal,          /* Array of arguments */
   128502   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   128503 ){
   128504   Fts3Table *p = (Fts3Table *)pVtab;
   128505   int rc = SQLITE_OK;             /* Return Code */
   128506   int isRemove = 0;               /* True for an UPDATE or DELETE */
   128507   u32 *aSzIns = 0;                /* Sizes of inserted documents */
   128508   u32 *aSzDel;                    /* Sizes of deleted documents */
   128509   int nChng = 0;                  /* Net change in number of documents */
   128510   int bInsertDone = 0;
   128511 
   128512   assert( p->pSegments==0 );
   128513   assert(
   128514       nArg==1                     /* DELETE operations */
   128515    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   128516   );
   128517 
   128518   /* Check for a "special" INSERT operation. One of the form:
   128519   **
   128520   **   INSERT INTO xyz(xyz) VALUES('command');
   128521   */
   128522   if( nArg>1
   128523    && sqlite3_value_type(apVal[0])==SQLITE_NULL
   128524    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   128525   ){
   128526     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
   128527     goto update_out;
   128528   }
   128529 
   128530   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
   128531     rc = SQLITE_CONSTRAINT;
   128532     goto update_out;
   128533   }
   128534 
   128535   /* Allocate space to hold the change in document sizes */
   128536   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
   128537   if( aSzIns==0 ){
   128538     rc = SQLITE_NOMEM;
   128539     goto update_out;
   128540   }
   128541   aSzDel = &aSzIns[p->nColumn+1];
   128542   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
   128543 
   128544   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
   128545   ** value, then this operation requires constraint handling.
   128546   **
   128547   ** If the on-conflict mode is REPLACE, this means that the existing row
   128548   ** should be deleted from the database before inserting the new row. Or,
   128549   ** if the on-conflict mode is other than REPLACE, then this method must
   128550   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
   128551   ** modify the database file.
   128552   */
   128553   if( nArg>1 && p->zContentTbl==0 ){
   128554     /* Find the value object that holds the new rowid value. */
   128555     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
   128556     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
   128557       pNewRowid = apVal[1];
   128558     }
   128559 
   128560     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
   128561         sqlite3_value_type(apVal[0])==SQLITE_NULL
   128562      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
   128563     )){
   128564       /* The new rowid is not NULL (in this case the rowid will be
   128565       ** automatically assigned and there is no chance of a conflict), and
   128566       ** the statement is either an INSERT or an UPDATE that modifies the
   128567       ** rowid column. So if the conflict mode is REPLACE, then delete any
   128568       ** existing row with rowid=pNewRowid.
   128569       **
   128570       ** Or, if the conflict mode is not REPLACE, insert the new record into
   128571       ** the %_content table. If we hit the duplicate rowid constraint (or any
   128572       ** other error) while doing so, return immediately.
   128573       **
   128574       ** This branch may also run if pNewRowid contains a value that cannot
   128575       ** be losslessly converted to an integer. In this case, the eventual
   128576       ** call to fts3InsertData() (either just below or further on in this
   128577       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
   128578       ** invoked, it will delete zero rows (since no row will have
   128579       ** docid=$pNewRowid if $pNewRowid is not an integer value).
   128580       */
   128581       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
   128582         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
   128583       }else{
   128584         rc = fts3InsertData(p, apVal, pRowid);
   128585         bInsertDone = 1;
   128586       }
   128587     }
   128588   }
   128589   if( rc!=SQLITE_OK ){
   128590     goto update_out;
   128591   }
   128592 
   128593   /* If this is a DELETE or UPDATE operation, remove the old record. */
   128594   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   128595     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
   128596     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   128597     isRemove = 1;
   128598   }
   128599 
   128600   /* If this is an INSERT or UPDATE operation, insert the new record. */
   128601   if( nArg>1 && rc==SQLITE_OK ){
   128602     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
   128603     if( bInsertDone==0 ){
   128604       rc = fts3InsertData(p, apVal, pRowid);
   128605       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
   128606         rc = FTS_CORRUPT_VTAB;
   128607       }
   128608     }
   128609     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
   128610       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
   128611     }
   128612     if( rc==SQLITE_OK ){
   128613       assert( p->iPrevDocid==*pRowid );
   128614       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
   128615     }
   128616     if( p->bHasDocsize ){
   128617       fts3InsertDocsize(&rc, p, aSzIns);
   128618     }
   128619     nChng++;
   128620   }
   128621 
   128622   if( p->bHasStat ){
   128623     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   128624   }
   128625 
   128626  update_out:
   128627   sqlite3_free(aSzIns);
   128628   sqlite3Fts3SegmentsClose(p);
   128629   return rc;
   128630 }
   128631 
   128632 /*
   128633 ** Flush any data in the pending-terms hash table to disk. If successful,
   128634 ** merge all segments in the database (including the new segment, if
   128635 ** there was any data to flush) into a single segment.
   128636 */
   128637 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   128638   int rc;
   128639   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   128640   if( rc==SQLITE_OK ){
   128641     rc = fts3DoOptimize(p, 1);
   128642     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   128643       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   128644       if( rc2!=SQLITE_OK ) rc = rc2;
   128645     }else{
   128646       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   128647       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   128648     }
   128649   }
   128650   sqlite3Fts3SegmentsClose(p);
   128651   return rc;
   128652 }
   128653 
   128654 #endif
   128655 
   128656 /************** End of fts3_write.c ******************************************/
   128657 /************** Begin file fts3_snippet.c ************************************/
   128658 /*
   128659 ** 2009 Oct 23
   128660 **
   128661 ** The author disclaims copyright to this source code.  In place of
   128662 ** a legal notice, here is a blessing:
   128663 **
   128664 **    May you do good and not evil.
   128665 **    May you find forgiveness for yourself and forgive others.
   128666 **    May you share freely, never taking more than you give.
   128667 **
   128668 ******************************************************************************
   128669 */
   128670 
   128671 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   128672 
   128673 /* #include <string.h> */
   128674 /* #include <assert.h> */
   128675 
   128676 /*
   128677 ** Characters that may appear in the second argument to matchinfo().
   128678 */
   128679 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   128680 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   128681 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   128682 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   128683 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   128684 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   128685 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   128686 
   128687 /*
   128688 ** The default value for the second argument to matchinfo().
   128689 */
   128690 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   128691 
   128692 
   128693 /*
   128694 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   128695 ** Fts3Expr.aDoclist[]/nDoclist.
   128696 */
   128697 typedef struct LoadDoclistCtx LoadDoclistCtx;
   128698 struct LoadDoclistCtx {
   128699   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   128700   int nPhrase;                    /* Number of phrases seen so far */
   128701   int nToken;                     /* Number of tokens seen so far */
   128702 };
   128703 
   128704 /*
   128705 ** The following types are used as part of the implementation of the
   128706 ** fts3BestSnippet() routine.
   128707 */
   128708 typedef struct SnippetIter SnippetIter;
   128709 typedef struct SnippetPhrase SnippetPhrase;
   128710 typedef struct SnippetFragment SnippetFragment;
   128711 
   128712 struct SnippetIter {
   128713   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   128714   int iCol;                       /* Extract snippet from this column */
   128715   int nSnippet;                   /* Requested snippet length (in tokens) */
   128716   int nPhrase;                    /* Number of phrases in query */
   128717   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   128718   int iCurrent;                   /* First token of current snippet */
   128719 };
   128720 
   128721 struct SnippetPhrase {
   128722   int nToken;                     /* Number of tokens in phrase */
   128723   char *pList;                    /* Pointer to start of phrase position list */
   128724   int iHead;                      /* Next value in position list */
   128725   char *pHead;                    /* Position list data following iHead */
   128726   int iTail;                      /* Next value in trailing position list */
   128727   char *pTail;                    /* Position list data following iTail */
   128728 };
   128729 
   128730 struct SnippetFragment {
   128731   int iCol;                       /* Column snippet is extracted from */
   128732   int iPos;                       /* Index of first token in snippet */
   128733   u64 covered;                    /* Mask of query phrases covered */
   128734   u64 hlmask;                     /* Mask of snippet terms to highlight */
   128735 };
   128736 
   128737 /*
   128738 ** This type is used as an fts3ExprIterate() context object while
   128739 ** accumulating the data returned by the matchinfo() function.
   128740 */
   128741 typedef struct MatchInfo MatchInfo;
   128742 struct MatchInfo {
   128743   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   128744   int nCol;                       /* Number of columns in table */
   128745   int nPhrase;                    /* Number of matchable phrases in query */
   128746   sqlite3_int64 nDoc;             /* Number of docs in database */
   128747   u32 *aMatchinfo;                /* Pre-allocated buffer */
   128748 };
   128749 
   128750 
   128751 
   128752 /*
   128753 ** The snippet() and offsets() functions both return text values. An instance
   128754 ** of the following structure is used to accumulate those values while the
   128755 ** functions are running. See fts3StringAppend() for details.
   128756 */
   128757 typedef struct StrBuffer StrBuffer;
   128758 struct StrBuffer {
   128759   char *z;                        /* Pointer to buffer containing string */
   128760   int n;                          /* Length of z in bytes (excl. nul-term) */
   128761   int nAlloc;                     /* Allocated size of buffer z in bytes */
   128762 };
   128763 
   128764 
   128765 /*
   128766 ** This function is used to help iterate through a position-list. A position
   128767 ** list is a list of unique integers, sorted from smallest to largest. Each
   128768 ** element of the list is represented by an FTS3 varint that takes the value
   128769 ** of the difference between the current element and the previous one plus
   128770 ** two. For example, to store the position-list:
   128771 **
   128772 **     4 9 113
   128773 **
   128774 ** the three varints:
   128775 **
   128776 **     6 7 106
   128777 **
   128778 ** are encoded.
   128779 **
   128780 ** When this function is called, *pp points to the start of an element of
   128781 ** the list. *piPos contains the value of the previous entry in the list.
   128782 ** After it returns, *piPos contains the value of the next element of the
   128783 ** list and *pp is advanced to the following varint.
   128784 */
   128785 static void fts3GetDeltaPosition(char **pp, int *piPos){
   128786   int iVal;
   128787   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
   128788   *piPos += (iVal-2);
   128789 }
   128790 
   128791 /*
   128792 ** Helper function for fts3ExprIterate() (see below).
   128793 */
   128794 static int fts3ExprIterate2(
   128795   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   128796   int *piPhrase,                  /* Pointer to phrase counter */
   128797   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   128798   void *pCtx                      /* Second argument to pass to callback */
   128799 ){
   128800   int rc;                         /* Return code */
   128801   int eType = pExpr->eType;       /* Type of expression node pExpr */
   128802 
   128803   if( eType!=FTSQUERY_PHRASE ){
   128804     assert( pExpr->pLeft && pExpr->pRight );
   128805     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   128806     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   128807       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   128808     }
   128809   }else{
   128810     rc = x(pExpr, *piPhrase, pCtx);
   128811     (*piPhrase)++;
   128812   }
   128813   return rc;
   128814 }
   128815 
   128816 /*
   128817 ** Iterate through all phrase nodes in an FTS3 query, except those that
   128818 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   128819 ** For each phrase node found, the supplied callback function is invoked.
   128820 **
   128821 ** If the callback function returns anything other than SQLITE_OK,
   128822 ** the iteration is abandoned and the error code returned immediately.
   128823 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   128824 ** all eligible phrase nodes.
   128825 */
   128826 static int fts3ExprIterate(
   128827   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   128828   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   128829   void *pCtx                      /* Second argument to pass to callback */
   128830 ){
   128831   int iPhrase = 0;                /* Variable used as the phrase counter */
   128832   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   128833 }
   128834 
   128835 /*
   128836 ** This is an fts3ExprIterate() callback used while loading the doclists
   128837 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   128838 ** fts3ExprLoadDoclists().
   128839 */
   128840 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   128841   int rc = SQLITE_OK;
   128842   Fts3Phrase *pPhrase = pExpr->pPhrase;
   128843   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   128844 
   128845   UNUSED_PARAMETER(iPhrase);
   128846 
   128847   p->nPhrase++;
   128848   p->nToken += pPhrase->nToken;
   128849 
   128850   return rc;
   128851 }
   128852 
   128853 /*
   128854 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   128855 ** pCsr.
   128856 **
   128857 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   128858 ** phrases in the expression (all phrases except those directly or
   128859 ** indirectly descended from the right-hand-side of a NOT operator). If
   128860 ** pnToken is not NULL, then it is set to the number of tokens in all
   128861 ** matchable phrases of the expression.
   128862 */
   128863 static int fts3ExprLoadDoclists(
   128864   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   128865   int *pnPhrase,                  /* OUT: Number of phrases in query */
   128866   int *pnToken                    /* OUT: Number of tokens in query */
   128867 ){
   128868   int rc;                         /* Return Code */
   128869   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   128870   sCtx.pCsr = pCsr;
   128871   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   128872   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   128873   if( pnToken ) *pnToken = sCtx.nToken;
   128874   return rc;
   128875 }
   128876 
   128877 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   128878   (*(int *)ctx)++;
   128879   UNUSED_PARAMETER(pExpr);
   128880   UNUSED_PARAMETER(iPhrase);
   128881   return SQLITE_OK;
   128882 }
   128883 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   128884   int nPhrase = 0;
   128885   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   128886   return nPhrase;
   128887 }
   128888 
   128889 /*
   128890 ** Advance the position list iterator specified by the first two
   128891 ** arguments so that it points to the first element with a value greater
   128892 ** than or equal to parameter iNext.
   128893 */
   128894 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   128895   char *pIter = *ppIter;
   128896   if( pIter ){
   128897     int iIter = *piIter;
   128898 
   128899     while( iIter<iNext ){
   128900       if( 0==(*pIter & 0xFE) ){
   128901         iIter = -1;
   128902         pIter = 0;
   128903         break;
   128904       }
   128905       fts3GetDeltaPosition(&pIter, &iIter);
   128906     }
   128907 
   128908     *piIter = iIter;
   128909     *ppIter = pIter;
   128910   }
   128911 }
   128912 
   128913 /*
   128914 ** Advance the snippet iterator to the next candidate snippet.
   128915 */
   128916 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   128917   int i;                          /* Loop counter */
   128918 
   128919   if( pIter->iCurrent<0 ){
   128920     /* The SnippetIter object has just been initialized. The first snippet
   128921     ** candidate always starts at offset 0 (even if this candidate has a
   128922     ** score of 0.0).
   128923     */
   128924     pIter->iCurrent = 0;
   128925 
   128926     /* Advance the 'head' iterator of each phrase to the first offset that
   128927     ** is greater than or equal to (iNext+nSnippet).
   128928     */
   128929     for(i=0; i<pIter->nPhrase; i++){
   128930       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128931       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   128932     }
   128933   }else{
   128934     int iStart;
   128935     int iEnd = 0x7FFFFFFF;
   128936 
   128937     for(i=0; i<pIter->nPhrase; i++){
   128938       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128939       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   128940         iEnd = pPhrase->iHead;
   128941       }
   128942     }
   128943     if( iEnd==0x7FFFFFFF ){
   128944       return 1;
   128945     }
   128946 
   128947     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   128948     for(i=0; i<pIter->nPhrase; i++){
   128949       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128950       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   128951       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   128952     }
   128953   }
   128954 
   128955   return 0;
   128956 }
   128957 
   128958 /*
   128959 ** Retrieve information about the current candidate snippet of snippet
   128960 ** iterator pIter.
   128961 */
   128962 static void fts3SnippetDetails(
   128963   SnippetIter *pIter,             /* Snippet iterator */
   128964   u64 mCovered,                   /* Bitmask of phrases already covered */
   128965   int *piToken,                   /* OUT: First token of proposed snippet */
   128966   int *piScore,                   /* OUT: "Score" for this snippet */
   128967   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   128968   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   128969 ){
   128970   int iStart = pIter->iCurrent;   /* First token of snippet */
   128971   int iScore = 0;                 /* Score of this snippet */
   128972   int i;                          /* Loop counter */
   128973   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   128974   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   128975 
   128976   for(i=0; i<pIter->nPhrase; i++){
   128977     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128978     if( pPhrase->pTail ){
   128979       char *pCsr = pPhrase->pTail;
   128980       int iCsr = pPhrase->iTail;
   128981 
   128982       while( iCsr<(iStart+pIter->nSnippet) ){
   128983         int j;
   128984         u64 mPhrase = (u64)1 << i;
   128985         u64 mPos = (u64)1 << (iCsr - iStart);
   128986         assert( iCsr>=iStart );
   128987         if( (mCover|mCovered)&mPhrase ){
   128988           iScore++;
   128989         }else{
   128990           iScore += 1000;
   128991         }
   128992         mCover |= mPhrase;
   128993 
   128994         for(j=0; j<pPhrase->nToken; j++){
   128995           mHighlight |= (mPos>>j);
   128996         }
   128997 
   128998         if( 0==(*pCsr & 0x0FE) ) break;
   128999         fts3GetDeltaPosition(&pCsr, &iCsr);
   129000       }
   129001     }
   129002   }
   129003 
   129004   /* Set the output variables before returning. */
   129005   *piToken = iStart;
   129006   *piScore = iScore;
   129007   *pmCover = mCover;
   129008   *pmHighlight = mHighlight;
   129009 }
   129010 
   129011 /*
   129012 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   129013 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   129014 */
   129015 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   129016   SnippetIter *p = (SnippetIter *)ctx;
   129017   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   129018   char *pCsr;
   129019 
   129020   pPhrase->nToken = pExpr->pPhrase->nToken;
   129021 
   129022   pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
   129023   if( pCsr ){
   129024     int iFirst = 0;
   129025     pPhrase->pList = pCsr;
   129026     fts3GetDeltaPosition(&pCsr, &iFirst);
   129027     assert( iFirst>=0 );
   129028     pPhrase->pHead = pCsr;
   129029     pPhrase->pTail = pCsr;
   129030     pPhrase->iHead = iFirst;
   129031     pPhrase->iTail = iFirst;
   129032   }else{
   129033     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
   129034   }
   129035 
   129036   return SQLITE_OK;
   129037 }
   129038 
   129039 /*
   129040 ** Select the fragment of text consisting of nFragment contiguous tokens
   129041 ** from column iCol that represent the "best" snippet. The best snippet
   129042 ** is the snippet with the highest score, where scores are calculated
   129043 ** by adding:
   129044 **
   129045 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
   129046 **
   129047 **   (b) +1000 points for the first occurence of each matchable phrase in
   129048 **       the snippet for which the corresponding mCovered bit is not set.
   129049 **
   129050 ** The selected snippet parameters are stored in structure *pFragment before
   129051 ** returning. The score of the selected snippet is stored in *piScore
   129052 ** before returning.
   129053 */
   129054 static int fts3BestSnippet(
   129055   int nSnippet,                   /* Desired snippet length */
   129056   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   129057   int iCol,                       /* Index of column to create snippet from */
   129058   u64 mCovered,                   /* Mask of phrases already covered */
   129059   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   129060   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   129061   int *piScore                    /* OUT: Score of snippet pFragment */
   129062 ){
   129063   int rc;                         /* Return Code */
   129064   int nList;                      /* Number of phrases in expression */
   129065   SnippetIter sIter;              /* Iterates through snippet candidates */
   129066   int nByte;                      /* Number of bytes of space to allocate */
   129067   int iBestScore = -1;            /* Best snippet score found so far */
   129068   int i;                          /* Loop counter */
   129069 
   129070   memset(&sIter, 0, sizeof(sIter));
   129071 
   129072   /* Iterate through the phrases in the expression to count them. The same
   129073   ** callback makes sure the doclists are loaded for each phrase.
   129074   */
   129075   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   129076   if( rc!=SQLITE_OK ){
   129077     return rc;
   129078   }
   129079 
   129080   /* Now that it is known how many phrases there are, allocate and zero
   129081   ** the required space using malloc().
   129082   */
   129083   nByte = sizeof(SnippetPhrase) * nList;
   129084   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   129085   if( !sIter.aPhrase ){
   129086     return SQLITE_NOMEM;
   129087   }
   129088   memset(sIter.aPhrase, 0, nByte);
   129089 
   129090   /* Initialize the contents of the SnippetIter object. Then iterate through
   129091   ** the set of phrases in the expression to populate the aPhrase[] array.
   129092   */
   129093   sIter.pCsr = pCsr;
   129094   sIter.iCol = iCol;
   129095   sIter.nSnippet = nSnippet;
   129096   sIter.nPhrase = nList;
   129097   sIter.iCurrent = -1;
   129098   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
   129099 
   129100   /* Set the *pmSeen output variable. */
   129101   for(i=0; i<nList; i++){
   129102     if( sIter.aPhrase[i].pHead ){
   129103       *pmSeen |= (u64)1 << i;
   129104     }
   129105   }
   129106 
   129107   /* Loop through all candidate snippets. Store the best snippet in
   129108   ** *pFragment. Store its associated 'score' in iBestScore.
   129109   */
   129110   pFragment->iCol = iCol;
   129111   while( !fts3SnippetNextCandidate(&sIter) ){
   129112     int iPos;
   129113     int iScore;
   129114     u64 mCover;
   129115     u64 mHighlight;
   129116     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
   129117     assert( iScore>=0 );
   129118     if( iScore>iBestScore ){
   129119       pFragment->iPos = iPos;
   129120       pFragment->hlmask = mHighlight;
   129121       pFragment->covered = mCover;
   129122       iBestScore = iScore;
   129123     }
   129124   }
   129125 
   129126   sqlite3_free(sIter.aPhrase);
   129127   *piScore = iBestScore;
   129128   return SQLITE_OK;
   129129 }
   129130 
   129131 
   129132 /*
   129133 ** Append a string to the string-buffer passed as the first argument.
   129134 **
   129135 ** If nAppend is negative, then the length of the string zAppend is
   129136 ** determined using strlen().
   129137 */
   129138 static int fts3StringAppend(
   129139   StrBuffer *pStr,                /* Buffer to append to */
   129140   const char *zAppend,            /* Pointer to data to append to buffer */
   129141   int nAppend                     /* Size of zAppend in bytes (or -1) */
   129142 ){
   129143   if( nAppend<0 ){
   129144     nAppend = (int)strlen(zAppend);
   129145   }
   129146 
   129147   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   129148   ** to grow the buffer until so that it is big enough to accomadate the
   129149   ** appended data.
   129150   */
   129151   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   129152     int nAlloc = pStr->nAlloc+nAppend+100;
   129153     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   129154     if( !zNew ){
   129155       return SQLITE_NOMEM;
   129156     }
   129157     pStr->z = zNew;
   129158     pStr->nAlloc = nAlloc;
   129159   }
   129160 
   129161   /* Append the data to the string buffer. */
   129162   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   129163   pStr->n += nAppend;
   129164   pStr->z[pStr->n] = '\0';
   129165 
   129166   return SQLITE_OK;
   129167 }
   129168 
   129169 /*
   129170 ** The fts3BestSnippet() function often selects snippets that end with a
   129171 ** query term. That is, the final term of the snippet is always a term
   129172 ** that requires highlighting. For example, if 'X' is a highlighted term
   129173 ** and '.' is a non-highlighted term, BestSnippet() may select:
   129174 **
   129175 **     ........X.....X
   129176 **
   129177 ** This function "shifts" the beginning of the snippet forward in the
   129178 ** document so that there are approximately the same number of
   129179 ** non-highlighted terms to the right of the final highlighted term as there
   129180 ** are to the left of the first highlighted term. For example, to this:
   129181 **
   129182 **     ....X.....X....
   129183 **
   129184 ** This is done as part of extracting the snippet text, not when selecting
   129185 ** the snippet. Snippet selection is done based on doclists only, so there
   129186 ** is no way for fts3BestSnippet() to know whether or not the document
   129187 ** actually contains terms that follow the final highlighted term.
   129188 */
   129189 static int fts3SnippetShift(
   129190   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   129191   int iLangid,                    /* Language id to use in tokenizing */
   129192   int nSnippet,                   /* Number of tokens desired for snippet */
   129193   const char *zDoc,               /* Document text to extract snippet from */
   129194   int nDoc,                       /* Size of buffer zDoc in bytes */
   129195   int *piPos,                     /* IN/OUT: First token of snippet */
   129196   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   129197 ){
   129198   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   129199 
   129200   if( hlmask ){
   129201     int nLeft;                    /* Tokens to the left of first highlight */
   129202     int nRight;                   /* Tokens to the right of last highlight */
   129203     int nDesired;                 /* Ideal number of tokens to shift forward */
   129204 
   129205     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   129206     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   129207     nDesired = (nLeft-nRight)/2;
   129208 
   129209     /* Ideally, the start of the snippet should be pushed forward in the
   129210     ** document nDesired tokens. This block checks if there are actually
   129211     ** nDesired tokens to the right of the snippet. If so, *piPos and
   129212     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   129213     ** right. Otherwise, the snippet is shifted by the number of tokens
   129214     ** available.
   129215     */
   129216     if( nDesired>0 ){
   129217       int nShift;                 /* Number of tokens to shift snippet by */
   129218       int iCurrent = 0;           /* Token counter */
   129219       int rc;                     /* Return Code */
   129220       sqlite3_tokenizer_module *pMod;
   129221       sqlite3_tokenizer_cursor *pC;
   129222       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   129223 
   129224       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   129225       ** or more tokens in zDoc/nDoc.
   129226       */
   129227       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
   129228       if( rc!=SQLITE_OK ){
   129229         return rc;
   129230       }
   129231       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   129232         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
   129233         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   129234       }
   129235       pMod->xClose(pC);
   129236       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   129237 
   129238       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   129239       assert( nShift<=nDesired );
   129240       if( nShift>0 ){
   129241         *piPos += nShift;
   129242         *pHlmask = hlmask >> nShift;
   129243       }
   129244     }
   129245   }
   129246   return SQLITE_OK;
   129247 }
   129248 
   129249 /*
   129250 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   129251 ** append it to string buffer pOut.
   129252 */
   129253 static int fts3SnippetText(
   129254   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   129255   SnippetFragment *pFragment,     /* Snippet to extract */
   129256   int iFragment,                  /* Fragment number */
   129257   int isLast,                     /* True for final fragment in snippet */
   129258   int nSnippet,                   /* Number of tokens in extracted snippet */
   129259   const char *zOpen,              /* String inserted before highlighted term */
   129260   const char *zClose,             /* String inserted after highlighted term */
   129261   const char *zEllipsis,          /* String inserted between snippets */
   129262   StrBuffer *pOut                 /* Write output here */
   129263 ){
   129264   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129265   int rc;                         /* Return code */
   129266   const char *zDoc;               /* Document text to extract snippet from */
   129267   int nDoc;                       /* Size of zDoc in bytes */
   129268   int iCurrent = 0;               /* Current token number of document */
   129269   int iEnd = 0;                   /* Byte offset of end of current token */
   129270   int isShiftDone = 0;            /* True after snippet is shifted */
   129271   int iPos = pFragment->iPos;     /* First token of snippet */
   129272   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   129273   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   129274   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   129275   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   129276   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
   129277   int DUMMY1;                     /* Dummy argument used with tokenizer */
   129278 
   129279   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   129280   if( zDoc==0 ){
   129281     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   129282       return SQLITE_NOMEM;
   129283     }
   129284     return SQLITE_OK;
   129285   }
   129286   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   129287 
   129288   /* Open a token cursor on the document. */
   129289   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   129290   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
   129291   if( rc!=SQLITE_OK ){
   129292     return rc;
   129293   }
   129294 
   129295   while( rc==SQLITE_OK ){
   129296     int iBegin;                   /* Offset in zDoc of start of token */
   129297     int iFin;                     /* Offset in zDoc of end of token */
   129298     int isHighlight;              /* True for highlighted terms */
   129299 
   129300     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   129301     if( rc!=SQLITE_OK ){
   129302       if( rc==SQLITE_DONE ){
   129303         /* Special case - the last token of the snippet is also the last token
   129304         ** of the column. Append any punctuation that occurred between the end
   129305         ** of the previous token and the end of the document to the output.
   129306         ** Then break out of the loop. */
   129307         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   129308       }
   129309       break;
   129310     }
   129311     if( iCurrent<iPos ){ continue; }
   129312 
   129313     if( !isShiftDone ){
   129314       int n = nDoc - iBegin;
   129315       rc = fts3SnippetShift(
   129316           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
   129317       );
   129318       isShiftDone = 1;
   129319 
   129320       /* Now that the shift has been done, check if the initial "..." are
   129321       ** required. They are required if (a) this is not the first fragment,
   129322       ** or (b) this fragment does not begin at position 0 of its column.
   129323       */
   129324       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
   129325         rc = fts3StringAppend(pOut, zEllipsis, -1);
   129326       }
   129327       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   129328     }
   129329 
   129330     if( iCurrent>=(iPos+nSnippet) ){
   129331       if( isLast ){
   129332         rc = fts3StringAppend(pOut, zEllipsis, -1);
   129333       }
   129334       break;
   129335     }
   129336 
   129337     /* Set isHighlight to true if this term should be highlighted. */
   129338     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   129339 
   129340     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   129341     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   129342     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   129343     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   129344 
   129345     iEnd = iFin;
   129346   }
   129347 
   129348   pMod->xClose(pC);
   129349   return rc;
   129350 }
   129351 
   129352 
   129353 /*
   129354 ** This function is used to count the entries in a column-list (a
   129355 ** delta-encoded list of term offsets within a single column of a single
   129356 ** row). When this function is called, *ppCollist should point to the
   129357 ** beginning of the first varint in the column-list (the varint that
   129358 ** contains the position of the first matching term in the column data).
   129359 ** Before returning, *ppCollist is set to point to the first byte after
   129360 ** the last varint in the column-list (either the 0x00 signifying the end
   129361 ** of the position-list, or the 0x01 that precedes the column number of
   129362 ** the next column in the position-list).
   129363 **
   129364 ** The number of elements in the column-list is returned.
   129365 */
   129366 static int fts3ColumnlistCount(char **ppCollist){
   129367   char *pEnd = *ppCollist;
   129368   char c = 0;
   129369   int nEntry = 0;
   129370 
   129371   /* A column-list is terminated by either a 0x01 or 0x00. */
   129372   while( 0xFE & (*pEnd | c) ){
   129373     c = *pEnd++ & 0x80;
   129374     if( !c ) nEntry++;
   129375   }
   129376 
   129377   *ppCollist = pEnd;
   129378   return nEntry;
   129379 }
   129380 
   129381 /*
   129382 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   129383 ** for a single query.
   129384 **
   129385 ** fts3ExprIterate() callback to load the 'global' elements of a
   129386 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   129387 ** of the matchinfo array that are constant for all rows returned by the
   129388 ** current query.
   129389 **
   129390 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   129391 ** function populates Matchinfo.aMatchinfo[] as follows:
   129392 **
   129393 **   for(iCol=0; iCol<nCol; iCol++){
   129394 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   129395 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   129396 **   }
   129397 **
   129398 ** where X is the number of matches for phrase iPhrase is column iCol of all
   129399 ** rows of the table. Y is the number of rows for which column iCol contains
   129400 ** at least one instance of phrase iPhrase.
   129401 **
   129402 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   129403 ** Y values are set to nDoc, where nDoc is the number of documents in the
   129404 ** file system. This is done because the full-text index doclist is required
   129405 ** to calculate these values properly, and the full-text index doclist is
   129406 ** not available for deferred tokens.
   129407 */
   129408 static int fts3ExprGlobalHitsCb(
   129409   Fts3Expr *pExpr,                /* Phrase expression node */
   129410   int iPhrase,                    /* Phrase number (numbered from zero) */
   129411   void *pCtx                      /* Pointer to MatchInfo structure */
   129412 ){
   129413   MatchInfo *p = (MatchInfo *)pCtx;
   129414   return sqlite3Fts3EvalPhraseStats(
   129415       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
   129416   );
   129417 }
   129418 
   129419 /*
   129420 ** fts3ExprIterate() callback used to collect the "local" part of the
   129421 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   129422 ** array that are different for each row returned by the query.
   129423 */
   129424 static int fts3ExprLocalHitsCb(
   129425   Fts3Expr *pExpr,                /* Phrase expression node */
   129426   int iPhrase,                    /* Phrase number */
   129427   void *pCtx                      /* Pointer to MatchInfo structure */
   129428 ){
   129429   MatchInfo *p = (MatchInfo *)pCtx;
   129430   int iStart = iPhrase * p->nCol * 3;
   129431   int i;
   129432 
   129433   for(i=0; i<p->nCol; i++){
   129434     char *pCsr;
   129435     pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
   129436     if( pCsr ){
   129437       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
   129438     }else{
   129439       p->aMatchinfo[iStart+i*3] = 0;
   129440     }
   129441   }
   129442 
   129443   return SQLITE_OK;
   129444 }
   129445 
   129446 static int fts3MatchinfoCheck(
   129447   Fts3Table *pTab,
   129448   char cArg,
   129449   char **pzErr
   129450 ){
   129451   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   129452    || (cArg==FTS3_MATCHINFO_NCOL)
   129453    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
   129454    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
   129455    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   129456    || (cArg==FTS3_MATCHINFO_LCS)
   129457    || (cArg==FTS3_MATCHINFO_HITS)
   129458   ){
   129459     return SQLITE_OK;
   129460   }
   129461   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
   129462   return SQLITE_ERROR;
   129463 }
   129464 
   129465 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   129466   int nVal;                       /* Number of integers output by cArg */
   129467 
   129468   switch( cArg ){
   129469     case FTS3_MATCHINFO_NDOC:
   129470     case FTS3_MATCHINFO_NPHRASE:
   129471     case FTS3_MATCHINFO_NCOL:
   129472       nVal = 1;
   129473       break;
   129474 
   129475     case FTS3_MATCHINFO_AVGLENGTH:
   129476     case FTS3_MATCHINFO_LENGTH:
   129477     case FTS3_MATCHINFO_LCS:
   129478       nVal = pInfo->nCol;
   129479       break;
   129480 
   129481     default:
   129482       assert( cArg==FTS3_MATCHINFO_HITS );
   129483       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   129484       break;
   129485   }
   129486 
   129487   return nVal;
   129488 }
   129489 
   129490 static int fts3MatchinfoSelectDoctotal(
   129491   Fts3Table *pTab,
   129492   sqlite3_stmt **ppStmt,
   129493   sqlite3_int64 *pnDoc,
   129494   const char **paLen
   129495 ){
   129496   sqlite3_stmt *pStmt;
   129497   const char *a;
   129498   sqlite3_int64 nDoc;
   129499 
   129500   if( !*ppStmt ){
   129501     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   129502     if( rc!=SQLITE_OK ) return rc;
   129503   }
   129504   pStmt = *ppStmt;
   129505   assert( sqlite3_data_count(pStmt)==1 );
   129506 
   129507   a = sqlite3_column_blob(pStmt, 0);
   129508   a += sqlite3Fts3GetVarint(a, &nDoc);
   129509   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
   129510   *pnDoc = (u32)nDoc;
   129511 
   129512   if( paLen ) *paLen = a;
   129513   return SQLITE_OK;
   129514 }
   129515 
   129516 /*
   129517 ** An instance of the following structure is used to store state while
   129518 ** iterating through a multi-column position-list corresponding to the
   129519 ** hits for a single phrase on a single row in order to calculate the
   129520 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   129521 */
   129522 typedef struct LcsIterator LcsIterator;
   129523 struct LcsIterator {
   129524   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   129525   int iPosOffset;                 /* Tokens count up to end of this phrase */
   129526   char *pRead;                    /* Cursor used to iterate through aDoclist */
   129527   int iPos;                       /* Current position */
   129528 };
   129529 
   129530 /*
   129531 ** If LcsIterator.iCol is set to the following value, the iterator has
   129532 ** finished iterating through all offsets for all columns.
   129533 */
   129534 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   129535 
   129536 static int fts3MatchinfoLcsCb(
   129537   Fts3Expr *pExpr,                /* Phrase expression node */
   129538   int iPhrase,                    /* Phrase number (numbered from zero) */
   129539   void *pCtx                      /* Pointer to MatchInfo structure */
   129540 ){
   129541   LcsIterator *aIter = (LcsIterator *)pCtx;
   129542   aIter[iPhrase].pExpr = pExpr;
   129543   return SQLITE_OK;
   129544 }
   129545 
   129546 /*
   129547 ** Advance the iterator passed as an argument to the next position. Return
   129548 ** 1 if the iterator is at EOF or if it now points to the start of the
   129549 ** position list for the next column.
   129550 */
   129551 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   129552   char *pRead = pIter->pRead;
   129553   sqlite3_int64 iRead;
   129554   int rc = 0;
   129555 
   129556   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   129557   if( iRead==0 || iRead==1 ){
   129558     pRead = 0;
   129559     rc = 1;
   129560   }else{
   129561     pIter->iPos += (int)(iRead-2);
   129562   }
   129563 
   129564   pIter->pRead = pRead;
   129565   return rc;
   129566 }
   129567 
   129568 /*
   129569 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   129570 **
   129571 ** If the call is successful, the longest-common-substring lengths for each
   129572 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   129573 ** array before returning. SQLITE_OK is returned in this case.
   129574 **
   129575 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   129576 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   129577 ** undefined.
   129578 */
   129579 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   129580   LcsIterator *aIter;
   129581   int i;
   129582   int iCol;
   129583   int nToken = 0;
   129584 
   129585   /* Allocate and populate the array of LcsIterator objects. The array
   129586   ** contains one element for each matchable phrase in the query.
   129587   **/
   129588   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   129589   if( !aIter ) return SQLITE_NOMEM;
   129590   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   129591   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   129592 
   129593   for(i=0; i<pInfo->nPhrase; i++){
   129594     LcsIterator *pIter = &aIter[i];
   129595     nToken -= pIter->pExpr->pPhrase->nToken;
   129596     pIter->iPosOffset = nToken;
   129597   }
   129598 
   129599   for(iCol=0; iCol<pInfo->nCol; iCol++){
   129600     int nLcs = 0;                 /* LCS value for this column */
   129601     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   129602 
   129603     for(i=0; i<pInfo->nPhrase; i++){
   129604       LcsIterator *pIt = &aIter[i];
   129605       pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
   129606       if( pIt->pRead ){
   129607         pIt->iPos = pIt->iPosOffset;
   129608         fts3LcsIteratorAdvance(&aIter[i]);
   129609         nLive++;
   129610       }
   129611     }
   129612 
   129613     while( nLive>0 ){
   129614       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   129615       int nThisLcs = 0;           /* LCS for the current iterator positions */
   129616 
   129617       for(i=0; i<pInfo->nPhrase; i++){
   129618         LcsIterator *pIter = &aIter[i];
   129619         if( pIter->pRead==0 ){
   129620           /* This iterator is already at EOF for this column. */
   129621           nThisLcs = 0;
   129622         }else{
   129623           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   129624             pAdv = pIter;
   129625           }
   129626           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   129627             nThisLcs++;
   129628           }else{
   129629             nThisLcs = 1;
   129630           }
   129631           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   129632         }
   129633       }
   129634       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   129635     }
   129636 
   129637     pInfo->aMatchinfo[iCol] = nLcs;
   129638   }
   129639 
   129640   sqlite3_free(aIter);
   129641   return SQLITE_OK;
   129642 }
   129643 
   129644 /*
   129645 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   129646 ** be returned by the matchinfo() function. Argument zArg contains the
   129647 ** format string passed as the second argument to matchinfo (or the
   129648 ** default value "pcx" if no second argument was specified). The format
   129649 ** string has already been validated and the pInfo->aMatchinfo[] array
   129650 ** is guaranteed to be large enough for the output.
   129651 **
   129652 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   129653 ** If it is false, then assume that those fields that do not change between
   129654 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   129655 ** have already been populated.
   129656 **
   129657 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   129658 ** occurs. If a value other than SQLITE_OK is returned, the state the
   129659 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   129660 */
   129661 static int fts3MatchinfoValues(
   129662   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   129663   int bGlobal,                    /* True to grab the global stats */
   129664   MatchInfo *pInfo,               /* Matchinfo context object */
   129665   const char *zArg                /* Matchinfo format string */
   129666 ){
   129667   int rc = SQLITE_OK;
   129668   int i;
   129669   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129670   sqlite3_stmt *pSelect = 0;
   129671 
   129672   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   129673 
   129674     switch( zArg[i] ){
   129675       case FTS3_MATCHINFO_NPHRASE:
   129676         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   129677         break;
   129678 
   129679       case FTS3_MATCHINFO_NCOL:
   129680         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   129681         break;
   129682 
   129683       case FTS3_MATCHINFO_NDOC:
   129684         if( bGlobal ){
   129685           sqlite3_int64 nDoc = 0;
   129686           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   129687           pInfo->aMatchinfo[0] = (u32)nDoc;
   129688         }
   129689         break;
   129690 
   129691       case FTS3_MATCHINFO_AVGLENGTH:
   129692         if( bGlobal ){
   129693           sqlite3_int64 nDoc;     /* Number of rows in table */
   129694           const char *a;          /* Aggregate column length array */
   129695 
   129696           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   129697           if( rc==SQLITE_OK ){
   129698             int iCol;
   129699             for(iCol=0; iCol<pInfo->nCol; iCol++){
   129700               u32 iVal;
   129701               sqlite3_int64 nToken;
   129702               a += sqlite3Fts3GetVarint(a, &nToken);
   129703               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   129704               pInfo->aMatchinfo[iCol] = iVal;
   129705             }
   129706           }
   129707         }
   129708         break;
   129709 
   129710       case FTS3_MATCHINFO_LENGTH: {
   129711         sqlite3_stmt *pSelectDocsize = 0;
   129712         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   129713         if( rc==SQLITE_OK ){
   129714           int iCol;
   129715           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   129716           for(iCol=0; iCol<pInfo->nCol; iCol++){
   129717             sqlite3_int64 nToken;
   129718             a += sqlite3Fts3GetVarint(a, &nToken);
   129719             pInfo->aMatchinfo[iCol] = (u32)nToken;
   129720           }
   129721         }
   129722         sqlite3_reset(pSelectDocsize);
   129723         break;
   129724       }
   129725 
   129726       case FTS3_MATCHINFO_LCS:
   129727         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   129728         if( rc==SQLITE_OK ){
   129729           rc = fts3MatchinfoLcs(pCsr, pInfo);
   129730         }
   129731         break;
   129732 
   129733       default: {
   129734         Fts3Expr *pExpr;
   129735         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   129736         pExpr = pCsr->pExpr;
   129737         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   129738         if( rc!=SQLITE_OK ) break;
   129739         if( bGlobal ){
   129740           if( pCsr->pDeferred ){
   129741             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   129742             if( rc!=SQLITE_OK ) break;
   129743           }
   129744           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   129745           if( rc!=SQLITE_OK ) break;
   129746         }
   129747         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   129748         break;
   129749       }
   129750     }
   129751 
   129752     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   129753   }
   129754 
   129755   sqlite3_reset(pSelect);
   129756   return rc;
   129757 }
   129758 
   129759 
   129760 /*
   129761 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   129762 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   129763 */
   129764 static int fts3GetMatchinfo(
   129765   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   129766   const char *zArg                /* Second argument to matchinfo() function */
   129767 ){
   129768   MatchInfo sInfo;
   129769   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129770   int rc = SQLITE_OK;
   129771   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   129772 
   129773   memset(&sInfo, 0, sizeof(MatchInfo));
   129774   sInfo.pCursor = pCsr;
   129775   sInfo.nCol = pTab->nColumn;
   129776 
   129777   /* If there is cached matchinfo() data, but the format string for the
   129778   ** cache does not match the format string for this request, discard
   129779   ** the cached data. */
   129780   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
   129781     assert( pCsr->aMatchinfo );
   129782     sqlite3_free(pCsr->aMatchinfo);
   129783     pCsr->zMatchinfo = 0;
   129784     pCsr->aMatchinfo = 0;
   129785   }
   129786 
   129787   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
   129788   ** matchinfo function has been called for this query. In this case
   129789   ** allocate the array used to accumulate the matchinfo data and
   129790   ** initialize those elements that are constant for every row.
   129791   */
   129792   if( pCsr->aMatchinfo==0 ){
   129793     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   129794     int nArg;                     /* Bytes in zArg */
   129795     int i;                        /* Used to iterate through zArg */
   129796 
   129797     /* Determine the number of phrases in the query */
   129798     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   129799     sInfo.nPhrase = pCsr->nPhrase;
   129800 
   129801     /* Determine the number of integers in the buffer returned by this call. */
   129802     for(i=0; zArg[i]; i++){
   129803       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   129804     }
   129805 
   129806     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   129807     nArg = (int)strlen(zArg);
   129808     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
   129809     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
   129810 
   129811     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
   129812     pCsr->nMatchinfo = nMatchinfo;
   129813     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
   129814     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
   129815     pCsr->isMatchinfoNeeded = 1;
   129816     bGlobal = 1;
   129817   }
   129818 
   129819   sInfo.aMatchinfo = pCsr->aMatchinfo;
   129820   sInfo.nPhrase = pCsr->nPhrase;
   129821   if( pCsr->isMatchinfoNeeded ){
   129822     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   129823     pCsr->isMatchinfoNeeded = 0;
   129824   }
   129825 
   129826   return rc;
   129827 }
   129828 
   129829 /*
   129830 ** Implementation of snippet() function.
   129831 */
   129832 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   129833   sqlite3_context *pCtx,          /* SQLite function call context */
   129834   Fts3Cursor *pCsr,               /* Cursor object */
   129835   const char *zStart,             /* Snippet start text - "<b>" */
   129836   const char *zEnd,               /* Snippet end text - "</b>" */
   129837   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   129838   int iCol,                       /* Extract snippet from this column */
   129839   int nToken                      /* Approximate number of tokens in snippet */
   129840 ){
   129841   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129842   int rc = SQLITE_OK;
   129843   int i;
   129844   StrBuffer res = {0, 0, 0};
   129845 
   129846   /* The returned text includes up to four fragments of text extracted from
   129847   ** the data in the current row. The first iteration of the for(...) loop
   129848   ** below attempts to locate a single fragment of text nToken tokens in
   129849   ** size that contains at least one instance of all phrases in the query
   129850   ** expression that appear in the current row. If such a fragment of text
   129851   ** cannot be found, the second iteration of the loop attempts to locate
   129852   ** a pair of fragments, and so on.
   129853   */
   129854   int nSnippet = 0;               /* Number of fragments in this snippet */
   129855   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   129856   int nFToken = -1;               /* Number of tokens in each fragment */
   129857 
   129858   if( !pCsr->pExpr ){
   129859     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   129860     return;
   129861   }
   129862 
   129863   for(nSnippet=1; 1; nSnippet++){
   129864 
   129865     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   129866     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   129867     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   129868 
   129869     if( nToken>=0 ){
   129870       nFToken = (nToken+nSnippet-1) / nSnippet;
   129871     }else{
   129872       nFToken = -1 * nToken;
   129873     }
   129874 
   129875     for(iSnip=0; iSnip<nSnippet; iSnip++){
   129876       int iBestScore = -1;        /* Best score of columns checked so far */
   129877       int iRead;                  /* Used to iterate through columns */
   129878       SnippetFragment *pFragment = &aSnippet[iSnip];
   129879 
   129880       memset(pFragment, 0, sizeof(*pFragment));
   129881 
   129882       /* Loop through all columns of the table being considered for snippets.
   129883       ** If the iCol argument to this function was negative, this means all
   129884       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   129885       */
   129886       for(iRead=0; iRead<pTab->nColumn; iRead++){
   129887         SnippetFragment sF = {0, 0, 0, 0};
   129888         int iS;
   129889         if( iCol>=0 && iRead!=iCol ) continue;
   129890 
   129891         /* Find the best snippet of nFToken tokens in column iRead. */
   129892         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   129893         if( rc!=SQLITE_OK ){
   129894           goto snippet_out;
   129895         }
   129896         if( iS>iBestScore ){
   129897           *pFragment = sF;
   129898           iBestScore = iS;
   129899         }
   129900       }
   129901 
   129902       mCovered |= pFragment->covered;
   129903     }
   129904 
   129905     /* If all query phrases seen by fts3BestSnippet() are present in at least
   129906     ** one of the nSnippet snippet fragments, break out of the loop.
   129907     */
   129908     assert( (mCovered&mSeen)==mCovered );
   129909     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   129910   }
   129911 
   129912   assert( nFToken>0 );
   129913 
   129914   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   129915     rc = fts3SnippetText(pCsr, &aSnippet[i],
   129916         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   129917     );
   129918   }
   129919 
   129920  snippet_out:
   129921   sqlite3Fts3SegmentsClose(pTab);
   129922   if( rc!=SQLITE_OK ){
   129923     sqlite3_result_error_code(pCtx, rc);
   129924     sqlite3_free(res.z);
   129925   }else{
   129926     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   129927   }
   129928 }
   129929 
   129930 
   129931 typedef struct TermOffset TermOffset;
   129932 typedef struct TermOffsetCtx TermOffsetCtx;
   129933 
   129934 struct TermOffset {
   129935   char *pList;                    /* Position-list */
   129936   int iPos;                       /* Position just read from pList */
   129937   int iOff;                       /* Offset of this term from read positions */
   129938 };
   129939 
   129940 struct TermOffsetCtx {
   129941   Fts3Cursor *pCsr;
   129942   int iCol;                       /* Column of table to populate aTerm for */
   129943   int iTerm;
   129944   sqlite3_int64 iDocid;
   129945   TermOffset *aTerm;
   129946 };
   129947 
   129948 /*
   129949 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   129950 */
   129951 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   129952   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   129953   int nTerm;                      /* Number of tokens in phrase */
   129954   int iTerm;                      /* For looping through nTerm phrase terms */
   129955   char *pList;                    /* Pointer to position list for phrase */
   129956   int iPos = 0;                   /* First position in position-list */
   129957 
   129958   UNUSED_PARAMETER(iPhrase);
   129959   pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
   129960   nTerm = pExpr->pPhrase->nToken;
   129961   if( pList ){
   129962     fts3GetDeltaPosition(&pList, &iPos);
   129963     assert( iPos>=0 );
   129964   }
   129965 
   129966   for(iTerm=0; iTerm<nTerm; iTerm++){
   129967     TermOffset *pT = &p->aTerm[p->iTerm++];
   129968     pT->iOff = nTerm-iTerm-1;
   129969     pT->pList = pList;
   129970     pT->iPos = iPos;
   129971   }
   129972 
   129973   return SQLITE_OK;
   129974 }
   129975 
   129976 /*
   129977 ** Implementation of offsets() function.
   129978 */
   129979 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   129980   sqlite3_context *pCtx,          /* SQLite function call context */
   129981   Fts3Cursor *pCsr                /* Cursor object */
   129982 ){
   129983   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129984   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   129985   const char *ZDUMMY;             /* Dummy argument used with xNext() */
   129986   int NDUMMY;                     /* Dummy argument used with xNext() */
   129987   int rc;                         /* Return Code */
   129988   int nToken;                     /* Number of tokens in query */
   129989   int iCol;                       /* Column currently being processed */
   129990   StrBuffer res = {0, 0, 0};      /* Result string */
   129991   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   129992 
   129993   if( !pCsr->pExpr ){
   129994     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   129995     return;
   129996   }
   129997 
   129998   memset(&sCtx, 0, sizeof(sCtx));
   129999   assert( pCsr->isRequireSeek==0 );
   130000 
   130001   /* Count the number of terms in the query */
   130002   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   130003   if( rc!=SQLITE_OK ) goto offsets_out;
   130004 
   130005   /* Allocate the array of TermOffset iterators. */
   130006   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   130007   if( 0==sCtx.aTerm ){
   130008     rc = SQLITE_NOMEM;
   130009     goto offsets_out;
   130010   }
   130011   sCtx.iDocid = pCsr->iPrevId;
   130012   sCtx.pCsr = pCsr;
   130013 
   130014   /* Loop through the table columns, appending offset information to
   130015   ** string-buffer res for each column.
   130016   */
   130017   for(iCol=0; iCol<pTab->nColumn; iCol++){
   130018     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   130019     int iStart;
   130020     int iEnd;
   130021     int iCurrent;
   130022     const char *zDoc;
   130023     int nDoc;
   130024 
   130025     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   130026     ** no way that this operation can fail, so the return code from
   130027     ** fts3ExprIterate() can be discarded.
   130028     */
   130029     sCtx.iCol = iCol;
   130030     sCtx.iTerm = 0;
   130031     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
   130032 
   130033     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   130034     ** in column iCol, jump immediately to the next iteration of the loop.
   130035     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   130036     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   130037     ** to the caller.
   130038     */
   130039     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   130040     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   130041     if( zDoc==0 ){
   130042       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   130043         continue;
   130044       }
   130045       rc = SQLITE_NOMEM;
   130046       goto offsets_out;
   130047     }
   130048 
   130049     /* Initialize a tokenizer iterator to iterate through column iCol. */
   130050     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
   130051         zDoc, nDoc, &pC
   130052     );
   130053     if( rc!=SQLITE_OK ) goto offsets_out;
   130054 
   130055     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   130056     while( rc==SQLITE_OK ){
   130057       int i;                      /* Used to loop through terms */
   130058       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   130059       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   130060 
   130061       for(i=0; i<nToken; i++){
   130062         TermOffset *pT = &sCtx.aTerm[i];
   130063         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   130064           iMinPos = pT->iPos-pT->iOff;
   130065           pTerm = pT;
   130066         }
   130067       }
   130068 
   130069       if( !pTerm ){
   130070         /* All offsets for this column have been gathered. */
   130071         rc = SQLITE_DONE;
   130072       }else{
   130073         assert( iCurrent<=iMinPos );
   130074         if( 0==(0xFE&*pTerm->pList) ){
   130075           pTerm->pList = 0;
   130076         }else{
   130077           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   130078         }
   130079         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   130080           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   130081         }
   130082         if( rc==SQLITE_OK ){
   130083           char aBuffer[64];
   130084           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   130085               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   130086           );
   130087           rc = fts3StringAppend(&res, aBuffer, -1);
   130088         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
   130089           rc = FTS_CORRUPT_VTAB;
   130090         }
   130091       }
   130092     }
   130093     if( rc==SQLITE_DONE ){
   130094       rc = SQLITE_OK;
   130095     }
   130096 
   130097     pMod->xClose(pC);
   130098     if( rc!=SQLITE_OK ) goto offsets_out;
   130099   }
   130100 
   130101  offsets_out:
   130102   sqlite3_free(sCtx.aTerm);
   130103   assert( rc!=SQLITE_DONE );
   130104   sqlite3Fts3SegmentsClose(pTab);
   130105   if( rc!=SQLITE_OK ){
   130106     sqlite3_result_error_code(pCtx,  rc);
   130107     sqlite3_free(res.z);
   130108   }else{
   130109     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   130110   }
   130111   return;
   130112 }
   130113 
   130114 /*
   130115 ** Implementation of matchinfo() function.
   130116 */
   130117 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   130118   sqlite3_context *pContext,      /* Function call context */
   130119   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   130120   const char *zArg                /* Second arg to matchinfo() function */
   130121 ){
   130122   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130123   int rc;
   130124   int i;
   130125   const char *zFormat;
   130126 
   130127   if( zArg ){
   130128     for(i=0; zArg[i]; i++){
   130129       char *zErr = 0;
   130130       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   130131         sqlite3_result_error(pContext, zErr, -1);
   130132         sqlite3_free(zErr);
   130133         return;
   130134       }
   130135     }
   130136     zFormat = zArg;
   130137   }else{
   130138     zFormat = FTS3_MATCHINFO_DEFAULT;
   130139   }
   130140 
   130141   if( !pCsr->pExpr ){
   130142     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   130143     return;
   130144   }
   130145 
   130146   /* Retrieve matchinfo() data. */
   130147   rc = fts3GetMatchinfo(pCsr, zFormat);
   130148   sqlite3Fts3SegmentsClose(pTab);
   130149 
   130150   if( rc!=SQLITE_OK ){
   130151     sqlite3_result_error_code(pContext, rc);
   130152   }else{
   130153     int n = pCsr->nMatchinfo * sizeof(u32);
   130154     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   130155   }
   130156 }
   130157 
   130158 #endif
   130159 
   130160 /************** End of fts3_snippet.c ****************************************/
   130161 /************** Begin file rtree.c *******************************************/
   130162 /*
   130163 ** 2001 September 15
   130164 **
   130165 ** The author disclaims copyright to this source code.  In place of
   130166 ** a legal notice, here is a blessing:
   130167 **
   130168 **    May you do good and not evil.
   130169 **    May you find forgiveness for yourself and forgive others.
   130170 **    May you share freely, never taking more than you give.
   130171 **
   130172 *************************************************************************
   130173 ** This file contains code for implementations of the r-tree and r*-tree
   130174 ** algorithms packaged as an SQLite virtual table module.
   130175 */
   130176 
   130177 /*
   130178 ** Database Format of R-Tree Tables
   130179 ** --------------------------------
   130180 **
   130181 ** The data structure for a single virtual r-tree table is stored in three
   130182 ** native SQLite tables declared as follows. In each case, the '%' character
   130183 ** in the table name is replaced with the user-supplied name of the r-tree
   130184 ** table.
   130185 **
   130186 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   130187 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   130188 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   130189 **
   130190 ** The data for each node of the r-tree structure is stored in the %_node
   130191 ** table. For each node that is not the root node of the r-tree, there is
   130192 ** an entry in the %_parent table associating the node with its parent.
   130193 ** And for each row of data in the table, there is an entry in the %_rowid
   130194 ** table that maps from the entries rowid to the id of the node that it
   130195 ** is stored on.
   130196 **
   130197 ** The root node of an r-tree always exists, even if the r-tree table is
   130198 ** empty. The nodeno of the root node is always 1. All other nodes in the
   130199 ** table must be the same size as the root node. The content of each node
   130200 ** is formatted as follows:
   130201 **
   130202 **   1. If the node is the root node (node 1), then the first 2 bytes
   130203 **      of the node contain the tree depth as a big-endian integer.
   130204 **      For non-root nodes, the first 2 bytes are left unused.
   130205 **
   130206 **   2. The next 2 bytes contain the number of entries currently
   130207 **      stored in the node.
   130208 **
   130209 **   3. The remainder of the node contains the node entries. Each entry
   130210 **      consists of a single 8-byte integer followed by an even number
   130211 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   130212 **      of a record. For internal nodes it is the node number of a
   130213 **      child page.
   130214 */
   130215 
   130216 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   130217 
   130218 /*
   130219 ** This file contains an implementation of a couple of different variants
   130220 ** of the r-tree algorithm. See the README file for further details. The
   130221 ** same data-structure is used for all, but the algorithms for insert and
   130222 ** delete operations vary. The variants used are selected at compile time
   130223 ** by defining the following symbols:
   130224 */
   130225 
   130226 /* Either, both or none of the following may be set to activate
   130227 ** r*tree variant algorithms.
   130228 */
   130229 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
   130230 #define VARIANT_RSTARTREE_REINSERT      1
   130231 
   130232 /*
   130233 ** Exactly one of the following must be set to 1.
   130234 */
   130235 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
   130236 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
   130237 #define VARIANT_RSTARTREE_SPLIT         1
   130238 
   130239 #define VARIANT_GUTTMAN_SPLIT \
   130240         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
   130241 
   130242 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   130243   #define PickNext QuadraticPickNext
   130244   #define PickSeeds QuadraticPickSeeds
   130245   #define AssignCells splitNodeGuttman
   130246 #endif
   130247 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   130248   #define PickNext LinearPickNext
   130249   #define PickSeeds LinearPickSeeds
   130250   #define AssignCells splitNodeGuttman
   130251 #endif
   130252 #if VARIANT_RSTARTREE_SPLIT
   130253   #define AssignCells splitNodeStartree
   130254 #endif
   130255 
   130256 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   130257 # define NDEBUG 1
   130258 #endif
   130259 
   130260 #ifndef SQLITE_CORE
   130261   SQLITE_EXTENSION_INIT1
   130262 #else
   130263 #endif
   130264 
   130265 /* #include <string.h> */
   130266 /* #include <assert.h> */
   130267 
   130268 #ifndef SQLITE_AMALGAMATION
   130269 #include "sqlite3rtree.h"
   130270 typedef sqlite3_int64 i64;
   130271 typedef unsigned char u8;
   130272 typedef unsigned int u32;
   130273 #endif
   130274 
   130275 /*  The following macro is used to suppress compiler warnings.
   130276 */
   130277 #ifndef UNUSED_PARAMETER
   130278 # define UNUSED_PARAMETER(x) (void)(x)
   130279 #endif
   130280 
   130281 typedef struct Rtree Rtree;
   130282 typedef struct RtreeCursor RtreeCursor;
   130283 typedef struct RtreeNode RtreeNode;
   130284 typedef struct RtreeCell RtreeCell;
   130285 typedef struct RtreeConstraint RtreeConstraint;
   130286 typedef struct RtreeMatchArg RtreeMatchArg;
   130287 typedef struct RtreeGeomCallback RtreeGeomCallback;
   130288 typedef union RtreeCoord RtreeCoord;
   130289 
   130290 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   130291 #define RTREE_MAX_DIMENSIONS 5
   130292 
   130293 /* Size of hash table Rtree.aHash. This hash table is not expected to
   130294 ** ever contain very many entries, so a fixed number of buckets is
   130295 ** used.
   130296 */
   130297 #define HASHSIZE 128
   130298 
   130299 /*
   130300 ** An rtree virtual-table object.
   130301 */
   130302 struct Rtree {
   130303   sqlite3_vtab base;
   130304   sqlite3 *db;                /* Host database connection */
   130305   int iNodeSize;              /* Size in bytes of each node in the node table */
   130306   int nDim;                   /* Number of dimensions */
   130307   int nBytesPerCell;          /* Bytes consumed per cell */
   130308   int iDepth;                 /* Current depth of the r-tree structure */
   130309   char *zDb;                  /* Name of database containing r-tree table */
   130310   char *zName;                /* Name of r-tree table */
   130311   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   130312   int nBusy;                  /* Current number of users of this structure */
   130313 
   130314   /* List of nodes removed during a CondenseTree operation. List is
   130315   ** linked together via the pointer normally used for hash chains -
   130316   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   130317   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   130318   */
   130319   RtreeNode *pDeleted;
   130320   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   130321 
   130322   /* Statements to read/write/delete a record from xxx_node */
   130323   sqlite3_stmt *pReadNode;
   130324   sqlite3_stmt *pWriteNode;
   130325   sqlite3_stmt *pDeleteNode;
   130326 
   130327   /* Statements to read/write/delete a record from xxx_rowid */
   130328   sqlite3_stmt *pReadRowid;
   130329   sqlite3_stmt *pWriteRowid;
   130330   sqlite3_stmt *pDeleteRowid;
   130331 
   130332   /* Statements to read/write/delete a record from xxx_parent */
   130333   sqlite3_stmt *pReadParent;
   130334   sqlite3_stmt *pWriteParent;
   130335   sqlite3_stmt *pDeleteParent;
   130336 
   130337   int eCoordType;
   130338 };
   130339 
   130340 /* Possible values for eCoordType: */
   130341 #define RTREE_COORD_REAL32 0
   130342 #define RTREE_COORD_INT32  1
   130343 
   130344 /*
   130345 ** The minimum number of cells allowed for a node is a third of the
   130346 ** maximum. In Gutman's notation:
   130347 **
   130348 **     m = M/3
   130349 **
   130350 ** If an R*-tree "Reinsert" operation is required, the same number of
   130351 ** cells are removed from the overfull node and reinserted into the tree.
   130352 */
   130353 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   130354 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   130355 #define RTREE_MAXCELLS 51
   130356 
   130357 /*
   130358 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   130359 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   130360 ** Therefore all non-root nodes must contain at least 3 entries. Since
   130361 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
   130362 ** 40 or less.
   130363 */
   130364 #define RTREE_MAX_DEPTH 40
   130365 
   130366 /*
   130367 ** An rtree cursor object.
   130368 */
   130369 struct RtreeCursor {
   130370   sqlite3_vtab_cursor base;
   130371   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
   130372   int iCell;                        /* Index of current cell in pNode */
   130373   int iStrategy;                    /* Copy of idxNum search parameter */
   130374   int nConstraint;                  /* Number of entries in aConstraint */
   130375   RtreeConstraint *aConstraint;     /* Search constraints. */
   130376 };
   130377 
   130378 union RtreeCoord {
   130379   float f;
   130380   int i;
   130381 };
   130382 
   130383 /*
   130384 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   130385 ** formatted as a double. This macro assumes that local variable pRtree points
   130386 ** to the Rtree structure associated with the RtreeCoord.
   130387 */
   130388 #define DCOORD(coord) (                           \
   130389   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   130390     ((double)coord.f) :                           \
   130391     ((double)coord.i)                             \
   130392 )
   130393 
   130394 /*
   130395 ** A search constraint.
   130396 */
   130397 struct RtreeConstraint {
   130398   int iCoord;                     /* Index of constrained coordinate */
   130399   int op;                         /* Constraining operation */
   130400   double rValue;                  /* Constraint value. */
   130401   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130402   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
   130403 };
   130404 
   130405 /* Possible values for RtreeConstraint.op */
   130406 #define RTREE_EQ    0x41
   130407 #define RTREE_LE    0x42
   130408 #define RTREE_LT    0x43
   130409 #define RTREE_GE    0x44
   130410 #define RTREE_GT    0x45
   130411 #define RTREE_MATCH 0x46
   130412 
   130413 /*
   130414 ** An rtree structure node.
   130415 */
   130416 struct RtreeNode {
   130417   RtreeNode *pParent;               /* Parent node */
   130418   i64 iNode;
   130419   int nRef;
   130420   int isDirty;
   130421   u8 *zData;
   130422   RtreeNode *pNext;                 /* Next node in this hash chain */
   130423 };
   130424 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   130425 
   130426 /*
   130427 ** Structure to store a deserialized rtree record.
   130428 */
   130429 struct RtreeCell {
   130430   i64 iRowid;
   130431   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
   130432 };
   130433 
   130434 
   130435 /*
   130436 ** Value for the first field of every RtreeMatchArg object. The MATCH
   130437 ** operator tests that the first field of a blob operand matches this
   130438 ** value to avoid operating on invalid blobs (which could cause a segfault).
   130439 */
   130440 #define RTREE_GEOMETRY_MAGIC 0x891245AB
   130441 
   130442 /*
   130443 ** An instance of this structure must be supplied as a blob argument to
   130444 ** the right-hand-side of an SQL MATCH operator used to constrain an
   130445 ** r-tree query.
   130446 */
   130447 struct RtreeMatchArg {
   130448   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
   130449   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130450   void *pContext;
   130451   int nParam;
   130452   double aParam[1];
   130453 };
   130454 
   130455 /*
   130456 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
   130457 ** a single instance of the following structure is allocated. It is used
   130458 ** as the context for the user-function created by by s_r_g_c(). The object
   130459 ** is eventually deleted by the destructor mechanism provided by
   130460 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
   130461 ** the geometry callback function).
   130462 */
   130463 struct RtreeGeomCallback {
   130464   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130465   void *pContext;
   130466 };
   130467 
   130468 #ifndef MAX
   130469 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   130470 #endif
   130471 #ifndef MIN
   130472 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   130473 #endif
   130474 
   130475 /*
   130476 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   130477 ** 64 bit integer. The deserialized value is returned.
   130478 */
   130479 static int readInt16(u8 *p){
   130480   return (p[0]<<8) + p[1];
   130481 }
   130482 static void readCoord(u8 *p, RtreeCoord *pCoord){
   130483   u32 i = (
   130484     (((u32)p[0]) << 24) +
   130485     (((u32)p[1]) << 16) +
   130486     (((u32)p[2]) <<  8) +
   130487     (((u32)p[3]) <<  0)
   130488   );
   130489   *(u32 *)pCoord = i;
   130490 }
   130491 static i64 readInt64(u8 *p){
   130492   return (
   130493     (((i64)p[0]) << 56) +
   130494     (((i64)p[1]) << 48) +
   130495     (((i64)p[2]) << 40) +
   130496     (((i64)p[3]) << 32) +
   130497     (((i64)p[4]) << 24) +
   130498     (((i64)p[5]) << 16) +
   130499     (((i64)p[6]) <<  8) +
   130500     (((i64)p[7]) <<  0)
   130501   );
   130502 }
   130503 
   130504 /*
   130505 ** Functions to serialize a 16 bit integer, 32 bit real number and
   130506 ** 64 bit integer. The value returned is the number of bytes written
   130507 ** to the argument buffer (always 2, 4 and 8 respectively).
   130508 */
   130509 static int writeInt16(u8 *p, int i){
   130510   p[0] = (i>> 8)&0xFF;
   130511   p[1] = (i>> 0)&0xFF;
   130512   return 2;
   130513 }
   130514 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   130515   u32 i;
   130516   assert( sizeof(RtreeCoord)==4 );
   130517   assert( sizeof(u32)==4 );
   130518   i = *(u32 *)pCoord;
   130519   p[0] = (i>>24)&0xFF;
   130520   p[1] = (i>>16)&0xFF;
   130521   p[2] = (i>> 8)&0xFF;
   130522   p[3] = (i>> 0)&0xFF;
   130523   return 4;
   130524 }
   130525 static int writeInt64(u8 *p, i64 i){
   130526   p[0] = (i>>56)&0xFF;
   130527   p[1] = (i>>48)&0xFF;
   130528   p[2] = (i>>40)&0xFF;
   130529   p[3] = (i>>32)&0xFF;
   130530   p[4] = (i>>24)&0xFF;
   130531   p[5] = (i>>16)&0xFF;
   130532   p[6] = (i>> 8)&0xFF;
   130533   p[7] = (i>> 0)&0xFF;
   130534   return 8;
   130535 }
   130536 
   130537 /*
   130538 ** Increment the reference count of node p.
   130539 */
   130540 static void nodeReference(RtreeNode *p){
   130541   if( p ){
   130542     p->nRef++;
   130543   }
   130544 }
   130545 
   130546 /*
   130547 ** Clear the content of node p (set all bytes to 0x00).
   130548 */
   130549 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   130550   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   130551   p->isDirty = 1;
   130552 }
   130553 
   130554 /*
   130555 ** Given a node number iNode, return the corresponding key to use
   130556 ** in the Rtree.aHash table.
   130557 */
   130558 static int nodeHash(i64 iNode){
   130559   return (
   130560     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
   130561     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
   130562   ) % HASHSIZE;
   130563 }
   130564 
   130565 /*
   130566 ** Search the node hash table for node iNode. If found, return a pointer
   130567 ** to it. Otherwise, return 0.
   130568 */
   130569 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   130570   RtreeNode *p;
   130571   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   130572   return p;
   130573 }
   130574 
   130575 /*
   130576 ** Add node pNode to the node hash table.
   130577 */
   130578 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   130579   int iHash;
   130580   assert( pNode->pNext==0 );
   130581   iHash = nodeHash(pNode->iNode);
   130582   pNode->pNext = pRtree->aHash[iHash];
   130583   pRtree->aHash[iHash] = pNode;
   130584 }
   130585 
   130586 /*
   130587 ** Remove node pNode from the node hash table.
   130588 */
   130589 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   130590   RtreeNode **pp;
   130591   if( pNode->iNode!=0 ){
   130592     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   130593     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   130594     *pp = pNode->pNext;
   130595     pNode->pNext = 0;
   130596   }
   130597 }
   130598 
   130599 /*
   130600 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   130601 ** indicating that node has not yet been assigned a node number. It is
   130602 ** assigned a node number when nodeWrite() is called to write the
   130603 ** node contents out to the database.
   130604 */
   130605 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   130606   RtreeNode *pNode;
   130607   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   130608   if( pNode ){
   130609     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   130610     pNode->zData = (u8 *)&pNode[1];
   130611     pNode->nRef = 1;
   130612     pNode->pParent = pParent;
   130613     pNode->isDirty = 1;
   130614     nodeReference(pParent);
   130615   }
   130616   return pNode;
   130617 }
   130618 
   130619 /*
   130620 ** Obtain a reference to an r-tree node.
   130621 */
   130622 static int
   130623 nodeAcquire(
   130624   Rtree *pRtree,             /* R-tree structure */
   130625   i64 iNode,                 /* Node number to load */
   130626   RtreeNode *pParent,        /* Either the parent node or NULL */
   130627   RtreeNode **ppNode         /* OUT: Acquired node */
   130628 ){
   130629   int rc;
   130630   int rc2 = SQLITE_OK;
   130631   RtreeNode *pNode;
   130632 
   130633   /* Check if the requested node is already in the hash table. If so,
   130634   ** increase its reference count and return it.
   130635   */
   130636   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   130637     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   130638     if( pParent && !pNode->pParent ){
   130639       nodeReference(pParent);
   130640       pNode->pParent = pParent;
   130641     }
   130642     pNode->nRef++;
   130643     *ppNode = pNode;
   130644     return SQLITE_OK;
   130645   }
   130646 
   130647   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   130648   rc = sqlite3_step(pRtree->pReadNode);
   130649   if( rc==SQLITE_ROW ){
   130650     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   130651     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
   130652       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   130653       if( !pNode ){
   130654         rc2 = SQLITE_NOMEM;
   130655       }else{
   130656         pNode->pParent = pParent;
   130657         pNode->zData = (u8 *)&pNode[1];
   130658         pNode->nRef = 1;
   130659         pNode->iNode = iNode;
   130660         pNode->isDirty = 0;
   130661         pNode->pNext = 0;
   130662         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   130663         nodeReference(pParent);
   130664       }
   130665     }
   130666   }
   130667   rc = sqlite3_reset(pRtree->pReadNode);
   130668   if( rc==SQLITE_OK ) rc = rc2;
   130669 
   130670   /* If the root node was just loaded, set pRtree->iDepth to the height
   130671   ** of the r-tree structure. A height of zero means all data is stored on
   130672   ** the root node. A height of one means the children of the root node
   130673   ** are the leaves, and so on. If the depth as specified on the root node
   130674   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   130675   */
   130676   if( pNode && iNode==1 ){
   130677     pRtree->iDepth = readInt16(pNode->zData);
   130678     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   130679       rc = SQLITE_CORRUPT_VTAB;
   130680     }
   130681   }
   130682 
   130683   /* If no error has occurred so far, check if the "number of entries"
   130684   ** field on the node is too large. If so, set the return code to
   130685   ** SQLITE_CORRUPT_VTAB.
   130686   */
   130687   if( pNode && rc==SQLITE_OK ){
   130688     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   130689       rc = SQLITE_CORRUPT_VTAB;
   130690     }
   130691   }
   130692 
   130693   if( rc==SQLITE_OK ){
   130694     if( pNode!=0 ){
   130695       nodeHashInsert(pRtree, pNode);
   130696     }else{
   130697       rc = SQLITE_CORRUPT_VTAB;
   130698     }
   130699     *ppNode = pNode;
   130700   }else{
   130701     sqlite3_free(pNode);
   130702     *ppNode = 0;
   130703   }
   130704 
   130705   return rc;
   130706 }
   130707 
   130708 /*
   130709 ** Overwrite cell iCell of node pNode with the contents of pCell.
   130710 */
   130711 static void nodeOverwriteCell(
   130712   Rtree *pRtree,
   130713   RtreeNode *pNode,
   130714   RtreeCell *pCell,
   130715   int iCell
   130716 ){
   130717   int ii;
   130718   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   130719   p += writeInt64(p, pCell->iRowid);
   130720   for(ii=0; ii<(pRtree->nDim*2); ii++){
   130721     p += writeCoord(p, &pCell->aCoord[ii]);
   130722   }
   130723   pNode->isDirty = 1;
   130724 }
   130725 
   130726 /*
   130727 ** Remove cell the cell with index iCell from node pNode.
   130728 */
   130729 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   130730   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   130731   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   130732   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   130733   memmove(pDst, pSrc, nByte);
   130734   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   130735   pNode->isDirty = 1;
   130736 }
   130737 
   130738 /*
   130739 ** Insert the contents of cell pCell into node pNode. If the insert
   130740 ** is successful, return SQLITE_OK.
   130741 **
   130742 ** If there is not enough free space in pNode, return SQLITE_FULL.
   130743 */
   130744 static int
   130745 nodeInsertCell(
   130746   Rtree *pRtree,
   130747   RtreeNode *pNode,
   130748   RtreeCell *pCell
   130749 ){
   130750   int nCell;                    /* Current number of cells in pNode */
   130751   int nMaxCell;                 /* Maximum number of cells for pNode */
   130752 
   130753   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   130754   nCell = NCELL(pNode);
   130755 
   130756   assert( nCell<=nMaxCell );
   130757   if( nCell<nMaxCell ){
   130758     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   130759     writeInt16(&pNode->zData[2], nCell+1);
   130760     pNode->isDirty = 1;
   130761   }
   130762 
   130763   return (nCell==nMaxCell);
   130764 }
   130765 
   130766 /*
   130767 ** If the node is dirty, write it out to the database.
   130768 */
   130769 static int
   130770 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   130771   int rc = SQLITE_OK;
   130772   if( pNode->isDirty ){
   130773     sqlite3_stmt *p = pRtree->pWriteNode;
   130774     if( pNode->iNode ){
   130775       sqlite3_bind_int64(p, 1, pNode->iNode);
   130776     }else{
   130777       sqlite3_bind_null(p, 1);
   130778     }
   130779     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   130780     sqlite3_step(p);
   130781     pNode->isDirty = 0;
   130782     rc = sqlite3_reset(p);
   130783     if( pNode->iNode==0 && rc==SQLITE_OK ){
   130784       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   130785       nodeHashInsert(pRtree, pNode);
   130786     }
   130787   }
   130788   return rc;
   130789 }
   130790 
   130791 /*
   130792 ** Release a reference to a node. If the node is dirty and the reference
   130793 ** count drops to zero, the node data is written to the database.
   130794 */
   130795 static int
   130796 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   130797   int rc = SQLITE_OK;
   130798   if( pNode ){
   130799     assert( pNode->nRef>0 );
   130800     pNode->nRef--;
   130801     if( pNode->nRef==0 ){
   130802       if( pNode->iNode==1 ){
   130803         pRtree->iDepth = -1;
   130804       }
   130805       if( pNode->pParent ){
   130806         rc = nodeRelease(pRtree, pNode->pParent);
   130807       }
   130808       if( rc==SQLITE_OK ){
   130809         rc = nodeWrite(pRtree, pNode);
   130810       }
   130811       nodeHashDelete(pRtree, pNode);
   130812       sqlite3_free(pNode);
   130813     }
   130814   }
   130815   return rc;
   130816 }
   130817 
   130818 /*
   130819 ** Return the 64-bit integer value associated with cell iCell of
   130820 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   130821 ** an internal node, then the 64-bit integer is a child page number.
   130822 */
   130823 static i64 nodeGetRowid(
   130824   Rtree *pRtree,
   130825   RtreeNode *pNode,
   130826   int iCell
   130827 ){
   130828   assert( iCell<NCELL(pNode) );
   130829   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   130830 }
   130831 
   130832 /*
   130833 ** Return coordinate iCoord from cell iCell in node pNode.
   130834 */
   130835 static void nodeGetCoord(
   130836   Rtree *pRtree,
   130837   RtreeNode *pNode,
   130838   int iCell,
   130839   int iCoord,
   130840   RtreeCoord *pCoord           /* Space to write result to */
   130841 ){
   130842   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   130843 }
   130844 
   130845 /*
   130846 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   130847 ** to by pCell with the results.
   130848 */
   130849 static void nodeGetCell(
   130850   Rtree *pRtree,
   130851   RtreeNode *pNode,
   130852   int iCell,
   130853   RtreeCell *pCell
   130854 ){
   130855   int ii;
   130856   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   130857   for(ii=0; ii<pRtree->nDim*2; ii++){
   130858     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
   130859   }
   130860 }
   130861 
   130862 
   130863 /* Forward declaration for the function that does the work of
   130864 ** the virtual table module xCreate() and xConnect() methods.
   130865 */
   130866 static int rtreeInit(
   130867   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   130868 );
   130869 
   130870 /*
   130871 ** Rtree virtual table module xCreate method.
   130872 */
   130873 static int rtreeCreate(
   130874   sqlite3 *db,
   130875   void *pAux,
   130876   int argc, const char *const*argv,
   130877   sqlite3_vtab **ppVtab,
   130878   char **pzErr
   130879 ){
   130880   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   130881 }
   130882 
   130883 /*
   130884 ** Rtree virtual table module xConnect method.
   130885 */
   130886 static int rtreeConnect(
   130887   sqlite3 *db,
   130888   void *pAux,
   130889   int argc, const char *const*argv,
   130890   sqlite3_vtab **ppVtab,
   130891   char **pzErr
   130892 ){
   130893   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   130894 }
   130895 
   130896 /*
   130897 ** Increment the r-tree reference count.
   130898 */
   130899 static void rtreeReference(Rtree *pRtree){
   130900   pRtree->nBusy++;
   130901 }
   130902 
   130903 /*
   130904 ** Decrement the r-tree reference count. When the reference count reaches
   130905 ** zero the structure is deleted.
   130906 */
   130907 static void rtreeRelease(Rtree *pRtree){
   130908   pRtree->nBusy--;
   130909   if( pRtree->nBusy==0 ){
   130910     sqlite3_finalize(pRtree->pReadNode);
   130911     sqlite3_finalize(pRtree->pWriteNode);
   130912     sqlite3_finalize(pRtree->pDeleteNode);
   130913     sqlite3_finalize(pRtree->pReadRowid);
   130914     sqlite3_finalize(pRtree->pWriteRowid);
   130915     sqlite3_finalize(pRtree->pDeleteRowid);
   130916     sqlite3_finalize(pRtree->pReadParent);
   130917     sqlite3_finalize(pRtree->pWriteParent);
   130918     sqlite3_finalize(pRtree->pDeleteParent);
   130919     sqlite3_free(pRtree);
   130920   }
   130921 }
   130922 
   130923 /*
   130924 ** Rtree virtual table module xDisconnect method.
   130925 */
   130926 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   130927   rtreeRelease((Rtree *)pVtab);
   130928   return SQLITE_OK;
   130929 }
   130930 
   130931 /*
   130932 ** Rtree virtual table module xDestroy method.
   130933 */
   130934 static int rtreeDestroy(sqlite3_vtab *pVtab){
   130935   Rtree *pRtree = (Rtree *)pVtab;
   130936   int rc;
   130937   char *zCreate = sqlite3_mprintf(
   130938     "DROP TABLE '%q'.'%q_node';"
   130939     "DROP TABLE '%q'.'%q_rowid';"
   130940     "DROP TABLE '%q'.'%q_parent';",
   130941     pRtree->zDb, pRtree->zName,
   130942     pRtree->zDb, pRtree->zName,
   130943     pRtree->zDb, pRtree->zName
   130944   );
   130945   if( !zCreate ){
   130946     rc = SQLITE_NOMEM;
   130947   }else{
   130948     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   130949     sqlite3_free(zCreate);
   130950   }
   130951   if( rc==SQLITE_OK ){
   130952     rtreeRelease(pRtree);
   130953   }
   130954 
   130955   return rc;
   130956 }
   130957 
   130958 /*
   130959 ** Rtree virtual table module xOpen method.
   130960 */
   130961 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   130962   int rc = SQLITE_NOMEM;
   130963   RtreeCursor *pCsr;
   130964 
   130965   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   130966   if( pCsr ){
   130967     memset(pCsr, 0, sizeof(RtreeCursor));
   130968     pCsr->base.pVtab = pVTab;
   130969     rc = SQLITE_OK;
   130970   }
   130971   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   130972 
   130973   return rc;
   130974 }
   130975 
   130976 
   130977 /*
   130978 ** Free the RtreeCursor.aConstraint[] array and its contents.
   130979 */
   130980 static void freeCursorConstraints(RtreeCursor *pCsr){
   130981   if( pCsr->aConstraint ){
   130982     int i;                        /* Used to iterate through constraint array */
   130983     for(i=0; i<pCsr->nConstraint; i++){
   130984       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
   130985       if( pGeom ){
   130986         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
   130987         sqlite3_free(pGeom);
   130988       }
   130989     }
   130990     sqlite3_free(pCsr->aConstraint);
   130991     pCsr->aConstraint = 0;
   130992   }
   130993 }
   130994 
   130995 /*
   130996 ** Rtree virtual table module xClose method.
   130997 */
   130998 static int rtreeClose(sqlite3_vtab_cursor *cur){
   130999   Rtree *pRtree = (Rtree *)(cur->pVtab);
   131000   int rc;
   131001   RtreeCursor *pCsr = (RtreeCursor *)cur;
   131002   freeCursorConstraints(pCsr);
   131003   rc = nodeRelease(pRtree, pCsr->pNode);
   131004   sqlite3_free(pCsr);
   131005   return rc;
   131006 }
   131007 
   131008 /*
   131009 ** Rtree virtual table module xEof method.
   131010 **
   131011 ** Return non-zero if the cursor does not currently point to a valid
   131012 ** record (i.e if the scan has finished), or zero otherwise.
   131013 */
   131014 static int rtreeEof(sqlite3_vtab_cursor *cur){
   131015   RtreeCursor *pCsr = (RtreeCursor *)cur;
   131016   return (pCsr->pNode==0);
   131017 }
   131018 
   131019 /*
   131020 ** The r-tree constraint passed as the second argument to this function is
   131021 ** guaranteed to be a MATCH constraint.
   131022 */
   131023 static int testRtreeGeom(
   131024   Rtree *pRtree,                  /* R-Tree object */
   131025   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
   131026   RtreeCell *pCell,               /* Cell to test */
   131027   int *pbRes                      /* OUT: Test result */
   131028 ){
   131029   int i;
   131030   double aCoord[RTREE_MAX_DIMENSIONS*2];
   131031   int nCoord = pRtree->nDim*2;
   131032 
   131033   assert( pConstraint->op==RTREE_MATCH );
   131034   assert( pConstraint->pGeom );
   131035 
   131036   for(i=0; i<nCoord; i++){
   131037     aCoord[i] = DCOORD(pCell->aCoord[i]);
   131038   }
   131039   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
   131040 }
   131041 
   131042 /*
   131043 ** Cursor pCursor currently points to a cell in a non-leaf page.
   131044 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
   131045 ** (excluded) by the constraints in the pCursor->aConstraint[]
   131046 ** array, or false otherwise.
   131047 **
   131048 ** Return SQLITE_OK if successful or an SQLite error code if an error
   131049 ** occurs within a geometry callback.
   131050 */
   131051 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   131052   RtreeCell cell;
   131053   int ii;
   131054   int bRes = 0;
   131055   int rc = SQLITE_OK;
   131056 
   131057   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   131058   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
   131059     RtreeConstraint *p = &pCursor->aConstraint[ii];
   131060     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
   131061     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
   131062 
   131063     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   131064         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   131065     );
   131066 
   131067     switch( p->op ){
   131068       case RTREE_LE: case RTREE_LT:
   131069         bRes = p->rValue<cell_min;
   131070         break;
   131071 
   131072       case RTREE_GE: case RTREE_GT:
   131073         bRes = p->rValue>cell_max;
   131074         break;
   131075 
   131076       case RTREE_EQ:
   131077         bRes = (p->rValue>cell_max || p->rValue<cell_min);
   131078         break;
   131079 
   131080       default: {
   131081         assert( p->op==RTREE_MATCH );
   131082         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
   131083         bRes = !bRes;
   131084         break;
   131085       }
   131086     }
   131087   }
   131088 
   131089   *pbEof = bRes;
   131090   return rc;
   131091 }
   131092 
   131093 /*
   131094 ** Test if the cell that cursor pCursor currently points to
   131095 ** would be filtered (excluded) by the constraints in the
   131096 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
   131097 ** returning. If the cell is not filtered (excluded) by the constraints,
   131098 ** set pbEof to zero.
   131099 **
   131100 ** Return SQLITE_OK if successful or an SQLite error code if an error
   131101 ** occurs within a geometry callback.
   131102 **
   131103 ** This function assumes that the cell is part of a leaf node.
   131104 */
   131105 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   131106   RtreeCell cell;
   131107   int ii;
   131108   *pbEof = 0;
   131109 
   131110   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   131111   for(ii=0; ii<pCursor->nConstraint; ii++){
   131112     RtreeConstraint *p = &pCursor->aConstraint[ii];
   131113     double coord = DCOORD(cell.aCoord[p->iCoord]);
   131114     int res;
   131115     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   131116         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   131117     );
   131118     switch( p->op ){
   131119       case RTREE_LE: res = (coord<=p->rValue); break;
   131120       case RTREE_LT: res = (coord<p->rValue);  break;
   131121       case RTREE_GE: res = (coord>=p->rValue); break;
   131122       case RTREE_GT: res = (coord>p->rValue);  break;
   131123       case RTREE_EQ: res = (coord==p->rValue); break;
   131124       default: {
   131125         int rc;
   131126         assert( p->op==RTREE_MATCH );
   131127         rc = testRtreeGeom(pRtree, p, &cell, &res);
   131128         if( rc!=SQLITE_OK ){
   131129           return rc;
   131130         }
   131131         break;
   131132       }
   131133     }
   131134 
   131135     if( !res ){
   131136       *pbEof = 1;
   131137       return SQLITE_OK;
   131138     }
   131139   }
   131140 
   131141   return SQLITE_OK;
   131142 }
   131143 
   131144 /*
   131145 ** Cursor pCursor currently points at a node that heads a sub-tree of
   131146 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
   131147 ** to point to the left-most cell of the sub-tree that matches the
   131148 ** configured constraints.
   131149 */
   131150 static int descendToCell(
   131151   Rtree *pRtree,
   131152   RtreeCursor *pCursor,
   131153   int iHeight,
   131154   int *pEof                 /* OUT: Set to true if cannot descend */
   131155 ){
   131156   int isEof;
   131157   int rc;
   131158   int ii;
   131159   RtreeNode *pChild;
   131160   sqlite3_int64 iRowid;
   131161 
   131162   RtreeNode *pSavedNode = pCursor->pNode;
   131163   int iSavedCell = pCursor->iCell;
   131164 
   131165   assert( iHeight>=0 );
   131166 
   131167   if( iHeight==0 ){
   131168     rc = testRtreeEntry(pRtree, pCursor, &isEof);
   131169   }else{
   131170     rc = testRtreeCell(pRtree, pCursor, &isEof);
   131171   }
   131172   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
   131173     goto descend_to_cell_out;
   131174   }
   131175 
   131176   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
   131177   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
   131178   if( rc!=SQLITE_OK ){
   131179     goto descend_to_cell_out;
   131180   }
   131181 
   131182   nodeRelease(pRtree, pCursor->pNode);
   131183   pCursor->pNode = pChild;
   131184   isEof = 1;
   131185   for(ii=0; isEof && ii<NCELL(pChild); ii++){
   131186     pCursor->iCell = ii;
   131187     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
   131188     if( rc!=SQLITE_OK ){
   131189       goto descend_to_cell_out;
   131190     }
   131191   }
   131192 
   131193   if( isEof ){
   131194     assert( pCursor->pNode==pChild );
   131195     nodeReference(pSavedNode);
   131196     nodeRelease(pRtree, pChild);
   131197     pCursor->pNode = pSavedNode;
   131198     pCursor->iCell = iSavedCell;
   131199   }
   131200 
   131201 descend_to_cell_out:
   131202   *pEof = isEof;
   131203   return rc;
   131204 }
   131205 
   131206 /*
   131207 ** One of the cells in node pNode is guaranteed to have a 64-bit
   131208 ** integer value equal to iRowid. Return the index of this cell.
   131209 */
   131210 static int nodeRowidIndex(
   131211   Rtree *pRtree,
   131212   RtreeNode *pNode,
   131213   i64 iRowid,
   131214   int *piIndex
   131215 ){
   131216   int ii;
   131217   int nCell = NCELL(pNode);
   131218   for(ii=0; ii<nCell; ii++){
   131219     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   131220       *piIndex = ii;
   131221       return SQLITE_OK;
   131222     }
   131223   }
   131224   return SQLITE_CORRUPT_VTAB;
   131225 }
   131226 
   131227 /*
   131228 ** Return the index of the cell containing a pointer to node pNode
   131229 ** in its parent. If pNode is the root node, return -1.
   131230 */
   131231 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   131232   RtreeNode *pParent = pNode->pParent;
   131233   if( pParent ){
   131234     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   131235   }
   131236   *piIndex = -1;
   131237   return SQLITE_OK;
   131238 }
   131239 
   131240 /*
   131241 ** Rtree virtual table module xNext method.
   131242 */
   131243 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   131244   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
   131245   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131246   int rc = SQLITE_OK;
   131247 
   131248   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
   131249   ** already at EOF. It is against the rules to call the xNext() method of
   131250   ** a cursor that has already reached EOF.
   131251   */
   131252   assert( pCsr->pNode );
   131253 
   131254   if( pCsr->iStrategy==1 ){
   131255     /* This "scan" is a direct lookup by rowid. There is no next entry. */
   131256     nodeRelease(pRtree, pCsr->pNode);
   131257     pCsr->pNode = 0;
   131258   }else{
   131259     /* Move to the next entry that matches the configured constraints. */
   131260     int iHeight = 0;
   131261     while( pCsr->pNode ){
   131262       RtreeNode *pNode = pCsr->pNode;
   131263       int nCell = NCELL(pNode);
   131264       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
   131265         int isEof;
   131266         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
   131267         if( rc!=SQLITE_OK || !isEof ){
   131268           return rc;
   131269         }
   131270       }
   131271       pCsr->pNode = pNode->pParent;
   131272       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
   131273       if( rc!=SQLITE_OK ){
   131274         return rc;
   131275       }
   131276       nodeReference(pCsr->pNode);
   131277       nodeRelease(pRtree, pNode);
   131278       iHeight++;
   131279     }
   131280   }
   131281 
   131282   return rc;
   131283 }
   131284 
   131285 /*
   131286 ** Rtree virtual table module xRowid method.
   131287 */
   131288 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   131289   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   131290   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131291 
   131292   assert(pCsr->pNode);
   131293   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   131294 
   131295   return SQLITE_OK;
   131296 }
   131297 
   131298 /*
   131299 ** Rtree virtual table module xColumn method.
   131300 */
   131301 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   131302   Rtree *pRtree = (Rtree *)cur->pVtab;
   131303   RtreeCursor *pCsr = (RtreeCursor *)cur;
   131304 
   131305   if( i==0 ){
   131306     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   131307     sqlite3_result_int64(ctx, iRowid);
   131308   }else{
   131309     RtreeCoord c;
   131310     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
   131311     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   131312       sqlite3_result_double(ctx, c.f);
   131313     }else{
   131314       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   131315       sqlite3_result_int(ctx, c.i);
   131316     }
   131317   }
   131318 
   131319   return SQLITE_OK;
   131320 }
   131321 
   131322 /*
   131323 ** Use nodeAcquire() to obtain the leaf node containing the record with
   131324 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   131325 ** return SQLITE_OK. If there is no such record in the table, set
   131326 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   131327 ** to zero and return an SQLite error code.
   131328 */
   131329 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
   131330   int rc;
   131331   *ppLeaf = 0;
   131332   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   131333   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   131334     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   131335     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   131336     sqlite3_reset(pRtree->pReadRowid);
   131337   }else{
   131338     rc = sqlite3_reset(pRtree->pReadRowid);
   131339   }
   131340   return rc;
   131341 }
   131342 
   131343 /*
   131344 ** This function is called to configure the RtreeConstraint object passed
   131345 ** as the second argument for a MATCH constraint. The value passed as the
   131346 ** first argument to this function is the right-hand operand to the MATCH
   131347 ** operator.
   131348 */
   131349 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   131350   RtreeMatchArg *p;
   131351   sqlite3_rtree_geometry *pGeom;
   131352   int nBlob;
   131353 
   131354   /* Check that value is actually a blob. */
   131355   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
   131356 
   131357   /* Check that the blob is roughly the right size. */
   131358   nBlob = sqlite3_value_bytes(pValue);
   131359   if( nBlob<(int)sizeof(RtreeMatchArg)
   131360    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
   131361   ){
   131362     return SQLITE_ERROR;
   131363   }
   131364 
   131365   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
   131366       sizeof(sqlite3_rtree_geometry) + nBlob
   131367   );
   131368   if( !pGeom ) return SQLITE_NOMEM;
   131369   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
   131370   p = (RtreeMatchArg *)&pGeom[1];
   131371 
   131372   memcpy(p, sqlite3_value_blob(pValue), nBlob);
   131373   if( p->magic!=RTREE_GEOMETRY_MAGIC
   131374    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
   131375   ){
   131376     sqlite3_free(pGeom);
   131377     return SQLITE_ERROR;
   131378   }
   131379 
   131380   pGeom->pContext = p->pContext;
   131381   pGeom->nParam = p->nParam;
   131382   pGeom->aParam = p->aParam;
   131383 
   131384   pCons->xGeom = p->xGeom;
   131385   pCons->pGeom = pGeom;
   131386   return SQLITE_OK;
   131387 }
   131388 
   131389 /*
   131390 ** Rtree virtual table module xFilter method.
   131391 */
   131392 static int rtreeFilter(
   131393   sqlite3_vtab_cursor *pVtabCursor,
   131394   int idxNum, const char *idxStr,
   131395   int argc, sqlite3_value **argv
   131396 ){
   131397   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   131398   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131399 
   131400   RtreeNode *pRoot = 0;
   131401   int ii;
   131402   int rc = SQLITE_OK;
   131403 
   131404   rtreeReference(pRtree);
   131405 
   131406   freeCursorConstraints(pCsr);
   131407   pCsr->iStrategy = idxNum;
   131408 
   131409   if( idxNum==1 ){
   131410     /* Special case - lookup by rowid. */
   131411     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   131412     i64 iRowid = sqlite3_value_int64(argv[0]);
   131413     rc = findLeafNode(pRtree, iRowid, &pLeaf);
   131414     pCsr->pNode = pLeaf;
   131415     if( pLeaf ){
   131416       assert( rc==SQLITE_OK );
   131417       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
   131418     }
   131419   }else{
   131420     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   131421     ** with the configured constraints.
   131422     */
   131423     if( argc>0 ){
   131424       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   131425       pCsr->nConstraint = argc;
   131426       if( !pCsr->aConstraint ){
   131427         rc = SQLITE_NOMEM;
   131428       }else{
   131429         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   131430         assert( (idxStr==0 && argc==0)
   131431                 || (idxStr && (int)strlen(idxStr)==argc*2) );
   131432         for(ii=0; ii<argc; ii++){
   131433           RtreeConstraint *p = &pCsr->aConstraint[ii];
   131434           p->op = idxStr[ii*2];
   131435           p->iCoord = idxStr[ii*2+1]-'a';
   131436           if( p->op==RTREE_MATCH ){
   131437             /* A MATCH operator. The right-hand-side must be a blob that
   131438             ** can be cast into an RtreeMatchArg object. One created using
   131439             ** an sqlite3_rtree_geometry_callback() SQL user function.
   131440             */
   131441             rc = deserializeGeometry(argv[ii], p);
   131442             if( rc!=SQLITE_OK ){
   131443               break;
   131444             }
   131445           }else{
   131446             p->rValue = sqlite3_value_double(argv[ii]);
   131447           }
   131448         }
   131449       }
   131450     }
   131451 
   131452     if( rc==SQLITE_OK ){
   131453       pCsr->pNode = 0;
   131454       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   131455     }
   131456     if( rc==SQLITE_OK ){
   131457       int isEof = 1;
   131458       int nCell = NCELL(pRoot);
   131459       pCsr->pNode = pRoot;
   131460       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
   131461         assert( pCsr->pNode==pRoot );
   131462         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
   131463         if( !isEof ){
   131464           break;
   131465         }
   131466       }
   131467       if( rc==SQLITE_OK && isEof ){
   131468         assert( pCsr->pNode==pRoot );
   131469         nodeRelease(pRtree, pRoot);
   131470         pCsr->pNode = 0;
   131471       }
   131472       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
   131473     }
   131474   }
   131475 
   131476   rtreeRelease(pRtree);
   131477   return rc;
   131478 }
   131479 
   131480 /*
   131481 ** Rtree virtual table module xBestIndex method. There are three
   131482 ** table scan strategies to choose from (in order from most to
   131483 ** least desirable):
   131484 **
   131485 **   idxNum     idxStr        Strategy
   131486 **   ------------------------------------------------
   131487 **     1        Unused        Direct lookup by rowid.
   131488 **     2        See below     R-tree query or full-table scan.
   131489 **   ------------------------------------------------
   131490 **
   131491 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   131492 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   131493 ** constraint used. The first two bytes of idxStr correspond to
   131494 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   131495 ** (argvIndex==1) etc.
   131496 **
   131497 ** The first of each pair of bytes in idxStr identifies the constraint
   131498 ** operator as follows:
   131499 **
   131500 **   Operator    Byte Value
   131501 **   ----------------------
   131502 **      =        0x41 ('A')
   131503 **     <=        0x42 ('B')
   131504 **      <        0x43 ('C')
   131505 **     >=        0x44 ('D')
   131506 **      >        0x45 ('E')
   131507 **   MATCH       0x46 ('F')
   131508 **   ----------------------
   131509 **
   131510 ** The second of each pair of bytes identifies the coordinate column
   131511 ** to which the constraint applies. The leftmost coordinate column
   131512 ** is 'a', the second from the left 'b' etc.
   131513 */
   131514 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   131515   int rc = SQLITE_OK;
   131516   int ii;
   131517 
   131518   int iIdx = 0;
   131519   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   131520   memset(zIdxStr, 0, sizeof(zIdxStr));
   131521   UNUSED_PARAMETER(tab);
   131522 
   131523   assert( pIdxInfo->idxStr==0 );
   131524   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
   131525     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   131526 
   131527     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   131528       /* We have an equality constraint on the rowid. Use strategy 1. */
   131529       int jj;
   131530       for(jj=0; jj<ii; jj++){
   131531         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   131532         pIdxInfo->aConstraintUsage[jj].omit = 0;
   131533       }
   131534       pIdxInfo->idxNum = 1;
   131535       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   131536       pIdxInfo->aConstraintUsage[jj].omit = 1;
   131537 
   131538       /* This strategy involves a two rowid lookups on an B-Tree structures
   131539       ** and then a linear search of an R-Tree node. This should be
   131540       ** considered almost as quick as a direct rowid lookup (for which
   131541       ** sqlite uses an internal cost of 0.0).
   131542       */
   131543       pIdxInfo->estimatedCost = 10.0;
   131544       return SQLITE_OK;
   131545     }
   131546 
   131547     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   131548       u8 op;
   131549       switch( p->op ){
   131550         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   131551         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   131552         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   131553         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   131554         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   131555         default:
   131556           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   131557           op = RTREE_MATCH;
   131558           break;
   131559       }
   131560       zIdxStr[iIdx++] = op;
   131561       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
   131562       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   131563       pIdxInfo->aConstraintUsage[ii].omit = 1;
   131564     }
   131565   }
   131566 
   131567   pIdxInfo->idxNum = 2;
   131568   pIdxInfo->needToFreeIdxStr = 1;
   131569   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   131570     return SQLITE_NOMEM;
   131571   }
   131572   assert( iIdx>=0 );
   131573   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
   131574   return rc;
   131575 }
   131576 
   131577 /*
   131578 ** Return the N-dimensional volumn of the cell stored in *p.
   131579 */
   131580 static float cellArea(Rtree *pRtree, RtreeCell *p){
   131581   float area = 1.0;
   131582   int ii;
   131583   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131584     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
   131585   }
   131586   return area;
   131587 }
   131588 
   131589 /*
   131590 ** Return the margin length of cell p. The margin length is the sum
   131591 ** of the objects size in each dimension.
   131592 */
   131593 static float cellMargin(Rtree *pRtree, RtreeCell *p){
   131594   float margin = 0.0;
   131595   int ii;
   131596   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131597     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   131598   }
   131599   return margin;
   131600 }
   131601 
   131602 /*
   131603 ** Store the union of cells p1 and p2 in p1.
   131604 */
   131605 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   131606   int ii;
   131607   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   131608     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131609       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   131610       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   131611     }
   131612   }else{
   131613     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131614       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   131615       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   131616     }
   131617   }
   131618 }
   131619 
   131620 /*
   131621 ** Return true if the area covered by p2 is a subset of the area covered
   131622 ** by p1. False otherwise.
   131623 */
   131624 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   131625   int ii;
   131626   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   131627   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131628     RtreeCoord *a1 = &p1->aCoord[ii];
   131629     RtreeCoord *a2 = &p2->aCoord[ii];
   131630     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   131631      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   131632     ){
   131633       return 0;
   131634     }
   131635   }
   131636   return 1;
   131637 }
   131638 
   131639 /*
   131640 ** Return the amount cell p would grow by if it were unioned with pCell.
   131641 */
   131642 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   131643   float area;
   131644   RtreeCell cell;
   131645   memcpy(&cell, p, sizeof(RtreeCell));
   131646   area = cellArea(pRtree, &cell);
   131647   cellUnion(pRtree, &cell, pCell);
   131648   return (cellArea(pRtree, &cell)-area);
   131649 }
   131650 
   131651 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
   131652 static float cellOverlap(
   131653   Rtree *pRtree,
   131654   RtreeCell *p,
   131655   RtreeCell *aCell,
   131656   int nCell,
   131657   int iExclude
   131658 ){
   131659   int ii;
   131660   float overlap = 0.0;
   131661   for(ii=0; ii<nCell; ii++){
   131662 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131663     if( ii!=iExclude )
   131664 #else
   131665     assert( iExclude==-1 );
   131666     UNUSED_PARAMETER(iExclude);
   131667 #endif
   131668     {
   131669       int jj;
   131670       float o = 1.0;
   131671       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   131672         double x1;
   131673         double x2;
   131674 
   131675         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   131676         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   131677 
   131678         if( x2<x1 ){
   131679           o = 0.0;
   131680           break;
   131681         }else{
   131682           o = o * (float)(x2-x1);
   131683         }
   131684       }
   131685       overlap += o;
   131686     }
   131687   }
   131688   return overlap;
   131689 }
   131690 #endif
   131691 
   131692 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131693 static float cellOverlapEnlargement(
   131694   Rtree *pRtree,
   131695   RtreeCell *p,
   131696   RtreeCell *pInsert,
   131697   RtreeCell *aCell,
   131698   int nCell,
   131699   int iExclude
   131700 ){
   131701   double before;
   131702   double after;
   131703   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   131704   cellUnion(pRtree, p, pInsert);
   131705   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   131706   return (float)(after-before);
   131707 }
   131708 #endif
   131709 
   131710 
   131711 /*
   131712 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   131713 ** ChooseSubTree in r*tree terminology.
   131714 */
   131715 static int ChooseLeaf(
   131716   Rtree *pRtree,               /* Rtree table */
   131717   RtreeCell *pCell,            /* Cell to insert into rtree */
   131718   int iHeight,                 /* Height of sub-tree rooted at pCell */
   131719   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   131720 ){
   131721   int rc;
   131722   int ii;
   131723   RtreeNode *pNode;
   131724   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   131725 
   131726   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   131727     int iCell;
   131728     sqlite3_int64 iBest = 0;
   131729 
   131730     float fMinGrowth = 0.0;
   131731     float fMinArea = 0.0;
   131732 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131733     float fMinOverlap = 0.0;
   131734     float overlap;
   131735 #endif
   131736 
   131737     int nCell = NCELL(pNode);
   131738     RtreeCell cell;
   131739     RtreeNode *pChild;
   131740 
   131741     RtreeCell *aCell = 0;
   131742 
   131743 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131744     if( ii==(pRtree->iDepth-1) ){
   131745       int jj;
   131746       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
   131747       if( !aCell ){
   131748         rc = SQLITE_NOMEM;
   131749         nodeRelease(pRtree, pNode);
   131750         pNode = 0;
   131751         continue;
   131752       }
   131753       for(jj=0; jj<nCell; jj++){
   131754         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
   131755       }
   131756     }
   131757 #endif
   131758 
   131759     /* Select the child node which will be enlarged the least if pCell
   131760     ** is inserted into it. Resolve ties by choosing the entry with
   131761     ** the smallest area.
   131762     */
   131763     for(iCell=0; iCell<nCell; iCell++){
   131764       int bBest = 0;
   131765       float growth;
   131766       float area;
   131767       nodeGetCell(pRtree, pNode, iCell, &cell);
   131768       growth = cellGrowth(pRtree, &cell, pCell);
   131769       area = cellArea(pRtree, &cell);
   131770 
   131771 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131772       if( ii==(pRtree->iDepth-1) ){
   131773         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
   131774       }else{
   131775         overlap = 0.0;
   131776       }
   131777       if( (iCell==0)
   131778        || (overlap<fMinOverlap)
   131779        || (overlap==fMinOverlap && growth<fMinGrowth)
   131780        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
   131781       ){
   131782         bBest = 1;
   131783         fMinOverlap = overlap;
   131784       }
   131785 #else
   131786       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   131787         bBest = 1;
   131788       }
   131789 #endif
   131790       if( bBest ){
   131791         fMinGrowth = growth;
   131792         fMinArea = area;
   131793         iBest = cell.iRowid;
   131794       }
   131795     }
   131796 
   131797     sqlite3_free(aCell);
   131798     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   131799     nodeRelease(pRtree, pNode);
   131800     pNode = pChild;
   131801   }
   131802 
   131803   *ppLeaf = pNode;
   131804   return rc;
   131805 }
   131806 
   131807 /*
   131808 ** A cell with the same content as pCell has just been inserted into
   131809 ** the node pNode. This function updates the bounding box cells in
   131810 ** all ancestor elements.
   131811 */
   131812 static int AdjustTree(
   131813   Rtree *pRtree,                    /* Rtree table */
   131814   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   131815   RtreeCell *pCell                  /* This cell was just inserted */
   131816 ){
   131817   RtreeNode *p = pNode;
   131818   while( p->pParent ){
   131819     RtreeNode *pParent = p->pParent;
   131820     RtreeCell cell;
   131821     int iCell;
   131822 
   131823     if( nodeParentIndex(pRtree, p, &iCell) ){
   131824       return SQLITE_CORRUPT_VTAB;
   131825     }
   131826 
   131827     nodeGetCell(pRtree, pParent, iCell, &cell);
   131828     if( !cellContains(pRtree, &cell, pCell) ){
   131829       cellUnion(pRtree, &cell, pCell);
   131830       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   131831     }
   131832 
   131833     p = pParent;
   131834   }
   131835   return SQLITE_OK;
   131836 }
   131837 
   131838 /*
   131839 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   131840 */
   131841 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   131842   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   131843   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   131844   sqlite3_step(pRtree->pWriteRowid);
   131845   return sqlite3_reset(pRtree->pWriteRowid);
   131846 }
   131847 
   131848 /*
   131849 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   131850 */
   131851 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   131852   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   131853   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   131854   sqlite3_step(pRtree->pWriteParent);
   131855   return sqlite3_reset(pRtree->pWriteParent);
   131856 }
   131857 
   131858 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   131859 
   131860 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   131861 /*
   131862 ** Implementation of the linear variant of the PickNext() function from
   131863 ** Guttman[84].
   131864 */
   131865 static RtreeCell *LinearPickNext(
   131866   Rtree *pRtree,
   131867   RtreeCell *aCell,
   131868   int nCell,
   131869   RtreeCell *pLeftBox,
   131870   RtreeCell *pRightBox,
   131871   int *aiUsed
   131872 ){
   131873   int ii;
   131874   for(ii=0; aiUsed[ii]; ii++);
   131875   aiUsed[ii] = 1;
   131876   return &aCell[ii];
   131877 }
   131878 
   131879 /*
   131880 ** Implementation of the linear variant of the PickSeeds() function from
   131881 ** Guttman[84].
   131882 */
   131883 static void LinearPickSeeds(
   131884   Rtree *pRtree,
   131885   RtreeCell *aCell,
   131886   int nCell,
   131887   int *piLeftSeed,
   131888   int *piRightSeed
   131889 ){
   131890   int i;
   131891   int iLeftSeed = 0;
   131892   int iRightSeed = 1;
   131893   float maxNormalInnerWidth = 0.0;
   131894 
   131895   /* Pick two "seed" cells from the array of cells. The algorithm used
   131896   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
   131897   ** indices of the two seed cells in the array are stored in local
   131898   ** variables iLeftSeek and iRightSeed.
   131899   */
   131900   for(i=0; i<pRtree->nDim; i++){
   131901     float x1 = DCOORD(aCell[0].aCoord[i*2]);
   131902     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
   131903     float x3 = x1;
   131904     float x4 = x2;
   131905     int jj;
   131906 
   131907     int iCellLeft = 0;
   131908     int iCellRight = 0;
   131909 
   131910     for(jj=1; jj<nCell; jj++){
   131911       float left = DCOORD(aCell[jj].aCoord[i*2]);
   131912       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
   131913 
   131914       if( left<x1 ) x1 = left;
   131915       if( right>x4 ) x4 = right;
   131916       if( left>x3 ){
   131917         x3 = left;
   131918         iCellRight = jj;
   131919       }
   131920       if( right<x2 ){
   131921         x2 = right;
   131922         iCellLeft = jj;
   131923       }
   131924     }
   131925 
   131926     if( x4!=x1 ){
   131927       float normalwidth = (x3 - x2) / (x4 - x1);
   131928       if( normalwidth>maxNormalInnerWidth ){
   131929         iLeftSeed = iCellLeft;
   131930         iRightSeed = iCellRight;
   131931       }
   131932     }
   131933   }
   131934 
   131935   *piLeftSeed = iLeftSeed;
   131936   *piRightSeed = iRightSeed;
   131937 }
   131938 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
   131939 
   131940 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   131941 /*
   131942 ** Implementation of the quadratic variant of the PickNext() function from
   131943 ** Guttman[84].
   131944 */
   131945 static RtreeCell *QuadraticPickNext(
   131946   Rtree *pRtree,
   131947   RtreeCell *aCell,
   131948   int nCell,
   131949   RtreeCell *pLeftBox,
   131950   RtreeCell *pRightBox,
   131951   int *aiUsed
   131952 ){
   131953   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
   131954 
   131955   int iSelect = -1;
   131956   float fDiff;
   131957   int ii;
   131958   for(ii=0; ii<nCell; ii++){
   131959     if( aiUsed[ii]==0 ){
   131960       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   131961       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   131962       float diff = FABS(right-left);
   131963       if( iSelect<0 || diff>fDiff ){
   131964         fDiff = diff;
   131965         iSelect = ii;
   131966       }
   131967     }
   131968   }
   131969   aiUsed[iSelect] = 1;
   131970   return &aCell[iSelect];
   131971 }
   131972 
   131973 /*
   131974 ** Implementation of the quadratic variant of the PickSeeds() function from
   131975 ** Guttman[84].
   131976 */
   131977 static void QuadraticPickSeeds(
   131978   Rtree *pRtree,
   131979   RtreeCell *aCell,
   131980   int nCell,
   131981   int *piLeftSeed,
   131982   int *piRightSeed
   131983 ){
   131984   int ii;
   131985   int jj;
   131986 
   131987   int iLeftSeed = 0;
   131988   int iRightSeed = 1;
   131989   float fWaste = 0.0;
   131990 
   131991   for(ii=0; ii<nCell; ii++){
   131992     for(jj=ii+1; jj<nCell; jj++){
   131993       float right = cellArea(pRtree, &aCell[jj]);
   131994       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
   131995       float waste = growth - right;
   131996 
   131997       if( waste>fWaste ){
   131998         iLeftSeed = ii;
   131999         iRightSeed = jj;
   132000         fWaste = waste;
   132001       }
   132002     }
   132003   }
   132004 
   132005   *piLeftSeed = iLeftSeed;
   132006   *piRightSeed = iRightSeed;
   132007 }
   132008 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
   132009 
   132010 /*
   132011 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   132012 ** nIdx. The aIdx array contains the set of integers from 0 to
   132013 ** (nIdx-1) in no particular order. This function sorts the values
   132014 ** in aIdx according to the indexed values in aDistance. For
   132015 ** example, assuming the inputs:
   132016 **
   132017 **   aIdx      = { 0,   1,   2,   3 }
   132018 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   132019 **
   132020 ** this function sets the aIdx array to contain:
   132021 **
   132022 **   aIdx      = { 0,   1,   2,   3 }
   132023 **
   132024 ** The aSpare array is used as temporary working space by the
   132025 ** sorting algorithm.
   132026 */
   132027 static void SortByDistance(
   132028   int *aIdx,
   132029   int nIdx,
   132030   float *aDistance,
   132031   int *aSpare
   132032 ){
   132033   if( nIdx>1 ){
   132034     int iLeft = 0;
   132035     int iRight = 0;
   132036 
   132037     int nLeft = nIdx/2;
   132038     int nRight = nIdx-nLeft;
   132039     int *aLeft = aIdx;
   132040     int *aRight = &aIdx[nLeft];
   132041 
   132042     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   132043     SortByDistance(aRight, nRight, aDistance, aSpare);
   132044 
   132045     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   132046     aLeft = aSpare;
   132047 
   132048     while( iLeft<nLeft || iRight<nRight ){
   132049       if( iLeft==nLeft ){
   132050         aIdx[iLeft+iRight] = aRight[iRight];
   132051         iRight++;
   132052       }else if( iRight==nRight ){
   132053         aIdx[iLeft+iRight] = aLeft[iLeft];
   132054         iLeft++;
   132055       }else{
   132056         float fLeft = aDistance[aLeft[iLeft]];
   132057         float fRight = aDistance[aRight[iRight]];
   132058         if( fLeft<fRight ){
   132059           aIdx[iLeft+iRight] = aLeft[iLeft];
   132060           iLeft++;
   132061         }else{
   132062           aIdx[iLeft+iRight] = aRight[iRight];
   132063           iRight++;
   132064         }
   132065       }
   132066     }
   132067 
   132068 #if 0
   132069     /* Check that the sort worked */
   132070     {
   132071       int jj;
   132072       for(jj=1; jj<nIdx; jj++){
   132073         float left = aDistance[aIdx[jj-1]];
   132074         float right = aDistance[aIdx[jj]];
   132075         assert( left<=right );
   132076       }
   132077     }
   132078 #endif
   132079   }
   132080 }
   132081 
   132082 /*
   132083 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   132084 ** nIdx. The aIdx array contains the set of integers from 0 to
   132085 ** (nIdx-1) in no particular order. This function sorts the values
   132086 ** in aIdx according to dimension iDim of the cells in aCell. The
   132087 ** minimum value of dimension iDim is considered first, the
   132088 ** maximum used to break ties.
   132089 **
   132090 ** The aSpare array is used as temporary working space by the
   132091 ** sorting algorithm.
   132092 */
   132093 static void SortByDimension(
   132094   Rtree *pRtree,
   132095   int *aIdx,
   132096   int nIdx,
   132097   int iDim,
   132098   RtreeCell *aCell,
   132099   int *aSpare
   132100 ){
   132101   if( nIdx>1 ){
   132102 
   132103     int iLeft = 0;
   132104     int iRight = 0;
   132105 
   132106     int nLeft = nIdx/2;
   132107     int nRight = nIdx-nLeft;
   132108     int *aLeft = aIdx;
   132109     int *aRight = &aIdx[nLeft];
   132110 
   132111     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   132112     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   132113 
   132114     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   132115     aLeft = aSpare;
   132116     while( iLeft<nLeft || iRight<nRight ){
   132117       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   132118       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   132119       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   132120       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   132121       if( (iLeft!=nLeft) && ((iRight==nRight)
   132122        || (xleft1<xright1)
   132123        || (xleft1==xright1 && xleft2<xright2)
   132124       )){
   132125         aIdx[iLeft+iRight] = aLeft[iLeft];
   132126         iLeft++;
   132127       }else{
   132128         aIdx[iLeft+iRight] = aRight[iRight];
   132129         iRight++;
   132130       }
   132131     }
   132132 
   132133 #if 0
   132134     /* Check that the sort worked */
   132135     {
   132136       int jj;
   132137       for(jj=1; jj<nIdx; jj++){
   132138         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   132139         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   132140         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   132141         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   132142         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   132143       }
   132144     }
   132145 #endif
   132146   }
   132147 }
   132148 
   132149 #if VARIANT_RSTARTREE_SPLIT
   132150 /*
   132151 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   132152 */
   132153 static int splitNodeStartree(
   132154   Rtree *pRtree,
   132155   RtreeCell *aCell,
   132156   int nCell,
   132157   RtreeNode *pLeft,
   132158   RtreeNode *pRight,
   132159   RtreeCell *pBboxLeft,
   132160   RtreeCell *pBboxRight
   132161 ){
   132162   int **aaSorted;
   132163   int *aSpare;
   132164   int ii;
   132165 
   132166   int iBestDim = 0;
   132167   int iBestSplit = 0;
   132168   float fBestMargin = 0.0;
   132169 
   132170   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   132171 
   132172   aaSorted = (int **)sqlite3_malloc(nByte);
   132173   if( !aaSorted ){
   132174     return SQLITE_NOMEM;
   132175   }
   132176 
   132177   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   132178   memset(aaSorted, 0, nByte);
   132179   for(ii=0; ii<pRtree->nDim; ii++){
   132180     int jj;
   132181     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   132182     for(jj=0; jj<nCell; jj++){
   132183       aaSorted[ii][jj] = jj;
   132184     }
   132185     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   132186   }
   132187 
   132188   for(ii=0; ii<pRtree->nDim; ii++){
   132189     float margin = 0.0;
   132190     float fBestOverlap = 0.0;
   132191     float fBestArea = 0.0;
   132192     int iBestLeft = 0;
   132193     int nLeft;
   132194 
   132195     for(
   132196       nLeft=RTREE_MINCELLS(pRtree);
   132197       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   132198       nLeft++
   132199     ){
   132200       RtreeCell left;
   132201       RtreeCell right;
   132202       int kk;
   132203       float overlap;
   132204       float area;
   132205 
   132206       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   132207       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   132208       for(kk=1; kk<(nCell-1); kk++){
   132209         if( kk<nLeft ){
   132210           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   132211         }else{
   132212           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   132213         }
   132214       }
   132215       margin += cellMargin(pRtree, &left);
   132216       margin += cellMargin(pRtree, &right);
   132217       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
   132218       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   132219       if( (nLeft==RTREE_MINCELLS(pRtree))
   132220        || (overlap<fBestOverlap)
   132221        || (overlap==fBestOverlap && area<fBestArea)
   132222       ){
   132223         iBestLeft = nLeft;
   132224         fBestOverlap = overlap;
   132225         fBestArea = area;
   132226       }
   132227     }
   132228 
   132229     if( ii==0 || margin<fBestMargin ){
   132230       iBestDim = ii;
   132231       fBestMargin = margin;
   132232       iBestSplit = iBestLeft;
   132233     }
   132234   }
   132235 
   132236   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   132237   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   132238   for(ii=0; ii<nCell; ii++){
   132239     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   132240     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   132241     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   132242     nodeInsertCell(pRtree, pTarget, pCell);
   132243     cellUnion(pRtree, pBbox, pCell);
   132244   }
   132245 
   132246   sqlite3_free(aaSorted);
   132247   return SQLITE_OK;
   132248 }
   132249 #endif
   132250 
   132251 #if VARIANT_GUTTMAN_SPLIT
   132252 /*
   132253 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
   132254 */
   132255 static int splitNodeGuttman(
   132256   Rtree *pRtree,
   132257   RtreeCell *aCell,
   132258   int nCell,
   132259   RtreeNode *pLeft,
   132260   RtreeNode *pRight,
   132261   RtreeCell *pBboxLeft,
   132262   RtreeCell *pBboxRight
   132263 ){
   132264   int iLeftSeed = 0;
   132265   int iRightSeed = 1;
   132266   int *aiUsed;
   132267   int i;
   132268 
   132269   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
   132270   if( !aiUsed ){
   132271     return SQLITE_NOMEM;
   132272   }
   132273   memset(aiUsed, 0, sizeof(int)*nCell);
   132274 
   132275   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
   132276 
   132277   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
   132278   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
   132279   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
   132280   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
   132281   aiUsed[iLeftSeed] = 1;
   132282   aiUsed[iRightSeed] = 1;
   132283 
   132284   for(i=nCell-2; i>0; i--){
   132285     RtreeCell *pNext;
   132286     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
   132287     float diff =
   132288       cellGrowth(pRtree, pBboxLeft, pNext) -
   132289       cellGrowth(pRtree, pBboxRight, pNext)
   132290     ;
   132291     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
   132292      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
   132293     ){
   132294       nodeInsertCell(pRtree, pRight, pNext);
   132295       cellUnion(pRtree, pBboxRight, pNext);
   132296     }else{
   132297       nodeInsertCell(pRtree, pLeft, pNext);
   132298       cellUnion(pRtree, pBboxLeft, pNext);
   132299     }
   132300   }
   132301 
   132302   sqlite3_free(aiUsed);
   132303   return SQLITE_OK;
   132304 }
   132305 #endif
   132306 
   132307 static int updateMapping(
   132308   Rtree *pRtree,
   132309   i64 iRowid,
   132310   RtreeNode *pNode,
   132311   int iHeight
   132312 ){
   132313   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   132314   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   132315   if( iHeight>0 ){
   132316     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   132317     if( pChild ){
   132318       nodeRelease(pRtree, pChild->pParent);
   132319       nodeReference(pNode);
   132320       pChild->pParent = pNode;
   132321     }
   132322   }
   132323   return xSetMapping(pRtree, iRowid, pNode->iNode);
   132324 }
   132325 
   132326 static int SplitNode(
   132327   Rtree *pRtree,
   132328   RtreeNode *pNode,
   132329   RtreeCell *pCell,
   132330   int iHeight
   132331 ){
   132332   int i;
   132333   int newCellIsRight = 0;
   132334 
   132335   int rc = SQLITE_OK;
   132336   int nCell = NCELL(pNode);
   132337   RtreeCell *aCell;
   132338   int *aiUsed;
   132339 
   132340   RtreeNode *pLeft = 0;
   132341   RtreeNode *pRight = 0;
   132342 
   132343   RtreeCell leftbbox;
   132344   RtreeCell rightbbox;
   132345 
   132346   /* Allocate an array and populate it with a copy of pCell and
   132347   ** all cells from node pLeft. Then zero the original node.
   132348   */
   132349   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   132350   if( !aCell ){
   132351     rc = SQLITE_NOMEM;
   132352     goto splitnode_out;
   132353   }
   132354   aiUsed = (int *)&aCell[nCell+1];
   132355   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   132356   for(i=0; i<nCell; i++){
   132357     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   132358   }
   132359   nodeZero(pRtree, pNode);
   132360   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   132361   nCell++;
   132362 
   132363   if( pNode->iNode==1 ){
   132364     pRight = nodeNew(pRtree, pNode);
   132365     pLeft = nodeNew(pRtree, pNode);
   132366     pRtree->iDepth++;
   132367     pNode->isDirty = 1;
   132368     writeInt16(pNode->zData, pRtree->iDepth);
   132369   }else{
   132370     pLeft = pNode;
   132371     pRight = nodeNew(pRtree, pLeft->pParent);
   132372     nodeReference(pLeft);
   132373   }
   132374 
   132375   if( !pLeft || !pRight ){
   132376     rc = SQLITE_NOMEM;
   132377     goto splitnode_out;
   132378   }
   132379 
   132380   memset(pLeft->zData, 0, pRtree->iNodeSize);
   132381   memset(pRight->zData, 0, pRtree->iNodeSize);
   132382 
   132383   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
   132384   if( rc!=SQLITE_OK ){
   132385     goto splitnode_out;
   132386   }
   132387 
   132388   /* Ensure both child nodes have node numbers assigned to them by calling
   132389   ** nodeWrite(). Node pRight always needs a node number, as it was created
   132390   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   132391   ** In this case avoid the all to nodeWrite().
   132392   */
   132393   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   132394    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   132395   ){
   132396     goto splitnode_out;
   132397   }
   132398 
   132399   rightbbox.iRowid = pRight->iNode;
   132400   leftbbox.iRowid = pLeft->iNode;
   132401 
   132402   if( pNode->iNode==1 ){
   132403     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   132404     if( rc!=SQLITE_OK ){
   132405       goto splitnode_out;
   132406     }
   132407   }else{
   132408     RtreeNode *pParent = pLeft->pParent;
   132409     int iCell;
   132410     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   132411     if( rc==SQLITE_OK ){
   132412       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   132413       rc = AdjustTree(pRtree, pParent, &leftbbox);
   132414     }
   132415     if( rc!=SQLITE_OK ){
   132416       goto splitnode_out;
   132417     }
   132418   }
   132419   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   132420     goto splitnode_out;
   132421   }
   132422 
   132423   for(i=0; i<NCELL(pRight); i++){
   132424     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   132425     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   132426     if( iRowid==pCell->iRowid ){
   132427       newCellIsRight = 1;
   132428     }
   132429     if( rc!=SQLITE_OK ){
   132430       goto splitnode_out;
   132431     }
   132432   }
   132433   if( pNode->iNode==1 ){
   132434     for(i=0; i<NCELL(pLeft); i++){
   132435       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   132436       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   132437       if( rc!=SQLITE_OK ){
   132438         goto splitnode_out;
   132439       }
   132440     }
   132441   }else if( newCellIsRight==0 ){
   132442     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   132443   }
   132444 
   132445   if( rc==SQLITE_OK ){
   132446     rc = nodeRelease(pRtree, pRight);
   132447     pRight = 0;
   132448   }
   132449   if( rc==SQLITE_OK ){
   132450     rc = nodeRelease(pRtree, pLeft);
   132451     pLeft = 0;
   132452   }
   132453 
   132454 splitnode_out:
   132455   nodeRelease(pRtree, pRight);
   132456   nodeRelease(pRtree, pLeft);
   132457   sqlite3_free(aCell);
   132458   return rc;
   132459 }
   132460 
   132461 /*
   132462 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   132463 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   132464 ** the pLeaf->pParent chain all the way up to the root node.
   132465 **
   132466 ** This operation is required when a row is deleted (or updated - an update
   132467 ** is implemented as a delete followed by an insert). SQLite provides the
   132468 ** rowid of the row to delete, which can be used to find the leaf on which
   132469 ** the entry resides (argument pLeaf). Once the leaf is located, this
   132470 ** function is called to determine its ancestry.
   132471 */
   132472 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   132473   int rc = SQLITE_OK;
   132474   RtreeNode *pChild = pLeaf;
   132475   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   132476     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   132477     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   132478     rc = sqlite3_step(pRtree->pReadParent);
   132479     if( rc==SQLITE_ROW ){
   132480       RtreeNode *pTest;           /* Used to test for reference loops */
   132481       i64 iNode;                  /* Node number of parent node */
   132482 
   132483       /* Before setting pChild->pParent, test that we are not creating a
   132484       ** loop of references (as we would if, say, pChild==pParent). We don't
   132485       ** want to do this as it leads to a memory leak when trying to delete
   132486       ** the referenced counted node structures.
   132487       */
   132488       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   132489       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   132490       if( !pTest ){
   132491         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   132492       }
   132493     }
   132494     rc = sqlite3_reset(pRtree->pReadParent);
   132495     if( rc==SQLITE_OK ) rc = rc2;
   132496     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
   132497     pChild = pChild->pParent;
   132498   }
   132499   return rc;
   132500 }
   132501 
   132502 static int deleteCell(Rtree *, RtreeNode *, int, int);
   132503 
   132504 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   132505   int rc;
   132506   int rc2;
   132507   RtreeNode *pParent = 0;
   132508   int iCell;
   132509 
   132510   assert( pNode->nRef==1 );
   132511 
   132512   /* Remove the entry in the parent cell. */
   132513   rc = nodeParentIndex(pRtree, pNode, &iCell);
   132514   if( rc==SQLITE_OK ){
   132515     pParent = pNode->pParent;
   132516     pNode->pParent = 0;
   132517     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   132518   }
   132519   rc2 = nodeRelease(pRtree, pParent);
   132520   if( rc==SQLITE_OK ){
   132521     rc = rc2;
   132522   }
   132523   if( rc!=SQLITE_OK ){
   132524     return rc;
   132525   }
   132526 
   132527   /* Remove the xxx_node entry. */
   132528   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   132529   sqlite3_step(pRtree->pDeleteNode);
   132530   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   132531     return rc;
   132532   }
   132533 
   132534   /* Remove the xxx_parent entry. */
   132535   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   132536   sqlite3_step(pRtree->pDeleteParent);
   132537   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   132538     return rc;
   132539   }
   132540 
   132541   /* Remove the node from the in-memory hash table and link it into
   132542   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   132543   */
   132544   nodeHashDelete(pRtree, pNode);
   132545   pNode->iNode = iHeight;
   132546   pNode->pNext = pRtree->pDeleted;
   132547   pNode->nRef++;
   132548   pRtree->pDeleted = pNode;
   132549 
   132550   return SQLITE_OK;
   132551 }
   132552 
   132553 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   132554   RtreeNode *pParent = pNode->pParent;
   132555   int rc = SQLITE_OK;
   132556   if( pParent ){
   132557     int ii;
   132558     int nCell = NCELL(pNode);
   132559     RtreeCell box;                            /* Bounding box for pNode */
   132560     nodeGetCell(pRtree, pNode, 0, &box);
   132561     for(ii=1; ii<nCell; ii++){
   132562       RtreeCell cell;
   132563       nodeGetCell(pRtree, pNode, ii, &cell);
   132564       cellUnion(pRtree, &box, &cell);
   132565     }
   132566     box.iRowid = pNode->iNode;
   132567     rc = nodeParentIndex(pRtree, pNode, &ii);
   132568     if( rc==SQLITE_OK ){
   132569       nodeOverwriteCell(pRtree, pParent, &box, ii);
   132570       rc = fixBoundingBox(pRtree, pParent);
   132571     }
   132572   }
   132573   return rc;
   132574 }
   132575 
   132576 /*
   132577 ** Delete the cell at index iCell of node pNode. After removing the
   132578 ** cell, adjust the r-tree data structure if required.
   132579 */
   132580 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   132581   RtreeNode *pParent;
   132582   int rc;
   132583 
   132584   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   132585     return rc;
   132586   }
   132587 
   132588   /* Remove the cell from the node. This call just moves bytes around
   132589   ** the in-memory node image, so it cannot fail.
   132590   */
   132591   nodeDeleteCell(pRtree, pNode, iCell);
   132592 
   132593   /* If the node is not the tree root and now has less than the minimum
   132594   ** number of cells, remove it from the tree. Otherwise, update the
   132595   ** cell in the parent node so that it tightly contains the updated
   132596   ** node.
   132597   */
   132598   pParent = pNode->pParent;
   132599   assert( pParent || pNode->iNode==1 );
   132600   if( pParent ){
   132601     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   132602       rc = removeNode(pRtree, pNode, iHeight);
   132603     }else{
   132604       rc = fixBoundingBox(pRtree, pNode);
   132605     }
   132606   }
   132607 
   132608   return rc;
   132609 }
   132610 
   132611 static int Reinsert(
   132612   Rtree *pRtree,
   132613   RtreeNode *pNode,
   132614   RtreeCell *pCell,
   132615   int iHeight
   132616 ){
   132617   int *aOrder;
   132618   int *aSpare;
   132619   RtreeCell *aCell;
   132620   float *aDistance;
   132621   int nCell;
   132622   float aCenterCoord[RTREE_MAX_DIMENSIONS];
   132623   int iDim;
   132624   int ii;
   132625   int rc = SQLITE_OK;
   132626 
   132627   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
   132628 
   132629   nCell = NCELL(pNode)+1;
   132630 
   132631   /* Allocate the buffers used by this operation. The allocation is
   132632   ** relinquished before this function returns.
   132633   */
   132634   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
   132635     sizeof(RtreeCell) +         /* aCell array */
   132636     sizeof(int)       +         /* aOrder array */
   132637     sizeof(int)       +         /* aSpare array */
   132638     sizeof(float)               /* aDistance array */
   132639   ));
   132640   if( !aCell ){
   132641     return SQLITE_NOMEM;
   132642   }
   132643   aOrder    = (int *)&aCell[nCell];
   132644   aSpare    = (int *)&aOrder[nCell];
   132645   aDistance = (float *)&aSpare[nCell];
   132646 
   132647   for(ii=0; ii<nCell; ii++){
   132648     if( ii==(nCell-1) ){
   132649       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   132650     }else{
   132651       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   132652     }
   132653     aOrder[ii] = ii;
   132654     for(iDim=0; iDim<pRtree->nDim; iDim++){
   132655       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
   132656       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
   132657     }
   132658   }
   132659   for(iDim=0; iDim<pRtree->nDim; iDim++){
   132660     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
   132661   }
   132662 
   132663   for(ii=0; ii<nCell; ii++){
   132664     aDistance[ii] = 0.0;
   132665     for(iDim=0; iDim<pRtree->nDim; iDim++){
   132666       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   132667           DCOORD(aCell[ii].aCoord[iDim*2]));
   132668       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   132669     }
   132670   }
   132671 
   132672   SortByDistance(aOrder, nCell, aDistance, aSpare);
   132673   nodeZero(pRtree, pNode);
   132674 
   132675   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   132676     RtreeCell *p = &aCell[aOrder[ii]];
   132677     nodeInsertCell(pRtree, pNode, p);
   132678     if( p->iRowid==pCell->iRowid ){
   132679       if( iHeight==0 ){
   132680         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   132681       }else{
   132682         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   132683       }
   132684     }
   132685   }
   132686   if( rc==SQLITE_OK ){
   132687     rc = fixBoundingBox(pRtree, pNode);
   132688   }
   132689   for(; rc==SQLITE_OK && ii<nCell; ii++){
   132690     /* Find a node to store this cell in. pNode->iNode currently contains
   132691     ** the height of the sub-tree headed by the cell.
   132692     */
   132693     RtreeNode *pInsert;
   132694     RtreeCell *p = &aCell[aOrder[ii]];
   132695     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   132696     if( rc==SQLITE_OK ){
   132697       int rc2;
   132698       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   132699       rc2 = nodeRelease(pRtree, pInsert);
   132700       if( rc==SQLITE_OK ){
   132701         rc = rc2;
   132702       }
   132703     }
   132704   }
   132705 
   132706   sqlite3_free(aCell);
   132707   return rc;
   132708 }
   132709 
   132710 /*
   132711 ** Insert cell pCell into node pNode. Node pNode is the head of a
   132712 ** subtree iHeight high (leaf nodes have iHeight==0).
   132713 */
   132714 static int rtreeInsertCell(
   132715   Rtree *pRtree,
   132716   RtreeNode *pNode,
   132717   RtreeCell *pCell,
   132718   int iHeight
   132719 ){
   132720   int rc = SQLITE_OK;
   132721   if( iHeight>0 ){
   132722     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   132723     if( pChild ){
   132724       nodeRelease(pRtree, pChild->pParent);
   132725       nodeReference(pNode);
   132726       pChild->pParent = pNode;
   132727     }
   132728   }
   132729   if( nodeInsertCell(pRtree, pNode, pCell) ){
   132730 #if VARIANT_RSTARTREE_REINSERT
   132731     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   132732       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   132733     }else{
   132734       pRtree->iReinsertHeight = iHeight;
   132735       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   132736     }
   132737 #else
   132738     rc = SplitNode(pRtree, pNode, pCell, iHeight);
   132739 #endif
   132740   }else{
   132741     rc = AdjustTree(pRtree, pNode, pCell);
   132742     if( rc==SQLITE_OK ){
   132743       if( iHeight==0 ){
   132744         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   132745       }else{
   132746         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   132747       }
   132748     }
   132749   }
   132750   return rc;
   132751 }
   132752 
   132753 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   132754   int ii;
   132755   int rc = SQLITE_OK;
   132756   int nCell = NCELL(pNode);
   132757 
   132758   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   132759     RtreeNode *pInsert;
   132760     RtreeCell cell;
   132761     nodeGetCell(pRtree, pNode, ii, &cell);
   132762 
   132763     /* Find a node to store this cell in. pNode->iNode currently contains
   132764     ** the height of the sub-tree headed by the cell.
   132765     */
   132766     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
   132767     if( rc==SQLITE_OK ){
   132768       int rc2;
   132769       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
   132770       rc2 = nodeRelease(pRtree, pInsert);
   132771       if( rc==SQLITE_OK ){
   132772         rc = rc2;
   132773       }
   132774     }
   132775   }
   132776   return rc;
   132777 }
   132778 
   132779 /*
   132780 ** Select a currently unused rowid for a new r-tree record.
   132781 */
   132782 static int newRowid(Rtree *pRtree, i64 *piRowid){
   132783   int rc;
   132784   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   132785   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   132786   sqlite3_step(pRtree->pWriteRowid);
   132787   rc = sqlite3_reset(pRtree->pWriteRowid);
   132788   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   132789   return rc;
   132790 }
   132791 
   132792 /*
   132793 ** Remove the entry with rowid=iDelete from the r-tree structure.
   132794 */
   132795 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   132796   int rc;                         /* Return code */
   132797   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
   132798   int iCell;                      /* Index of iDelete cell in pLeaf */
   132799   RtreeNode *pRoot;               /* Root node of rtree structure */
   132800 
   132801 
   132802   /* Obtain a reference to the root node to initialise Rtree.iDepth */
   132803   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   132804 
   132805   /* Obtain a reference to the leaf node that contains the entry
   132806   ** about to be deleted.
   132807   */
   132808   if( rc==SQLITE_OK ){
   132809     rc = findLeafNode(pRtree, iDelete, &pLeaf);
   132810   }
   132811 
   132812   /* Delete the cell in question from the leaf node. */
   132813   if( rc==SQLITE_OK ){
   132814     int rc2;
   132815     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   132816     if( rc==SQLITE_OK ){
   132817       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   132818     }
   132819     rc2 = nodeRelease(pRtree, pLeaf);
   132820     if( rc==SQLITE_OK ){
   132821       rc = rc2;
   132822     }
   132823   }
   132824 
   132825   /* Delete the corresponding entry in the <rtree>_rowid table. */
   132826   if( rc==SQLITE_OK ){
   132827     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   132828     sqlite3_step(pRtree->pDeleteRowid);
   132829     rc = sqlite3_reset(pRtree->pDeleteRowid);
   132830   }
   132831 
   132832   /* Check if the root node now has exactly one child. If so, remove
   132833   ** it, schedule the contents of the child for reinsertion and
   132834   ** reduce the tree height by one.
   132835   **
   132836   ** This is equivalent to copying the contents of the child into
   132837   ** the root node (the operation that Gutman's paper says to perform
   132838   ** in this scenario).
   132839   */
   132840   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   132841     int rc2;
   132842     RtreeNode *pChild;
   132843     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   132844     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   132845     if( rc==SQLITE_OK ){
   132846       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   132847     }
   132848     rc2 = nodeRelease(pRtree, pChild);
   132849     if( rc==SQLITE_OK ) rc = rc2;
   132850     if( rc==SQLITE_OK ){
   132851       pRtree->iDepth--;
   132852       writeInt16(pRoot->zData, pRtree->iDepth);
   132853       pRoot->isDirty = 1;
   132854     }
   132855   }
   132856 
   132857   /* Re-insert the contents of any underfull nodes removed from the tree. */
   132858   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   132859     if( rc==SQLITE_OK ){
   132860       rc = reinsertNodeContent(pRtree, pLeaf);
   132861     }
   132862     pRtree->pDeleted = pLeaf->pNext;
   132863     sqlite3_free(pLeaf);
   132864   }
   132865 
   132866   /* Release the reference to the root node. */
   132867   if( rc==SQLITE_OK ){
   132868     rc = nodeRelease(pRtree, pRoot);
   132869   }else{
   132870     nodeRelease(pRtree, pRoot);
   132871   }
   132872 
   132873   return rc;
   132874 }
   132875 
   132876 /*
   132877 ** The xUpdate method for rtree module virtual tables.
   132878 */
   132879 static int rtreeUpdate(
   132880   sqlite3_vtab *pVtab,
   132881   int nData,
   132882   sqlite3_value **azData,
   132883   sqlite_int64 *pRowid
   132884 ){
   132885   Rtree *pRtree = (Rtree *)pVtab;
   132886   int rc = SQLITE_OK;
   132887   RtreeCell cell;                 /* New cell to insert if nData>1 */
   132888   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
   132889 
   132890   rtreeReference(pRtree);
   132891   assert(nData>=1);
   132892 
   132893   /* Constraint handling. A write operation on an r-tree table may return
   132894   ** SQLITE_CONSTRAINT for two reasons:
   132895   **
   132896   **   1. A duplicate rowid value, or
   132897   **   2. The supplied data violates the "x2>=x1" constraint.
   132898   **
   132899   ** In the first case, if the conflict-handling mode is REPLACE, then
   132900   ** the conflicting row can be removed before proceeding. In the second
   132901   ** case, SQLITE_CONSTRAINT must be returned regardless of the
   132902   ** conflict-handling mode specified by the user.
   132903   */
   132904   if( nData>1 ){
   132905     int ii;
   132906 
   132907     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   132908     assert( nData==(pRtree->nDim*2 + 3) );
   132909     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   132910       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   132911         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
   132912         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
   132913         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   132914           rc = SQLITE_CONSTRAINT;
   132915           goto constraint;
   132916         }
   132917       }
   132918     }else{
   132919       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   132920         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   132921         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   132922         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   132923           rc = SQLITE_CONSTRAINT;
   132924           goto constraint;
   132925         }
   132926       }
   132927     }
   132928 
   132929     /* If a rowid value was supplied, check if it is already present in
   132930     ** the table. If so, the constraint has failed. */
   132931     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
   132932       cell.iRowid = sqlite3_value_int64(azData[2]);
   132933       if( sqlite3_value_type(azData[0])==SQLITE_NULL
   132934        || sqlite3_value_int64(azData[0])!=cell.iRowid
   132935       ){
   132936         int steprc;
   132937         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   132938         steprc = sqlite3_step(pRtree->pReadRowid);
   132939         rc = sqlite3_reset(pRtree->pReadRowid);
   132940         if( SQLITE_ROW==steprc ){
   132941           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
   132942             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
   132943           }else{
   132944             rc = SQLITE_CONSTRAINT;
   132945             goto constraint;
   132946           }
   132947         }
   132948       }
   132949       bHaveRowid = 1;
   132950     }
   132951   }
   132952 
   132953   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   132954   ** record to delete from the r-tree table. The following block does
   132955   ** just that.
   132956   */
   132957   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   132958     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
   132959   }
   132960 
   132961   /* If the azData[] array contains more than one element, elements
   132962   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   132963   ** the r-tree structure.
   132964   */
   132965   if( rc==SQLITE_OK && nData>1 ){
   132966     /* Insert the new record into the r-tree */
   132967     RtreeNode *pLeaf;
   132968 
   132969     /* Figure out the rowid of the new row. */
   132970     if( bHaveRowid==0 ){
   132971       rc = newRowid(pRtree, &cell.iRowid);
   132972     }
   132973     *pRowid = cell.iRowid;
   132974 
   132975     if( rc==SQLITE_OK ){
   132976       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   132977     }
   132978     if( rc==SQLITE_OK ){
   132979       int rc2;
   132980       pRtree->iReinsertHeight = -1;
   132981       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   132982       rc2 = nodeRelease(pRtree, pLeaf);
   132983       if( rc==SQLITE_OK ){
   132984         rc = rc2;
   132985       }
   132986     }
   132987   }
   132988 
   132989 constraint:
   132990   rtreeRelease(pRtree);
   132991   return rc;
   132992 }
   132993 
   132994 /*
   132995 ** The xRename method for rtree module virtual tables.
   132996 */
   132997 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   132998   Rtree *pRtree = (Rtree *)pVtab;
   132999   int rc = SQLITE_NOMEM;
   133000   char *zSql = sqlite3_mprintf(
   133001     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   133002     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   133003     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   133004     , pRtree->zDb, pRtree->zName, zNewName
   133005     , pRtree->zDb, pRtree->zName, zNewName
   133006     , pRtree->zDb, pRtree->zName, zNewName
   133007   );
   133008   if( zSql ){
   133009     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   133010     sqlite3_free(zSql);
   133011   }
   133012   return rc;
   133013 }
   133014 
   133015 static sqlite3_module rtreeModule = {
   133016   0,                          /* iVersion */
   133017   rtreeCreate,                /* xCreate - create a table */
   133018   rtreeConnect,               /* xConnect - connect to an existing table */
   133019   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   133020   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   133021   rtreeDestroy,               /* xDestroy - Drop a table */
   133022   rtreeOpen,                  /* xOpen - open a cursor */
   133023   rtreeClose,                 /* xClose - close a cursor */
   133024   rtreeFilter,                /* xFilter - configure scan constraints */
   133025   rtreeNext,                  /* xNext - advance a cursor */
   133026   rtreeEof,                   /* xEof */
   133027   rtreeColumn,                /* xColumn - read data */
   133028   rtreeRowid,                 /* xRowid - read data */
   133029   rtreeUpdate,                /* xUpdate - write data */
   133030   0,                          /* xBegin - begin transaction */
   133031   0,                          /* xSync - sync transaction */
   133032   0,                          /* xCommit - commit transaction */
   133033   0,                          /* xRollback - rollback transaction */
   133034   0,                          /* xFindFunction - function overloading */
   133035   rtreeRename,                /* xRename - rename the table */
   133036   0,                          /* xSavepoint */
   133037   0,                          /* xRelease */
   133038   0                           /* xRollbackTo */
   133039 };
   133040 
   133041 static int rtreeSqlInit(
   133042   Rtree *pRtree,
   133043   sqlite3 *db,
   133044   const char *zDb,
   133045   const char *zPrefix,
   133046   int isCreate
   133047 ){
   133048   int rc = SQLITE_OK;
   133049 
   133050   #define N_STATEMENT 9
   133051   static const char *azSql[N_STATEMENT] = {
   133052     /* Read and write the xxx_node table */
   133053     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   133054     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   133055     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   133056 
   133057     /* Read and write the xxx_rowid table */
   133058     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   133059     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   133060     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   133061 
   133062     /* Read and write the xxx_parent table */
   133063     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   133064     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   133065     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   133066   };
   133067   sqlite3_stmt **appStmt[N_STATEMENT];
   133068   int i;
   133069 
   133070   pRtree->db = db;
   133071 
   133072   if( isCreate ){
   133073     char *zCreate = sqlite3_mprintf(
   133074 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   133075 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   133076 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
   133077 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   133078       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   133079     );
   133080     if( !zCreate ){
   133081       return SQLITE_NOMEM;
   133082     }
   133083     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   133084     sqlite3_free(zCreate);
   133085     if( rc!=SQLITE_OK ){
   133086       return rc;
   133087     }
   133088   }
   133089 
   133090   appStmt[0] = &pRtree->pReadNode;
   133091   appStmt[1] = &pRtree->pWriteNode;
   133092   appStmt[2] = &pRtree->pDeleteNode;
   133093   appStmt[3] = &pRtree->pReadRowid;
   133094   appStmt[4] = &pRtree->pWriteRowid;
   133095   appStmt[5] = &pRtree->pDeleteRowid;
   133096   appStmt[6] = &pRtree->pReadParent;
   133097   appStmt[7] = &pRtree->pWriteParent;
   133098   appStmt[8] = &pRtree->pDeleteParent;
   133099 
   133100   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   133101     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   133102     if( zSql ){
   133103       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   133104     }else{
   133105       rc = SQLITE_NOMEM;
   133106     }
   133107     sqlite3_free(zSql);
   133108   }
   133109 
   133110   return rc;
   133111 }
   133112 
   133113 /*
   133114 ** The second argument to this function contains the text of an SQL statement
   133115 ** that returns a single integer value. The statement is compiled and executed
   133116 ** using database connection db. If successful, the integer value returned
   133117 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   133118 ** code is returned and the value of *piVal after returning is not defined.
   133119 */
   133120 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   133121   int rc = SQLITE_NOMEM;
   133122   if( zSql ){
   133123     sqlite3_stmt *pStmt = 0;
   133124     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   133125     if( rc==SQLITE_OK ){
   133126       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   133127         *piVal = sqlite3_column_int(pStmt, 0);
   133128       }
   133129       rc = sqlite3_finalize(pStmt);
   133130     }
   133131   }
   133132   return rc;
   133133 }
   133134 
   133135 /*
   133136 ** This function is called from within the xConnect() or xCreate() method to
   133137 ** determine the node-size used by the rtree table being created or connected
   133138 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   133139 ** Otherwise, an SQLite error code is returned.
   133140 **
   133141 ** If this function is being called as part of an xConnect(), then the rtree
   133142 ** table already exists. In this case the node-size is determined by inspecting
   133143 ** the root node of the tree.
   133144 **
   133145 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   133146 ** This ensures that each node is stored on a single database page. If the
   133147 ** database page-size is so large that more than RTREE_MAXCELLS entries
   133148 ** would fit in a single node, use a smaller node-size.
   133149 */
   133150 static int getNodeSize(
   133151   sqlite3 *db,                    /* Database handle */
   133152   Rtree *pRtree,                  /* Rtree handle */
   133153   int isCreate                    /* True for xCreate, false for xConnect */
   133154 ){
   133155   int rc;
   133156   char *zSql;
   133157   if( isCreate ){
   133158     int iPageSize = 0;
   133159     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   133160     rc = getIntFromStmt(db, zSql, &iPageSize);
   133161     if( rc==SQLITE_OK ){
   133162       pRtree->iNodeSize = iPageSize-64;
   133163       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   133164         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   133165       }
   133166     }
   133167   }else{
   133168     zSql = sqlite3_mprintf(
   133169         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   133170         pRtree->zDb, pRtree->zName
   133171     );
   133172     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   133173   }
   133174 
   133175   sqlite3_free(zSql);
   133176   return rc;
   133177 }
   133178 
   133179 /*
   133180 ** This function is the implementation of both the xConnect and xCreate
   133181 ** methods of the r-tree virtual table.
   133182 **
   133183 **   argv[0]   -> module name
   133184 **   argv[1]   -> database name
   133185 **   argv[2]   -> table name
   133186 **   argv[...] -> column names...
   133187 */
   133188 static int rtreeInit(
   133189   sqlite3 *db,                        /* Database connection */
   133190   void *pAux,                         /* One of the RTREE_COORD_* constants */
   133191   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   133192   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   133193   char **pzErr,                       /* OUT: Error message, if any */
   133194   int isCreate                        /* True for xCreate, false for xConnect */
   133195 ){
   133196   int rc = SQLITE_OK;
   133197   Rtree *pRtree;
   133198   int nDb;              /* Length of string argv[1] */
   133199   int nName;            /* Length of string argv[2] */
   133200   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   133201 
   133202   const char *aErrMsg[] = {
   133203     0,                                                    /* 0 */
   133204     "Wrong number of columns for an rtree table",         /* 1 */
   133205     "Too few columns for an rtree table",                 /* 2 */
   133206     "Too many columns for an rtree table"                 /* 3 */
   133207   };
   133208 
   133209   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   133210   if( aErrMsg[iErr] ){
   133211     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   133212     return SQLITE_ERROR;
   133213   }
   133214 
   133215   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   133216 
   133217   /* Allocate the sqlite3_vtab structure */
   133218   nDb = (int)strlen(argv[1]);
   133219   nName = (int)strlen(argv[2]);
   133220   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   133221   if( !pRtree ){
   133222     return SQLITE_NOMEM;
   133223   }
   133224   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   133225   pRtree->nBusy = 1;
   133226   pRtree->base.pModule = &rtreeModule;
   133227   pRtree->zDb = (char *)&pRtree[1];
   133228   pRtree->zName = &pRtree->zDb[nDb+1];
   133229   pRtree->nDim = (argc-4)/2;
   133230   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   133231   pRtree->eCoordType = eCoordType;
   133232   memcpy(pRtree->zDb, argv[1], nDb);
   133233   memcpy(pRtree->zName, argv[2], nName);
   133234 
   133235   /* Figure out the node size to use. */
   133236   rc = getNodeSize(db, pRtree, isCreate);
   133237 
   133238   /* Create/Connect to the underlying relational database schema. If
   133239   ** that is successful, call sqlite3_declare_vtab() to configure
   133240   ** the r-tree table schema.
   133241   */
   133242   if( rc==SQLITE_OK ){
   133243     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   133244       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   133245     }else{
   133246       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   133247       char *zTmp;
   133248       int ii;
   133249       for(ii=4; zSql && ii<argc; ii++){
   133250         zTmp = zSql;
   133251         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   133252         sqlite3_free(zTmp);
   133253       }
   133254       if( zSql ){
   133255         zTmp = zSql;
   133256         zSql = sqlite3_mprintf("%s);", zTmp);
   133257         sqlite3_free(zTmp);
   133258       }
   133259       if( !zSql ){
   133260         rc = SQLITE_NOMEM;
   133261       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   133262         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   133263       }
   133264       sqlite3_free(zSql);
   133265     }
   133266   }
   133267 
   133268   if( rc==SQLITE_OK ){
   133269     *ppVtab = (sqlite3_vtab *)pRtree;
   133270   }else{
   133271     rtreeRelease(pRtree);
   133272   }
   133273   return rc;
   133274 }
   133275 
   133276 
   133277 /*
   133278 ** Implementation of a scalar function that decodes r-tree nodes to
   133279 ** human readable strings. This can be used for debugging and analysis.
   133280 **
   133281 ** The scalar function takes two arguments, a blob of data containing
   133282 ** an r-tree node, and the number of dimensions the r-tree indexes.
   133283 ** For a two-dimensional r-tree structure called "rt", to deserialize
   133284 ** all nodes, a statement like:
   133285 **
   133286 **   SELECT rtreenode(2, data) FROM rt_node;
   133287 **
   133288 ** The human readable string takes the form of a Tcl list with one
   133289 ** entry for each cell in the r-tree node. Each entry is itself a
   133290 ** list, containing the 8-byte rowid/pageno followed by the
   133291 ** <num-dimension>*2 coordinates.
   133292 */
   133293 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   133294   char *zText = 0;
   133295   RtreeNode node;
   133296   Rtree tree;
   133297   int ii;
   133298 
   133299   UNUSED_PARAMETER(nArg);
   133300   memset(&node, 0, sizeof(RtreeNode));
   133301   memset(&tree, 0, sizeof(Rtree));
   133302   tree.nDim = sqlite3_value_int(apArg[0]);
   133303   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   133304   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   133305 
   133306   for(ii=0; ii<NCELL(&node); ii++){
   133307     char zCell[512];
   133308     int nCell = 0;
   133309     RtreeCell cell;
   133310     int jj;
   133311 
   133312     nodeGetCell(&tree, &node, ii, &cell);
   133313     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
   133314     nCell = (int)strlen(zCell);
   133315     for(jj=0; jj<tree.nDim*2; jj++){
   133316       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
   133317       nCell = (int)strlen(zCell);
   133318     }
   133319 
   133320     if( zText ){
   133321       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   133322       sqlite3_free(zText);
   133323       zText = zTextNew;
   133324     }else{
   133325       zText = sqlite3_mprintf("{%s}", zCell);
   133326     }
   133327   }
   133328 
   133329   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   133330 }
   133331 
   133332 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   133333   UNUSED_PARAMETER(nArg);
   133334   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   133335    || sqlite3_value_bytes(apArg[0])<2
   133336   ){
   133337     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   133338   }else{
   133339     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   133340     sqlite3_result_int(ctx, readInt16(zBlob));
   133341   }
   133342 }
   133343 
   133344 /*
   133345 ** Register the r-tree module with database handle db. This creates the
   133346 ** virtual table module "rtree" and the debugging/analysis scalar
   133347 ** function "rtreenode".
   133348 */
   133349 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   133350   const int utf8 = SQLITE_UTF8;
   133351   int rc;
   133352 
   133353   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   133354   if( rc==SQLITE_OK ){
   133355     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   133356   }
   133357   if( rc==SQLITE_OK ){
   133358     void *c = (void *)RTREE_COORD_REAL32;
   133359     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   133360   }
   133361   if( rc==SQLITE_OK ){
   133362     void *c = (void *)RTREE_COORD_INT32;
   133363     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   133364   }
   133365 
   133366   return rc;
   133367 }
   133368 
   133369 /*
   133370 ** A version of sqlite3_free() that can be used as a callback. This is used
   133371 ** in two places - as the destructor for the blob value returned by the
   133372 ** invocation of a geometry function, and as the destructor for the geometry
   133373 ** functions themselves.
   133374 */
   133375 static void doSqlite3Free(void *p){
   133376   sqlite3_free(p);
   133377 }
   133378 
   133379 /*
   133380 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
   133381 ** scalar user function. This C function is the callback used for all such
   133382 ** registered SQL functions.
   133383 **
   133384 ** The scalar user functions return a blob that is interpreted by r-tree
   133385 ** table MATCH operators.
   133386 */
   133387 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   133388   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   133389   RtreeMatchArg *pBlob;
   133390   int nBlob;
   133391 
   133392   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
   133393   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   133394   if( !pBlob ){
   133395     sqlite3_result_error_nomem(ctx);
   133396   }else{
   133397     int i;
   133398     pBlob->magic = RTREE_GEOMETRY_MAGIC;
   133399     pBlob->xGeom = pGeomCtx->xGeom;
   133400     pBlob->pContext = pGeomCtx->pContext;
   133401     pBlob->nParam = nArg;
   133402     for(i=0; i<nArg; i++){
   133403       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   133404     }
   133405     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
   133406   }
   133407 }
   133408 
   133409 /*
   133410 ** Register a new geometry function for use with the r-tree MATCH operator.
   133411 */
   133412 SQLITE_API int sqlite3_rtree_geometry_callback(
   133413   sqlite3 *db,
   133414   const char *zGeom,
   133415   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
   133416   void *pContext
   133417 ){
   133418   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   133419 
   133420   /* Allocate and populate the context object. */
   133421   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   133422   if( !pGeomCtx ) return SQLITE_NOMEM;
   133423   pGeomCtx->xGeom = xGeom;
   133424   pGeomCtx->pContext = pContext;
   133425 
   133426   /* Create the new user-function. Register a destructor function to delete
   133427   ** the context object when it is no longer required.  */
   133428   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   133429       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
   133430   );
   133431 }
   133432 
   133433 #if !SQLITE_CORE
   133434 SQLITE_API int sqlite3_extension_init(
   133435   sqlite3 *db,
   133436   char **pzErrMsg,
   133437   const sqlite3_api_routines *pApi
   133438 ){
   133439   SQLITE_EXTENSION_INIT2(pApi)
   133440   return sqlite3RtreeInit(db);
   133441 }
   133442 #endif
   133443 
   133444 #endif
   133445 
   133446 /************** End of rtree.c ***********************************************/
   133447 /************** Begin file icu.c *********************************************/
   133448 /*
   133449 ** 2007 May 6
   133450 **
   133451 ** The author disclaims copyright to this source code.  In place of
   133452 ** a legal notice, here is a blessing:
   133453 **
   133454 **    May you do good and not evil.
   133455 **    May you find forgiveness for yourself and forgive others.
   133456 **    May you share freely, never taking more than you give.
   133457 **
   133458 *************************************************************************
   133459 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   133460 **
   133461 ** This file implements an integration between the ICU library
   133462 ** ("International Components for Unicode", an open-source library
   133463 ** for handling unicode data) and SQLite. The integration uses
   133464 ** ICU to provide the following to SQLite:
   133465 **
   133466 **   * An implementation of the SQL regexp() function (and hence REGEXP
   133467 **     operator) using the ICU uregex_XX() APIs.
   133468 **
   133469 **   * Implementations of the SQL scalar upper() and lower() functions
   133470 **     for case mapping.
   133471 **
   133472 **   * Integration of ICU and SQLite collation seqences.
   133473 **
   133474 **   * An implementation of the LIKE operator that uses ICU to
   133475 **     provide case-independent matching.
   133476 */
   133477 
   133478 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   133479 
   133480 /* Include ICU headers */
   133481 #include <unicode/utypes.h>
   133482 #include <unicode/uregex.h>
   133483 #include <unicode/ustring.h>
   133484 #include <unicode/ucol.h>
   133485 
   133486 /* #include <assert.h> */
   133487 
   133488 #ifndef SQLITE_CORE
   133489   SQLITE_EXTENSION_INIT1
   133490 #else
   133491 #endif
   133492 
   133493 /*
   133494 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   133495 ** operator.
   133496 */
   133497 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   133498 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   133499 #endif
   133500 
   133501 /*
   133502 ** Version of sqlite3_free() that is always a function, never a macro.
   133503 */
   133504 static void xFree(void *p){
   133505   sqlite3_free(p);
   133506 }
   133507 
   133508 /*
   133509 ** Compare two UTF-8 strings for equality where the first string is
   133510 ** a "LIKE" expression. Return true (1) if they are the same and
   133511 ** false (0) if they are different.
   133512 */
   133513 static int icuLikeCompare(
   133514   const uint8_t *zPattern,   /* LIKE pattern */
   133515   const uint8_t *zString,    /* The UTF-8 string to compare against */
   133516   const UChar32 uEsc         /* The escape character */
   133517 ){
   133518   static const int MATCH_ONE = (UChar32)'_';
   133519   static const int MATCH_ALL = (UChar32)'%';
   133520 
   133521   int iPattern = 0;       /* Current byte index in zPattern */
   133522   int iString = 0;        /* Current byte index in zString */
   133523 
   133524   int prevEscape = 0;     /* True if the previous character was uEsc */
   133525 
   133526   while( zPattern[iPattern]!=0 ){
   133527 
   133528     /* Read (and consume) the next character from the input pattern. */
   133529     UChar32 uPattern;
   133530     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   133531     assert(uPattern!=0);
   133532 
   133533     /* There are now 4 possibilities:
   133534     **
   133535     **     1. uPattern is an unescaped match-all character "%",
   133536     **     2. uPattern is an unescaped match-one character "_",
   133537     **     3. uPattern is an unescaped escape character, or
   133538     **     4. uPattern is to be handled as an ordinary character
   133539     */
   133540     if( !prevEscape && uPattern==MATCH_ALL ){
   133541       /* Case 1. */
   133542       uint8_t c;
   133543 
   133544       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   133545       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   133546       ** test string.
   133547       */
   133548       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   133549         if( c==MATCH_ONE ){
   133550           if( zString[iString]==0 ) return 0;
   133551           U8_FWD_1_UNSAFE(zString, iString);
   133552         }
   133553         iPattern++;
   133554       }
   133555 
   133556       if( zPattern[iPattern]==0 ) return 1;
   133557 
   133558       while( zString[iString] ){
   133559         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   133560           return 1;
   133561         }
   133562         U8_FWD_1_UNSAFE(zString, iString);
   133563       }
   133564       return 0;
   133565 
   133566     }else if( !prevEscape && uPattern==MATCH_ONE ){
   133567       /* Case 2. */
   133568       if( zString[iString]==0 ) return 0;
   133569       U8_FWD_1_UNSAFE(zString, iString);
   133570 
   133571     }else if( !prevEscape && uPattern==uEsc){
   133572       /* Case 3. */
   133573       prevEscape = 1;
   133574 
   133575     }else{
   133576       /* Case 4. */
   133577       UChar32 uString;
   133578       U8_NEXT_UNSAFE(zString, iString, uString);
   133579       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   133580       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   133581       if( uString!=uPattern ){
   133582         return 0;
   133583       }
   133584       prevEscape = 0;
   133585     }
   133586   }
   133587 
   133588   return zString[iString]==0;
   133589 }
   133590 
   133591 /*
   133592 ** Implementation of the like() SQL function.  This function implements
   133593 ** the build-in LIKE operator.  The first argument to the function is the
   133594 ** pattern and the second argument is the string.  So, the SQL statements:
   133595 **
   133596 **       A LIKE B
   133597 **
   133598 ** is implemented as like(B, A). If there is an escape character E,
   133599 **
   133600 **       A LIKE B ESCAPE E
   133601 **
   133602 ** is mapped to like(B, A, E).
   133603 */
   133604 static void icuLikeFunc(
   133605   sqlite3_context *context,
   133606   int argc,
   133607   sqlite3_value **argv
   133608 ){
   133609   const unsigned char *zA = sqlite3_value_text(argv[0]);
   133610   const unsigned char *zB = sqlite3_value_text(argv[1]);
   133611   UChar32 uEsc = 0;
   133612 
   133613   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   133614   ** of deep recursion and N*N behavior in patternCompare().
   133615   */
   133616   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   133617     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   133618     return;
   133619   }
   133620 
   133621 
   133622   if( argc==3 ){
   133623     /* The escape character string must consist of a single UTF-8 character.
   133624     ** Otherwise, return an error.
   133625     */
   133626     int nE= sqlite3_value_bytes(argv[2]);
   133627     const unsigned char *zE = sqlite3_value_text(argv[2]);
   133628     int i = 0;
   133629     if( zE==0 ) return;
   133630     U8_NEXT(zE, i, nE, uEsc);
   133631     if( i!=nE){
   133632       sqlite3_result_error(context,
   133633           "ESCAPE expression must be a single character", -1);
   133634       return;
   133635     }
   133636   }
   133637 
   133638   if( zA && zB ){
   133639     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   133640   }
   133641 }
   133642 
   133643 /*
   133644 ** This function is called when an ICU function called from within
   133645 ** the implementation of an SQL scalar function returns an error.
   133646 **
   133647 ** The scalar function context passed as the first argument is
   133648 ** loaded with an error message based on the following two args.
   133649 */
   133650 static void icuFunctionError(
   133651   sqlite3_context *pCtx,       /* SQLite scalar function context */
   133652   const char *zName,           /* Name of ICU function that failed */
   133653   UErrorCode e                 /* Error code returned by ICU function */
   133654 ){
   133655   char zBuf[128];
   133656   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   133657   zBuf[127] = '\0';
   133658   sqlite3_result_error(pCtx, zBuf, -1);
   133659 }
   133660 
   133661 /*
   133662 ** Function to delete compiled regexp objects. Registered as
   133663 ** a destructor function with sqlite3_set_auxdata().
   133664 */
   133665 static void icuRegexpDelete(void *p){
   133666   URegularExpression *pExpr = (URegularExpression *)p;
   133667   uregex_close(pExpr);
   133668 }
   133669 
   133670 /*
   133671 ** Implementation of SQLite REGEXP operator. This scalar function takes
   133672 ** two arguments. The first is a regular expression pattern to compile
   133673 ** the second is a string to match against that pattern. If either
   133674 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   133675 ** is 1 if the string matches the pattern, or 0 otherwise.
   133676 **
   133677 ** SQLite maps the regexp() function to the regexp() operator such
   133678 ** that the following two are equivalent:
   133679 **
   133680 **     zString REGEXP zPattern
   133681 **     regexp(zPattern, zString)
   133682 **
   133683 ** Uses the following ICU regexp APIs:
   133684 **
   133685 **     uregex_open()
   133686 **     uregex_matches()
   133687 **     uregex_close()
   133688 */
   133689 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   133690   UErrorCode status = U_ZERO_ERROR;
   133691   URegularExpression *pExpr;
   133692   UBool res;
   133693   const UChar *zString = sqlite3_value_text16(apArg[1]);
   133694 
   133695   (void)nArg;  /* Unused parameter */
   133696 
   133697   /* If the left hand side of the regexp operator is NULL,
   133698   ** then the result is also NULL.
   133699   */
   133700   if( !zString ){
   133701     return;
   133702   }
   133703 
   133704   pExpr = sqlite3_get_auxdata(p, 0);
   133705   if( !pExpr ){
   133706     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   133707     if( !zPattern ){
   133708       return;
   133709     }
   133710     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   133711 
   133712     if( U_SUCCESS(status) ){
   133713       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   133714     }else{
   133715       assert(!pExpr);
   133716       icuFunctionError(p, "uregex_open", status);
   133717       return;
   133718     }
   133719   }
   133720 
   133721   /* Configure the text that the regular expression operates on. */
   133722   uregex_setText(pExpr, zString, -1, &status);
   133723   if( !U_SUCCESS(status) ){
   133724     icuFunctionError(p, "uregex_setText", status);
   133725     return;
   133726   }
   133727 
   133728   /* Attempt the match */
   133729   res = uregex_matches(pExpr, 0, &status);
   133730   if( !U_SUCCESS(status) ){
   133731     icuFunctionError(p, "uregex_matches", status);
   133732     return;
   133733   }
   133734 
   133735   /* Set the text that the regular expression operates on to a NULL
   133736   ** pointer. This is not really necessary, but it is tidier than
   133737   ** leaving the regular expression object configured with an invalid
   133738   ** pointer after this function returns.
   133739   */
   133740   uregex_setText(pExpr, 0, 0, &status);
   133741 
   133742   /* Return 1 or 0. */
   133743   sqlite3_result_int(p, res ? 1 : 0);
   133744 }
   133745 
   133746 /*
   133747 ** Implementations of scalar functions for case mapping - upper() and
   133748 ** lower(). Function upper() converts its input to upper-case (ABC).
   133749 ** Function lower() converts to lower-case (abc).
   133750 **
   133751 ** ICU provides two types of case mapping, "general" case mapping and
   133752 ** "language specific". Refer to ICU documentation for the differences
   133753 ** between the two.
   133754 **
   133755 ** To utilise "general" case mapping, the upper() or lower() scalar
   133756 ** functions are invoked with one argument:
   133757 **
   133758 **     upper('ABC') -> 'abc'
   133759 **     lower('abc') -> 'ABC'
   133760 **
   133761 ** To access ICU "language specific" case mapping, upper() or lower()
   133762 ** should be invoked with two arguments. The second argument is the name
   133763 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   133764 ** as the second argument is the same as invoking the 1 argument version
   133765 ** of upper() or lower().
   133766 **
   133767 **     lower('I', 'en_us') -> 'i'
   133768 **     lower('I', 'tr_tr') -> '' (small dotless i)
   133769 **
   133770 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   133771 */
   133772 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   133773   const UChar *zInput;
   133774   UChar *zOutput;
   133775   int nInput;
   133776   int nOutput;
   133777 
   133778   UErrorCode status = U_ZERO_ERROR;
   133779   const char *zLocale = 0;
   133780 
   133781   assert(nArg==1 || nArg==2);
   133782   if( nArg==2 ){
   133783     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   133784   }
   133785 
   133786   zInput = sqlite3_value_text16(apArg[0]);
   133787   if( !zInput ){
   133788     return;
   133789   }
   133790   nInput = sqlite3_value_bytes16(apArg[0]);
   133791 
   133792   nOutput = nInput * 2 + 2;
   133793   zOutput = sqlite3_malloc(nOutput);
   133794   if( !zOutput ){
   133795     return;
   133796   }
   133797 
   133798   if( sqlite3_user_data(p) ){
   133799     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   133800   }else{
   133801     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   133802   }
   133803 
   133804   if( !U_SUCCESS(status) ){
   133805     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   133806     return;
   133807   }
   133808 
   133809   sqlite3_result_text16(p, zOutput, -1, xFree);
   133810 }
   133811 
   133812 /*
   133813 ** Collation sequence destructor function. The pCtx argument points to
   133814 ** a UCollator structure previously allocated using ucol_open().
   133815 */
   133816 static void icuCollationDel(void *pCtx){
   133817   UCollator *p = (UCollator *)pCtx;
   133818   ucol_close(p);
   133819 }
   133820 
   133821 /*
   133822 ** Collation sequence comparison function. The pCtx argument points to
   133823 ** a UCollator structure previously allocated using ucol_open().
   133824 */
   133825 static int icuCollationColl(
   133826   void *pCtx,
   133827   int nLeft,
   133828   const void *zLeft,
   133829   int nRight,
   133830   const void *zRight
   133831 ){
   133832   UCollationResult res;
   133833   UCollator *p = (UCollator *)pCtx;
   133834   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   133835   switch( res ){
   133836     case UCOL_LESS:    return -1;
   133837     case UCOL_GREATER: return +1;
   133838     case UCOL_EQUAL:   return 0;
   133839   }
   133840   assert(!"Unexpected return value from ucol_strcoll()");
   133841   return 0;
   133842 }
   133843 
   133844 /*
   133845 ** Implementation of the scalar function icu_load_collation().
   133846 **
   133847 ** This scalar function is used to add ICU collation based collation
   133848 ** types to an SQLite database connection. It is intended to be called
   133849 ** as follows:
   133850 **
   133851 **     SELECT icu_load_collation(<locale>, <collation-name>);
   133852 **
   133853 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   133854 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   133855 ** collation sequence to create.
   133856 */
   133857 static void icuLoadCollation(
   133858   sqlite3_context *p,
   133859   int nArg,
   133860   sqlite3_value **apArg
   133861 ){
   133862   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   133863   UErrorCode status = U_ZERO_ERROR;
   133864   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   133865   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   133866   UCollator *pUCollator;    /* ICU library collation object */
   133867   int rc;                   /* Return code from sqlite3_create_collation_x() */
   133868 
   133869   assert(nArg==2);
   133870   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   133871   zName = (const char *)sqlite3_value_text(apArg[1]);
   133872 
   133873   if( !zLocale || !zName ){
   133874     return;
   133875   }
   133876 
   133877   pUCollator = ucol_open(zLocale, &status);
   133878   if( !U_SUCCESS(status) ){
   133879     icuFunctionError(p, "ucol_open", status);
   133880     return;
   133881   }
   133882   assert(p);
   133883 
   133884   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   133885       icuCollationColl, icuCollationDel
   133886   );
   133887   if( rc!=SQLITE_OK ){
   133888     ucol_close(pUCollator);
   133889     sqlite3_result_error(p, "Error registering collation function", -1);
   133890   }
   133891 }
   133892 
   133893 /*
   133894 ** Register the ICU extension functions with database db.
   133895 */
   133896 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   133897   struct IcuScalar {
   133898     const char *zName;                        /* Function name */
   133899     int nArg;                                 /* Number of arguments */
   133900     int enc;                                  /* Optimal text encoding */
   133901     void *pContext;                           /* sqlite3_user_data() context */
   133902     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   133903   } scalars[] = {
   133904     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   133905 
   133906     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   133907     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   133908     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   133909     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   133910 
   133911     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   133912     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   133913     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   133914     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   133915 
   133916     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   133917     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   133918 
   133919     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   133920   };
   133921 
   133922   int rc = SQLITE_OK;
   133923   int i;
   133924 
   133925   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
   133926     struct IcuScalar *p = &scalars[i];
   133927     rc = sqlite3_create_function(
   133928         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   133929     );
   133930   }
   133931 
   133932   return rc;
   133933 }
   133934 
   133935 #if !SQLITE_CORE
   133936 SQLITE_API int sqlite3_extension_init(
   133937   sqlite3 *db,
   133938   char **pzErrMsg,
   133939   const sqlite3_api_routines *pApi
   133940 ){
   133941   SQLITE_EXTENSION_INIT2(pApi)
   133942   return sqlite3IcuInit(db);
   133943 }
   133944 #endif
   133945 
   133946 #endif
   133947 
   133948 /************** End of icu.c *************************************************/
   133949 /************** Begin file fts3_icu.c ****************************************/
   133950 /*
   133951 ** 2007 June 22
   133952 **
   133953 ** The author disclaims copyright to this source code.  In place of
   133954 ** a legal notice, here is a blessing:
   133955 **
   133956 **    May you do good and not evil.
   133957 **    May you find forgiveness for yourself and forgive others.
   133958 **    May you share freely, never taking more than you give.
   133959 **
   133960 *************************************************************************
   133961 ** This file implements a tokenizer for fts3 based on the ICU library.
   133962 */
   133963 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   133964 #ifdef SQLITE_ENABLE_ICU
   133965 
   133966 /* #include <assert.h> */
   133967 /* #include <string.h> */
   133968 
   133969 #include <unicode/ubrk.h>
   133970 /* #include <unicode/ucol.h> */
   133971 /* #include <unicode/ustring.h> */
   133972 #include <unicode/utf16.h>
   133973 
   133974 typedef struct IcuTokenizer IcuTokenizer;
   133975 typedef struct IcuCursor IcuCursor;
   133976 
   133977 struct IcuTokenizer {
   133978   sqlite3_tokenizer base;
   133979   char *zLocale;
   133980 };
   133981 
   133982 struct IcuCursor {
   133983   sqlite3_tokenizer_cursor base;
   133984 
   133985   UBreakIterator *pIter;      /* ICU break-iterator object */
   133986   int nChar;                  /* Number of UChar elements in pInput */
   133987   UChar *aChar;               /* Copy of input using utf-16 encoding */
   133988   int *aOffset;               /* Offsets of each character in utf-8 input */
   133989 
   133990   int nBuffer;
   133991   char *zBuffer;
   133992 
   133993   int iToken;
   133994 };
   133995 
   133996 /*
   133997 ** Create a new tokenizer instance.
   133998 */
   133999 static int icuCreate(
   134000   int argc,                            /* Number of entries in argv[] */
   134001   const char * const *argv,            /* Tokenizer creation arguments */
   134002   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   134003 ){
   134004   IcuTokenizer *p;
   134005   int n = 0;
   134006 
   134007   if( argc>0 ){
   134008     n = strlen(argv[0])+1;
   134009   }
   134010   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   134011   if( !p ){
   134012     return SQLITE_NOMEM;
   134013   }
   134014   memset(p, 0, sizeof(IcuTokenizer));
   134015 
   134016   if( n ){
   134017     p->zLocale = (char *)&p[1];
   134018     memcpy(p->zLocale, argv[0], n);
   134019   }
   134020 
   134021   *ppTokenizer = (sqlite3_tokenizer *)p;
   134022 
   134023   return SQLITE_OK;
   134024 }
   134025 
   134026 /*
   134027 ** Destroy a tokenizer
   134028 */
   134029 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   134030   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   134031   sqlite3_free(p);
   134032   return SQLITE_OK;
   134033 }
   134034 
   134035 /*
   134036 ** Prepare to begin tokenizing a particular string.  The input
   134037 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   134038 ** used to incrementally tokenize this string is returned in
   134039 ** *ppCursor.
   134040 */
   134041 static int icuOpen(
   134042   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   134043   const char *zInput,                    /* Input string */
   134044   int nInput,                            /* Length of zInput in bytes */
   134045   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   134046 ){
   134047   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   134048   IcuCursor *pCsr;
   134049 
   134050   const int32_t opt = U_FOLD_CASE_DEFAULT;
   134051   UErrorCode status = U_ZERO_ERROR;
   134052   int nChar;
   134053 
   134054   UChar32 c;
   134055   int iInput = 0;
   134056   int iOut = 0;
   134057 
   134058   *ppCursor = 0;
   134059 
   134060   if( nInput<0 ){
   134061     nInput = strlen(zInput);
   134062   }
   134063   nChar = nInput+1;
   134064   pCsr = (IcuCursor *)sqlite3_malloc(
   134065       sizeof(IcuCursor) +                /* IcuCursor */
   134066       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
   134067       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   134068   );
   134069   if( !pCsr ){
   134070     return SQLITE_NOMEM;
   134071   }
   134072   memset(pCsr, 0, sizeof(IcuCursor));
   134073   pCsr->aChar = (UChar *)&pCsr[1];
   134074   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
   134075 
   134076   pCsr->aOffset[iOut] = iInput;
   134077   U8_NEXT(zInput, iInput, nInput, c);
   134078   while( c>0 ){
   134079     int isError = 0;
   134080     c = u_foldCase(c, opt);
   134081     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   134082     if( isError ){
   134083       sqlite3_free(pCsr);
   134084       return SQLITE_ERROR;
   134085     }
   134086     pCsr->aOffset[iOut] = iInput;
   134087 
   134088     if( iInput<nInput ){
   134089       U8_NEXT(zInput, iInput, nInput, c);
   134090     }else{
   134091       c = 0;
   134092     }
   134093   }
   134094 
   134095   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   134096   if( !U_SUCCESS(status) ){
   134097     sqlite3_free(pCsr);
   134098     return SQLITE_ERROR;
   134099   }
   134100   pCsr->nChar = iOut;
   134101 
   134102   ubrk_first(pCsr->pIter);
   134103   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   134104   return SQLITE_OK;
   134105 }
   134106 
   134107 /*
   134108 ** Close a tokenization cursor previously opened by a call to icuOpen().
   134109 */
   134110 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   134111   IcuCursor *pCsr = (IcuCursor *)pCursor;
   134112   ubrk_close(pCsr->pIter);
   134113   sqlite3_free(pCsr->zBuffer);
   134114   sqlite3_free(pCsr);
   134115   return SQLITE_OK;
   134116 }
   134117 
   134118 /*
   134119 ** Extract the next token from a tokenization cursor.
   134120 */
   134121 static int icuNext(
   134122   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   134123   const char **ppToken,               /* OUT: *ppToken is the token text */
   134124   int *pnBytes,                       /* OUT: Number of bytes in token */
   134125   int *piStartOffset,                 /* OUT: Starting offset of token */
   134126   int *piEndOffset,                   /* OUT: Ending offset of token */
   134127   int *piPosition                     /* OUT: Position integer of token */
   134128 ){
   134129   IcuCursor *pCsr = (IcuCursor *)pCursor;
   134130 
   134131   int iStart = 0;
   134132   int iEnd = 0;
   134133   int nByte = 0;
   134134 
   134135   while( iStart==iEnd ){
   134136     UChar32 c;
   134137 
   134138     iStart = ubrk_current(pCsr->pIter);
   134139     iEnd = ubrk_next(pCsr->pIter);
   134140     if( iEnd==UBRK_DONE ){
   134141       return SQLITE_DONE;
   134142     }
   134143 
   134144     while( iStart<iEnd ){
   134145       int iWhite = iStart;
   134146       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   134147       if( u_isspace(c) ){
   134148         iStart = iWhite;
   134149       }else{
   134150         break;
   134151       }
   134152     }
   134153     assert(iStart<=iEnd);
   134154   }
   134155 
   134156   do {
   134157     UErrorCode status = U_ZERO_ERROR;
   134158     if( nByte ){
   134159       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   134160       if( !zNew ){
   134161         return SQLITE_NOMEM;
   134162       }
   134163       pCsr->zBuffer = zNew;
   134164       pCsr->nBuffer = nByte;
   134165     }
   134166 
   134167     u_strToUTF8(
   134168         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   134169         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   134170         &status                                  /* Output success/failure */
   134171     );
   134172   } while( nByte>pCsr->nBuffer );
   134173 
   134174   *ppToken = pCsr->zBuffer;
   134175   *pnBytes = nByte;
   134176   *piStartOffset = pCsr->aOffset[iStart];
   134177   *piEndOffset = pCsr->aOffset[iEnd];
   134178   *piPosition = pCsr->iToken++;
   134179 
   134180   return SQLITE_OK;
   134181 }
   134182 
   134183 /*
   134184 ** The set of routines that implement the simple tokenizer
   134185 */
   134186 static const sqlite3_tokenizer_module icuTokenizerModule = {
   134187   0,                           /* iVersion */
   134188   icuCreate,                   /* xCreate  */
   134189   icuDestroy,                  /* xCreate  */
   134190   icuOpen,                     /* xOpen    */
   134191   icuClose,                    /* xClose   */
   134192   icuNext,                     /* xNext    */
   134193 };
   134194 
   134195 /*
   134196 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   134197 */
   134198 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   134199   sqlite3_tokenizer_module const**ppModule
   134200 ){
   134201   *ppModule = &icuTokenizerModule;
   134202 }
   134203 
   134204 #endif /* defined(SQLITE_ENABLE_ICU) */
   134205 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134206 
   134207 /************** End of fts3_icu.c ********************************************/
   134208